AnilNiraula commited on
Commit
5ef25e1
·
verified ·
1 Parent(s): f3373ab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -28
app.py CHANGED
@@ -61,9 +61,6 @@ for ticker, data in all_data.items():
61
  series_list.append(s)
62
  adj_close_data = pd.concat(series_list, axis=1) if series_list else pd.DataFrame()
63
 
64
- # Display the first few rows to verify (for debugging; remove in production)
65
- print(adj_close_data.head())
66
-
67
  # Update available symbols to include new tickers
68
  available_symbols = ['TSLA', 'MSFT', 'NVDA', 'GOOG', 'AMZN', 'SPY', 'AAPL', 'META', 'NFLX', 'INTC', 'AMD', 'IBM', 'ORCL', 'CSCO', 'JPM', 'BAC', 'WFC', 'V', 'MA', 'XOM', 'CVX', 'PFE', 'JNJ', 'MRK', 'PLTR', 'SOUN']
69
 
@@ -182,41 +179,59 @@ def generate_response(user_query, enable_thinking=False):
182
  start_date, end_date = parse_dates(user_query)
183
  print(f"Parsed dates: {start_date} to {end_date}") # Debugging
184
  if start_date is None or end_date is None:
185
- return "Invalid date range provided. Please specify a valid range, e.g., 'between 2010 and 2020'."
186
- hist = fetch_stock_data(symbol, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'))
187
- print(f"Data fetched for {symbol}: {'Valid' if hist is not None and not hist.empty else 'Empty/None'}") # Debugging
188
- if "average price" in user_query.lower():
189
- if hist is not None and not hist.empty and 'Close' in hist.columns:
190
- avg_price = hist['Close'].mean()
191
- summary = f"The average adjusted closing price for {symbol} from {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')} is ${avg_price:.2f}."
192
- else:
193
- summary = f"No data available for {symbol} in the specified period."
194
- elif "cagr" in user_query.lower() or "return" in user_query.lower():
195
- growth_rate = calculate_growth_rate(start_date, end_date, symbol)
196
- if growth_rate is not None:
197
- summary = f"The CAGR for {symbol} over the period from {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')} is {growth_rate:.2f}%."
198
- else:
199
- summary = f"No data available for {symbol} in the specified period."
200
- investment_match = re.search(r'\$(\d+)', user_query)
201
- if investment_match:
202
- principal = float(investment_match.group(1))
203
- years = (end_date - start_date).days / 365.25
204
- projected = calculate_investment(principal, years)
205
- summary += f" Projecting ${principal} at 7% return over {years:.1f} years: ${projected:.2f}."
 
206
  else:
207
  summary = "Could not identify a valid stock symbol in the query. Please specify a company or ticker (e.g., 'Tesla' or 'TSLA')."
 
 
208
  system_prompt = (
209
  "You are FinChat, a knowledgeable financial advisor. Always respond in a friendly, professional manner. "
210
  "For greetings like 'Hi' or 'Hello', reply warmly, e.g., 'Hi! I'm FinChat, your financial advisor. What can I help you with today regarding stocks, investments, or advice?' "
211
- "Provide accurate, concise advice based on data."
 
212
  )
213
- # Placeholder for generation logic (tokenize, generate, decode)
214
- return summary or "Please provide a specific stock or investment query."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
  # Gradio interface setup
217
  demo = gr.Interface(
218
  fn=generate_response,
219
- inputs=[gr.Textbox(lines=2, placeholder="Enter your query (e.g., 'Tesla average price between 2010 and 2020')"), gr.Checkbox(label="Enable Thinking")],
220
  outputs="text",
221
  title="FinChat",
222
  description="Ask about stock performance, CAGR, or investments."
 
61
  series_list.append(s)
62
  adj_close_data = pd.concat(series_list, axis=1) if series_list else pd.DataFrame()
63
 
 
 
 
64
  # Update available symbols to include new tickers
65
  available_symbols = ['TSLA', 'MSFT', 'NVDA', 'GOOG', 'AMZN', 'SPY', 'AAPL', 'META', 'NFLX', 'INTC', 'AMD', 'IBM', 'ORCL', 'CSCO', 'JPM', 'BAC', 'WFC', 'V', 'MA', 'XOM', 'CVX', 'PFE', 'JNJ', 'MRK', 'PLTR', 'SOUN']
66
 
 
179
  start_date, end_date = parse_dates(user_query)
180
  print(f"Parsed dates: {start_date} to {end_date}") # Debugging
181
  if start_date is None or end_date is None:
182
+ summary = "Invalid date range provided. Please specify a valid range, e.g., 'between 2010 and 2020'."
183
+ else:
184
+ hist = fetch_stock_data(symbol, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'))
185
+ print(f"Data fetched for {symbol}: { 'Valid' if hist is not None and not hist.empty else 'Empty/None'}") # Debugging
186
+ if "average price" in user_query.lower():
187
+ if hist is not None and not hist.empty and 'Close' in hist.columns:
188
+ avg_price = hist['Close'].mean()
189
+ summary = f"The average adjusted closing price for {symbol} from {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')} is ${avg_price:.2f}."
190
+ else:
191
+ summary = f"No data available for {symbol} in the specified period."
192
+ elif "cagr" in user_query.lower() or "return" in user_query.lower():
193
+ growth_rate = calculate_growth_rate(start_date, end_date, symbol)
194
+ if growth_rate is not None:
195
+ summary = f"The CAGR (geometric average annual return) for {symbol} over the period from {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')} is {growth_rate:.2f}%."
196
+ else:
197
+ summary = f"No data available for {symbol} in the specified period."
198
+ investment_match = re.search(r'\$(\d+)', user_query)
199
+ if investment_match:
200
+ principal = float(investment_match.group(1))
201
+ years = (end_date - start_date).days / 365.25
202
+ projected = calculate_investment(principal, years)
203
+ summary += f" Projecting ${principal} at 7% return over {years:.1f} years: ${projected:.2f}."
204
  else:
205
  summary = "Could not identify a valid stock symbol in the query. Please specify a company or ticker (e.g., 'Tesla' or 'TSLA')."
206
+
207
+ # Enhanced system prompt for better guidance
208
  system_prompt = (
209
  "You are FinChat, a knowledgeable financial advisor. Always respond in a friendly, professional manner. "
210
  "For greetings like 'Hi' or 'Hello', reply warmly, e.g., 'Hi! I'm FinChat, your financial advisor. What can I help you with today regarding stocks, investments, or advice?' "
211
+ "Provide accurate, concise advice based on the provided data summary. If no data is available, suggest alternatives politely. "
212
+ "Use the data summary to inform your response where relevant."
213
  )
214
+
215
+ # Integrate thinking if enabled (simple chain-of-thought prompt)
216
+ thinking_prompt = "Think step by step before responding. " if enable_thinking else ""
217
+
218
+ # Prepare messages for the model
219
+ messages = [
220
+ {"role": "system", "content": system_prompt},
221
+ {"role": "user", "content": f"{thinking_prompt}Query: {user_query}\nData summary: {summary if summary else 'No specific data computed; respond generally based on knowledge.'}"}
222
+ ]
223
+
224
+ # Generate response using the model
225
+ input_ids = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)
226
+ outputs = model.generate(input_ids, max_new_tokens=200, do_sample=True, temperature=0.7)
227
+ response = tokenizer.decode(outputs[0][input_ids.shape[1]:], skip_special_tokens=True)
228
+
229
+ return response
230
 
231
  # Gradio interface setup
232
  demo = gr.Interface(
233
  fn=generate_response,
234
+ inputs=[gr.Textbox(lines=2, placeholder="Enter your query (e.g., 'average return for TSLA stock between 2010 and 2020')"), gr.Checkbox(label="Enable Thinking")],
235
  outputs="text",
236
  title="FinChat",
237
  description="Ask about stock performance, CAGR, or investments."