TDN-M commited on
Commit
15b6b3e
·
verified ·
1 Parent(s): aa90039

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -180
app.py CHANGED
@@ -17,8 +17,7 @@ class FinanceAIAgent:
17
  self.conversation_history = []
18
 
19
  def generate_response(self, prompt: str, context: str = "") -> str:
20
- # Combine context and prompt
21
- full_prompt = f"{context}\n\nUser: {prompt}\nAssistant:"
22
 
23
  try:
24
  chat_completion = self.client.chat.completions.create(
@@ -29,54 +28,54 @@ class FinanceAIAgent:
29
  )
30
  return chat_completion.choices[0].message.content
31
  except Exception as e:
32
- return f"Error generating response: {str(e)}"
33
 
34
  def analyze_portfolio(self, portfolio_data: str) -> str:
35
- prompt = f"""Analyze the following investment portfolio and provide insights:
36
  {portfolio_data}
37
- Include:
38
- 1. Risk assessment
39
- 2. Diversification analysis
40
- 3. Recommendations for rebalancing
41
- 4. Potential areas of concern"""
42
  return self.generate_response(prompt)
43
 
44
  def financial_planning(self, income: float, expenses: List[Dict], goals: List[str]) -> str:
45
- prompt = f"""Create a financial plan based on:
46
- Income: ${income}
47
- Monthly Expenses: {json.dumps(expenses, indent=2)}
48
- Financial Goals: {json.dumps(goals, indent=2)}
49
 
50
- Provide:
51
- 1. Budget breakdown
52
- 2. Savings recommendations
53
- 3. Investment strategies
54
- 4. Timeline for achieving goals"""
55
  return self.generate_response(prompt)
56
 
57
  def market_analysis(self, ticker: str, timeframe: str) -> str:
58
- prompt = f"""Provide a detailed market analysis for {ticker} over {timeframe} timeframe.
59
- Include:
60
- 1. Technical analysis perspectives
61
- 2. Fundamental factors
62
- 3. Market sentiment
63
- 4. Risk factors
64
- 5. Potential catalysts"""
65
  return self.generate_response(prompt)
66
 
67
  def create_finance_ai_interface():
68
  agent = FinanceAIAgent(api_key=os.getenv("GROQ_API_KEY"))
69
 
70
- with gr.Blocks(title="Finance AI Assistant") as interface:
71
- gr.Markdown("# Finance AI Assistant")
72
 
73
- with gr.Tab("Portfolio Analysis"):
74
  portfolio_input = gr.Textbox(
75
- label="Enter portfolio details (ticker symbols and allocations)",
76
  placeholder="AAPL: 25%, MSFT: 25%, GOOGL: 25%, AMZN: 25%"
77
  )
78
- portfolio_button = gr.Button("Analyze Portfolio")
79
- portfolio_output = gr.Textbox(label="Analysis Results")
80
 
81
  portfolio_button.click(
82
  fn=agent.analyze_portfolio,
@@ -84,24 +83,24 @@ def create_finance_ai_interface():
84
  outputs=portfolio_output
85
  )
86
 
87
- with gr.Tab("Financial Planning"):
88
  with gr.Row():
89
- income_input = gr.Number(label="Monthly Income ($)")
90
 
91
  with gr.Row():
92
  expenses_input = gr.Dataframe(
93
- headers=["Category", "Amount"],
94
  datatype=["str", "number"],
95
- label="Monthly Expenses"
96
  )
97
 
98
  goals_input = gr.Textbox(
99
- label="Financial Goals (one per line)",
100
- placeholder="1. Save for retirement\n2. Buy a house\n3. Start a business"
101
  )
102
 
103
- planning_button = gr.Button("Generate Financial Plan")
104
- planning_output = gr.Textbox(label="Financial Plan")
105
 
106
  def process_financial_plan(income, expenses_df, goals):
107
  expenses = expenses_df.to_dict('records')
@@ -114,16 +113,16 @@ def create_finance_ai_interface():
114
  outputs=planning_output
115
  )
116
 
117
- with gr.Tab("Market Analysis"):
118
  with gr.Row():
119
- ticker_input = gr.Textbox(label="Stock Ticker")
120
  timeframe_input = gr.Dropdown(
121
- choices=["1 day", "1 week", "1 month", "3 months", "1 year"],
122
- label="Timeframe"
123
  )
124
 
125
- market_button = gr.Button("Analyze Market")
126
- market_output = gr.Textbox(label="Market Analysis")
127
 
128
  market_button.click(
129
  fn=agent.market_analysis,
@@ -131,10 +130,10 @@ def create_finance_ai_interface():
131
  outputs=market_output
132
  )
133
 
134
- with gr.Tab("AI Chat"):
135
  chatbot = gr.Chatbot()
136
- msg = gr.Textbox(label="Ask anything about finance")
137
- clear = gr.Button("Clear")
138
 
139
  def respond(message, history):
140
  history.append((message, agent.generate_response(message)))
@@ -148,135 +147,4 @@ def create_finance_ai_interface():
148
  # Launch the interface
149
  if __name__ == "__main__":
150
  interface = create_finance_ai_interface()
151
- interface.launch()
152
-
153
- # import gradio as gr
154
- # import groq
155
- # import pandas as pd
156
- # from datetime import datetime
157
- # import plotly.express as px
158
- # import json
159
- # import os
160
- # from typing import List, Dict
161
- # from dotenv import load_dotenv
162
-
163
- # # Load environment variables
164
- # load_dotenv()
165
-
166
- # # Initialize Groq client
167
- # client = groq.Groq(api_key=os.environ["GROQ_API_KEY"])
168
-
169
- # class FinanceAgent:
170
- # def __init__(self):
171
- # self.transactions = []
172
- # self.budgets = {}
173
- # self.goals = []
174
-
175
- # def get_ai_advice(self, query: str) -> str:
176
- # """Get financial advice from LLaMA model via Groq"""
177
- # chat_completion = client.chat.completions.create(
178
- # messages=[{
179
- # "role": "system",
180
- # "content": "You are a financial advisor. Provide clear, actionable advice."
181
- # }, {
182
- # "role": "user",
183
- # "content": query
184
- # }],
185
- # model="llama-3.3-70b-versatile",
186
- # temperature=0.7,
187
- # )
188
- # return chat_completion.choices[0].message.content
189
-
190
- # def add_transaction(self, amount: float, category: str, description: str) -> Dict:
191
- # """Add a new transaction"""
192
- # transaction = {
193
- # "date": datetime.now().strftime("%Y-%m-%d"),
194
- # "amount": amount,
195
- # "category": category,
196
- # "description": description
197
- # }
198
- # self.transactions.append(transaction)
199
- # return {"status": "success", "message": "Transaction added successfully"}
200
-
201
- # def set_budget(self, category: str, amount: float) -> Dict:
202
- # """Set a budget for a category"""
203
- # self.budgets[category] = amount
204
- # return {"status": "success", "message": f"Budget set for {category}"}
205
-
206
- # def get_spending_analysis(self) -> Dict:
207
- # """Analyze spending patterns"""
208
- # df = pd.DataFrame(self.transactions)
209
- # if df.empty:
210
- # return {"status": "error", "message": "No transactions found"}
211
-
212
- # spending_by_category = df.groupby('category')['amount'].sum().to_dict()
213
- # return {
214
- # "status": "success",
215
- # "spending": spending_by_category,
216
- # "total": sum(spending_by_category.values())
217
- # }
218
-
219
- # def create_interface():
220
- # agent = FinanceAgent()
221
-
222
- # with gr.Blocks(title="Personal Finance Assistant") as interface:
223
- # gr.Markdown("# Personal Finance Assistant")
224
-
225
- # with gr.Tab("Transactions"):
226
- # with gr.Row():
227
- # amount_input = gr.Number(label="Amount")
228
- # category_input = gr.Dropdown(
229
- # choices=["Groceries", "Utilities", "Entertainment", "Transportation", "Other"],
230
- # label="Category"
231
- # )
232
- # description_input = gr.Textbox(label="Description")
233
- # add_btn = gr.Button("Add Transaction")
234
- # transaction_output = gr.JSON(label="Result")
235
-
236
- # add_btn.click(
237
- # fn=agent.add_transaction,
238
- # inputs=[amount_input, category_input, description_input],
239
- # outputs=transaction_output
240
- # )
241
-
242
- # with gr.Tab("Budgeting"):
243
- # with gr.Row():
244
- # budget_category = gr.Dropdown(
245
- # choices=["Groceries", "Utilities", "Entertainment", "Transportation", "Other"],
246
- # label="Category"
247
- # )
248
- # budget_amount = gr.Number(label="Budget Amount")
249
- # set_budget_btn = gr.Button("Set Budget")
250
- # budget_output = gr.JSON(label="Result")
251
-
252
- # set_budget_btn.click(
253
- # fn=agent.set_budget,
254
- # inputs=[budget_category, budget_amount],
255
- # outputs=budget_output
256
- # )
257
-
258
- # with gr.Tab("Analysis"):
259
- # analyze_btn = gr.Button("Analyze Spending")
260
- # spending_output = gr.JSON(label="Spending Analysis")
261
-
262
- # analyze_btn.click(
263
- # fn=agent.get_spending_analysis,
264
- # outputs=spending_output
265
- # )
266
-
267
- # with gr.Tab("AI Advisor"):
268
- # query_input = gr.Textbox(label="Ask for financial advice")
269
- # advice_btn = gr.Button("Get Advice")
270
- # advice_output = gr.Textbox(label="AI Advice")
271
-
272
- # advice_btn.click(
273
- # fn=agent.get_ai_advice,
274
- # inputs=query_input,
275
- # outputs=advice_output
276
- # )
277
-
278
- # return interface
279
-
280
- # if __name__ == "__main__":
281
- # interface = create_interface()
282
- # interface.launch()
 
17
  self.conversation_history = []
18
 
19
  def generate_response(self, prompt: str, context: str = "") -> str:
20
+ full_prompt = f"{context}\n\nNgười dùng: {prompt}\nTrợ lý:"
 
21
 
22
  try:
23
  chat_completion = self.client.chat.completions.create(
 
28
  )
29
  return chat_completion.choices[0].message.content
30
  except Exception as e:
31
+ return f"Lỗi khi tạo phản hồi: {str(e)}"
32
 
33
  def analyze_portfolio(self, portfolio_data: str) -> str:
34
+ prompt = f"""Phân tích danh mục đầu sau và cung cấp thông tin chi tiết:
35
  {portfolio_data}
36
+ Bao gồm:
37
+ 1. Đánh giá rủi ro
38
+ 2. Phân tích đa dạng hóa
39
+ 3. Đề xuất điều chỉnh danh mục
40
+ 4. Các lĩnh vực tiềm ẩn rủi ro"""
41
  return self.generate_response(prompt)
42
 
43
  def financial_planning(self, income: float, expenses: List[Dict], goals: List[str]) -> str:
44
+ prompt = f"""Lập kế hoạch tài chính dựa trên:
45
+ Thu nhập: ${income}
46
+ Chi phí hàng tháng: {json.dumps(expenses, indent=2)}
47
+ Mục tiêu tài chính: {json.dumps(goals, indent=2)}
48
 
49
+ Cung cấp:
50
+ 1. Phân tích ngân sách
51
+ 2. Đề xuất tiết kiệm
52
+ 3. Chiến lược đầu tư
53
+ 4. Thời gian đạt được mục tiêu"""
54
  return self.generate_response(prompt)
55
 
56
  def market_analysis(self, ticker: str, timeframe: str) -> str:
57
+ prompt = f"""Cung cấp phân tích thị trường chi tiết cho {ticker} trong khung thời gian {timeframe}.
58
+ Bao gồm:
59
+ 1. Góc nhìn phân tích kỹ thuật
60
+ 2. Yếu tố cơ bản
61
+ 3. Tâm lý thị trường
62
+ 4. Yếu tố rủi ro
63
+ 5. Các yếu tố tiềm năng ảnh hưởng"""
64
  return self.generate_response(prompt)
65
 
66
  def create_finance_ai_interface():
67
  agent = FinanceAIAgent(api_key=os.getenv("GROQ_API_KEY"))
68
 
69
+ with gr.Blocks(title="Trợ lý Tài chính AI") as interface:
70
+ gr.Markdown("# Trợ lý Tài chính AI")
71
 
72
+ with gr.Tab("Phân tích Danh mục"):
73
  portfolio_input = gr.Textbox(
74
+ label="Nhập chi tiết danh mục ( cổ phiếu và tỷ lệ phân bổ)",
75
  placeholder="AAPL: 25%, MSFT: 25%, GOOGL: 25%, AMZN: 25%"
76
  )
77
+ portfolio_button = gr.Button("Phân tích Danh mục")
78
+ portfolio_output = gr.Textbox(label="Kết quả Phân tích")
79
 
80
  portfolio_button.click(
81
  fn=agent.analyze_portfolio,
 
83
  outputs=portfolio_output
84
  )
85
 
86
+ with gr.Tab("Lập Kế hoạch Tài chính"):
87
  with gr.Row():
88
+ income_input = gr.Number(label="Thu nhập Hàng tháng ($)")
89
 
90
  with gr.Row():
91
  expenses_input = gr.Dataframe(
92
+ headers=["Danh mục", "Số tiền"],
93
  datatype=["str", "number"],
94
+ label="Chi phí Hàng tháng"
95
  )
96
 
97
  goals_input = gr.Textbox(
98
+ label="Mục tiêu Tài chính (mỗi dòng một mục tiêu)",
99
+ placeholder="1. Tiết kiệm cho nghỉ hưu\n2. Mua nhà\n3. Khởi nghiệp"
100
  )
101
 
102
+ planning_button = gr.Button("Tạo Kế hoạch Tài chính")
103
+ planning_output = gr.Textbox(label="Kế hoạch Tài chính")
104
 
105
  def process_financial_plan(income, expenses_df, goals):
106
  expenses = expenses_df.to_dict('records')
 
113
  outputs=planning_output
114
  )
115
 
116
+ with gr.Tab("Phân tích Thị trường"):
117
  with gr.Row():
118
+ ticker_input = gr.Textbox(label=" Cổ phiếu")
119
  timeframe_input = gr.Dropdown(
120
+ choices=["1 ngày", "1 tuần", "1 tháng", "3 tháng", "1 năm"],
121
+ label="Khung Thời gian"
122
  )
123
 
124
+ market_button = gr.Button("Phân tích Thị trường")
125
+ market_output = gr.Textbox(label="Kết quả Phân tích Thị trường")
126
 
127
  market_button.click(
128
  fn=agent.market_analysis,
 
130
  outputs=market_output
131
  )
132
 
133
+ with gr.Tab("Trò chuyện AI"):
134
  chatbot = gr.Chatbot()
135
+ msg = gr.Textbox(label="Hỏi bất kỳ điều gì về tài chính")
136
+ clear = gr.Button("Xóa")
137
 
138
  def respond(message, history):
139
  history.append((message, agent.generate_response(message)))
 
147
  # Launch the interface
148
  if __name__ == "__main__":
149
  interface = create_finance_ai_interface()
150
+ interface.launch()