Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,7 +8,6 @@ import torch
|
|
| 8 |
import yfinance as yf
|
| 9 |
from functools import lru_cache
|
| 10 |
import pandas as pd
|
| 11 |
-
from dateutil import parser # Added for flexible date parsing
|
| 12 |
|
| 13 |
# Define the list of tickers
|
| 14 |
tickers = ['TSLA', 'PLTR', 'SOUN', 'MSFT']
|
|
@@ -88,51 +87,153 @@ def fetch_stock_data(symbol, start_date, end_date):
|
|
| 88 |
return None
|
| 89 |
|
| 90 |
def parse_dates(query):
|
| 91 |
-
query_lower = query.lower()
|
| 92 |
-
start_date = None
|
| 93 |
-
end_date = None
|
| 94 |
-
|
| 95 |
# Handle year ranges like "between 2010 and 2020"
|
| 96 |
-
range_match = re.search(r'between\s+(\d{4})\s+and\s+(\d{4})',
|
| 97 |
if range_match:
|
| 98 |
start_year = int(range_match.group(1))
|
| 99 |
end_year = int(range_match.group(2))
|
| 100 |
-
|
| 101 |
-
end_date = datetime(end_year, 12, 31)
|
| 102 |
-
|
| 103 |
-
if not range_match:
|
| 104 |
-
# Add pattern for "from X to Y"
|
| 105 |
-
range_match = re.search(r'from\s+(\d{4})\s+to\s+(\d{4})', query_lower)
|
| 106 |
-
if range_match:
|
| 107 |
-
start_year = int(range_match.group(1))
|
| 108 |
-
end_year = int(range_match.group(2))
|
| 109 |
start_date = datetime(start_year, 1, 1)
|
| 110 |
end_date = datetime(end_year, 12, 31)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
import yfinance as yf
|
| 9 |
from functools import lru_cache
|
| 10 |
import pandas as pd
|
|
|
|
| 11 |
|
| 12 |
# Define the list of tickers
|
| 13 |
tickers = ['TSLA', 'PLTR', 'SOUN', 'MSFT']
|
|
|
|
| 87 |
return None
|
| 88 |
|
| 89 |
def parse_dates(query):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
# Handle year ranges like "between 2010 and 2020"
|
| 91 |
+
range_match = re.search(r'between\s+(\d{4})\s+and\s+(\d{4})', query.lower())
|
| 92 |
if range_match:
|
| 93 |
start_year = int(range_match.group(1))
|
| 94 |
end_year = int(range_match.group(2))
|
| 95 |
+
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
start_date = datetime(start_year, 1, 1)
|
| 97 |
end_date = datetime(end_year, 12, 31)
|
| 98 |
+
if start_date >= end_date:
|
| 99 |
+
raise ValueError("Start date must be before end date")
|
| 100 |
+
return start_date, end_date
|
| 101 |
+
except ValueError as e:
|
| 102 |
+
print(f"Date parsing error: {e}")
|
| 103 |
+
return None, None
|
| 104 |
+
# Fallback to period parsing for recent periods
|
| 105 |
+
period_match = re.search(r'(\d+)\s*(year|month|week|day)s?', query.lower())
|
| 106 |
+
if period_match:
|
| 107 |
+
num = int(period_match.group(1))
|
| 108 |
+
unit = period_match.group(2)
|
| 109 |
+
if unit == 'year':
|
| 110 |
+
period = timedelta(days=365 * num)
|
| 111 |
+
elif unit == 'month':
|
| 112 |
+
period = timedelta(days=30 * num)
|
| 113 |
+
elif unit == 'week':
|
| 114 |
+
period = timedelta(weeks=num)
|
| 115 |
+
elif unit == 'day':
|
| 116 |
+
period = timedelta(days=num)
|
| 117 |
+
else:
|
| 118 |
+
period = timedelta(days=365)
|
| 119 |
+
end_date = datetime.now()
|
| 120 |
+
start_date = end_date - period
|
| 121 |
+
return start_date, end_date
|
| 122 |
+
# Default to 1 year
|
| 123 |
+
end_date = datetime.now()
|
| 124 |
+
start_date = end_date - timedelta(days=365)
|
| 125 |
+
return start_date, end_date
|
| 126 |
|
| 127 |
+
def find_closest_symbol(input_symbol):
|
| 128 |
+
input_symbol = input_symbol.upper()
|
| 129 |
+
# Check if input matches a company name
|
| 130 |
+
for company, ticker in company_to_ticker.items():
|
| 131 |
+
if company in input_symbol.lower():
|
| 132 |
+
return ticker
|
| 133 |
+
# Fallback to ticker matching
|
| 134 |
+
closest = difflib.get_close_matches(input_symbol, available_symbols, n=1, cutoff=0.6)
|
| 135 |
+
return closest[0] if closest else None
|
| 136 |
|
| 137 |
+
def calculate_growth_rate(start_date, end_date, symbol):
|
| 138 |
+
hist = fetch_stock_data(symbol, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'))
|
| 139 |
+
if hist is None or hist.empty or 'Close' not in hist.columns:
|
| 140 |
+
print(f"No valid data for {symbol} from {start_date} to {end_date}")
|
| 141 |
+
return None
|
| 142 |
+
beginning_value = hist.iloc[0]['Close']
|
| 143 |
+
ending_value = hist.iloc[-1]['Close']
|
| 144 |
+
years = (end_date - start_date).days / 365.25
|
| 145 |
+
if years <= 0:
|
| 146 |
+
return 0
|
| 147 |
+
total_return = ending_value / beginning_value
|
| 148 |
+
cagr = total_return ** (1 / years) - 1
|
| 149 |
+
return cagr * 100
|
| 150 |
|
| 151 |
+
def calculate_investment(principal, years, annual_return=0.07):
|
| 152 |
+
return principal * (1 + annual_return) ** years
|
| 153 |
+
|
| 154 |
+
model_name = "HuggingFaceTB/SmolLM-135M-Instruct"
|
| 155 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 156 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 157 |
+
model_name,
|
| 158 |
+
device_map="auto",
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
def generate_response(user_query, enable_thinking=False):
|
| 162 |
+
print(f"Processing query: {user_query}") # Debugging
|
| 163 |
+
stock_keywords = ['stock', 'growth', 'investment', 'price', 'return', 'cagr']
|
| 164 |
+
is_stock_query = any(keyword in user_query.lower() for keyword in stock_keywords)
|
| 165 |
+
print(f"Is stock query: {is_stock_query}") # Debugging
|
| 166 |
+
summary = ""
|
| 167 |
+
if is_stock_query:
|
| 168 |
+
# Try to find symbol from company name or ticker
|
| 169 |
+
symbol = None
|
| 170 |
+
for company, ticker in company_to_ticker.items():
|
| 171 |
+
if company in user_query.lower():
|
| 172 |
+
symbol = ticker
|
| 173 |
+
break
|
| 174 |
+
if not symbol:
|
| 175 |
+
symbol_match = re.search(r'\b([A-Z]{1,5})\b', user_query.upper())
|
| 176 |
+
symbol = find_closest_symbol(symbol_match.group(1)) if symbol_match else None
|
| 177 |
+
print(f"Detected symbol: {symbol}") # Debugging
|
| 178 |
+
if symbol:
|
| 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."
|
| 238 |
+
)
|
| 239 |
+
demo.launch()
|