finance_agent / app.py
TDN-M's picture
Update app.py
15b6b3e verified
import gradio as gr
import groq
import os
import json
from typing import Dict, List
import pandas as pd
from datetime import datetime
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
class FinanceAIAgent:
def __init__(self, api_key: str):
self.client = groq.Client(api_key=api_key)
self.model = "llama-3.3-70b-versatile"
self.conversation_history = []
def generate_response(self, prompt: str, context: str = "") -> str:
full_prompt = f"{context}\n\nNgười dùng: {prompt}\nTrợ lý:"
try:
chat_completion = self.client.chat.completions.create(
model=self.model,
messages=[{"role": "user", "content": full_prompt}],
temperature=0.7,
max_tokens=1000
)
return chat_completion.choices[0].message.content
except Exception as e:
return f"Lỗi khi tạo phản hồi: {str(e)}"
def analyze_portfolio(self, portfolio_data: str) -> str:
prompt = f"""Phân tích danh mục đầu tư sau và cung cấp thông tin chi tiết:
{portfolio_data}
Bao gồm:
1. Đánh giá rủi ro
2. Phân tích đa dạng hóa
3. Đề xuất điều chỉnh danh mục
4. Các lĩnh vực tiềm ẩn rủi ro"""
return self.generate_response(prompt)
def financial_planning(self, income: float, expenses: List[Dict], goals: List[str]) -> str:
prompt = f"""Lập kế hoạch tài chính dựa trên:
Thu nhập: ${income}
Chi phí hàng tháng: {json.dumps(expenses, indent=2)}
Mục tiêu tài chính: {json.dumps(goals, indent=2)}
Cung cấp:
1. Phân tích ngân sách
2. Đề xuất tiết kiệm
3. Chiến lược đầu tư
4. Thời gian đạt được mục tiêu"""
return self.generate_response(prompt)
def market_analysis(self, ticker: str, timeframe: str) -> str:
prompt = f"""Cung cấp phân tích thị trường chi tiết cho {ticker} trong khung thời gian {timeframe}.
Bao gồm:
1. Góc nhìn phân tích kỹ thuật
2. Yếu tố cơ bản
3. Tâm lý thị trường
4. Yếu tố rủi ro
5. Các yếu tố tiềm năng ảnh hưởng"""
return self.generate_response(prompt)
def create_finance_ai_interface():
agent = FinanceAIAgent(api_key=os.getenv("GROQ_API_KEY"))
with gr.Blocks(title="Trợ lý Tài chính AI") as interface:
gr.Markdown("# Trợ lý Tài chính AI")
with gr.Tab("Phân tích Danh mục"):
portfolio_input = gr.Textbox(
label="Nhập chi tiết danh mục (mã cổ phiếu và tỷ lệ phân bổ)",
placeholder="AAPL: 25%, MSFT: 25%, GOOGL: 25%, AMZN: 25%"
)
portfolio_button = gr.Button("Phân tích Danh mục")
portfolio_output = gr.Textbox(label="Kết quả Phân tích")
portfolio_button.click(
fn=agent.analyze_portfolio,
inputs=[portfolio_input],
outputs=portfolio_output
)
with gr.Tab("Lập Kế hoạch Tài chính"):
with gr.Row():
income_input = gr.Number(label="Thu nhập Hàng tháng ($)")
with gr.Row():
expenses_input = gr.Dataframe(
headers=["Danh mục", "Số tiền"],
datatype=["str", "number"],
label="Chi phí Hàng tháng"
)
goals_input = gr.Textbox(
label="Mục tiêu Tài chính (mỗi dòng một mục tiêu)",
placeholder="1. Tiết kiệm cho nghỉ hưu\n2. Mua nhà\n3. Khởi nghiệp"
)
planning_button = gr.Button("Tạo Kế hoạch Tài chính")
planning_output = gr.Textbox(label="Kế hoạch Tài chính")
def process_financial_plan(income, expenses_df, goals):
expenses = expenses_df.to_dict('records')
goals_list = [g.strip() for g in goals.split('\n') if g.strip()]
return agent.financial_planning(income, expenses, goals_list)
planning_button.click(
fn=process_financial_plan,
inputs=[income_input, expenses_input, goals_input],
outputs=planning_output
)
with gr.Tab("Phân tích Thị trường"):
with gr.Row():
ticker_input = gr.Textbox(label="Mã Cổ phiếu")
timeframe_input = gr.Dropdown(
choices=["1 ngày", "1 tuần", "1 tháng", "3 tháng", "1 năm"],
label="Khung Thời gian"
)
market_button = gr.Button("Phân tích Thị trường")
market_output = gr.Textbox(label="Kết quả Phân tích Thị trường")
market_button.click(
fn=agent.market_analysis,
inputs=[ticker_input, timeframe_input],
outputs=market_output
)
with gr.Tab("Trò chuyện AI"):
chatbot = gr.Chatbot()
msg = gr.Textbox(label="Hỏi bất kỳ điều gì về tài chính")
clear = gr.Button("Xóa")
def respond(message, history):
history.append((message, agent.generate_response(message)))
return "", history
msg.submit(respond, [msg, chatbot], [msg, chatbot])
clear.click(lambda: None, None, chatbot, queue=False)
return interface
# Launch the interface
if __name__ == "__main__":
interface = create_finance_ai_interface()
interface.launch()