Spaces:
Sleeping
Sleeping
File size: 5,996 Bytes
c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e c30d6e8 15b6b3e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
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() |