swayam-the-coder commited on
Commit
e29c0a9
ยท
verified ยท
1 Parent(s): b8ae9ec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -158
app.py CHANGED
@@ -1,16 +1,15 @@
1
  import streamlit as st
 
2
  import pandas as pd
3
- import numpy as np
4
  from prophet import Prophet
5
  import plotly.graph_objs as go
6
  import google.generativeai as genai
7
- import requests
8
- from datetime import datetime
9
 
10
  # Streamlit app details
11
  st.set_page_config(page_title="TechyTrade", layout="wide")
12
 
13
- # Custom CSS from HF version
14
  st.markdown("""
15
  <style>
16
  @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;700&display=swap');
@@ -39,11 +38,11 @@ st.markdown("""
39
  </style>
40
  """, unsafe_allow_html=True)
41
 
42
- # Sidebar inputs
43
  with st.sidebar:
44
  st.title("๐Ÿ“Š TechyTrade")
45
- ticker = st.text_input("Enter a stock ticker (e.g. AAPL) ๐Ÿท๏ธ", "AAPL").upper().strip()
46
- period = st.selectbox("Enter a time frame โณ", ("1M", "6M", "1Y", "5Y"), index=0)
47
  forecast_period = st.slider("Select forecast period (days) ๐Ÿ”ฎ", min_value=1, max_value=365, value=30)
48
  st.write("Select Technical Indicators:")
49
  sma_checkbox = st.checkbox("Simple Moving Average (SMA)")
@@ -54,27 +53,21 @@ with st.sidebar:
54
  google_api_key = st.text_input("Enter your Google API Key ๐Ÿ”‘", type="password")
55
  button = st.button("Submit ๐Ÿš€")
56
 
57
- # Load generative model (cache)
58
  @st.cache_resource
59
  def load_model(api_key):
60
  genai.configure(api_key=api_key)
61
  return genai.GenerativeModel('gemini-1.5-flash')
62
 
63
- # Generate AI-based reasons
64
- def generate_reasons(fig_desc, stock_info, price_info, biz_metrics, api_key):
65
  model = load_model(api_key)
66
- prompt = f"Based on the following stock price graph description:\n\n{fig_desc}\n\n and the tables:\n\n{stock_info}\n\n and\n\n{price_info}\n\n and\n\n{biz_metrics}\n\n Analyze the trends and give recommendations and insights."
67
  response = model.generate_content(prompt)
68
  return response.text
69
 
70
- # Format large numbers with suffix
71
  def format_value(value):
72
- if value == "N/A" or value is None:
73
- return "N/A"
74
- try:
75
- value = float(value)
76
- except:
77
- return "N/A"
78
  suffixes = ["", "K", "M", "B", "T"]
79
  suffix_index = 0
80
  while value >= 1000 and suffix_index < len(suffixes) - 1:
@@ -82,7 +75,7 @@ def format_value(value):
82
  suffix_index += 1
83
  return f"${value:.1f}{suffixes[suffix_index]}"
84
 
85
- # Technical indicator calculations (same as HF version)
86
  def calculate_sma(data, window):
87
  return data.rolling(window=window).mean()
88
 
@@ -110,103 +103,38 @@ def calculate_bollinger_bands(data, window):
110
  lower_band = sma - (std * 2)
111
  return upper_band, lower_band
112
 
113
- # Alpha Vantage stock data retrieval function
114
- def get_stock_data_alpha_vantage(ticker, period):
115
- # Use TIME_SERIES_DAILY or TIME_SERIES_WEEKLY depending on period
116
- api_key = "656HG6SEB317EFAB"
117
- function = "TIME_SERIES_DAILY"
118
- interval_days = 1
119
- if period == "1M":
120
- outputsize = "compact" # last 100 days approx
121
- elif period == "6M":
122
- outputsize = "full"
123
- elif period == "1Y":
124
- outputsize = "full"
125
- elif period == "5Y":
126
- # Alpha Vantage free API doesn't support 5Y directly, fallback to full daily
127
- outputsize = "full"
128
- else:
129
- outputsize = "compact"
130
-
131
- url = f"https://www.alphavantage.co/query?function={function}&symbol={ticker}&outputsize={outputsize}&apikey={api_key}"
132
- response = requests.get(url)
133
- data = response.json()
134
-
135
- if "Time Series (Daily)" not in data:
136
- raise ValueError(f"Error fetching data for ticker {ticker}: {data.get('Note') or data.get('Error Message') or 'Unknown error'}")
137
-
138
- df = pd.DataFrame.from_dict(data["Time Series (Daily)"], orient='index')
139
- df = df.rename(columns={
140
- '1. open': 'Open',
141
- '2. high': 'High',
142
- '3. low': 'Low',
143
- '4. close': 'Close',
144
- '5. volume': 'Volume'
145
- })
146
- df.index = pd.to_datetime(df.index)
147
- df = df.sort_index()
148
-
149
- # Filter date range based on selected period
150
- now = pd.Timestamp.now()
151
- if period == "1M":
152
- cutoff = now - pd.DateOffset(months=1)
153
- elif period == "6M":
154
- cutoff = now - pd.DateOffset(months=6)
155
- elif period == "1Y":
156
- cutoff = now - pd.DateOffset(years=1)
157
- elif period == "5Y":
158
- cutoff = now - pd.DateOffset(years=5)
159
- else:
160
- cutoff = df.index.min()
161
-
162
- df = df[df.index >= cutoff]
163
-
164
- # Convert columns to float
165
- for col in ['Open', 'High', 'Low', 'Close', 'Volume']:
166
- df[col] = df[col].astype(float)
167
-
168
- return df
169
-
170
- # Dummy function to simulate getting stock info (Alpha Vantage does not provide all info)
171
- def get_stock_info_alpha_vantage(ticker):
172
- # Return dummy or partial info for demo
173
- return {
174
- "country": "N/A",
175
- "sector": "N/A",
176
- "industry": "N/A",
177
- "marketCap": "N/A",
178
- "enterpriseValue": "N/A",
179
- "fullTimeEmployees": "N/A",
180
- "currentPrice": "N/A",
181
- "previousClose": "N/A",
182
- "dayHigh": "N/A",
183
- "dayLow": "N/A",
184
- "fiftyTwoWeekHigh": "N/A",
185
- "fiftyTwoWeekLow": "N/A",
186
- "forwardEps": "N/A",
187
- "forwardPE": "N/A",
188
- "pegRatio": "N/A",
189
- "dividendRate": "N/A",
190
- "dividendYield": "N/A",
191
- "recommendationKey": "N/A",
192
- "longName": ticker
193
- }
194
-
195
- # Main execution on button click
196
  if button:
197
- if not ticker:
198
  st.error("Please provide a valid stock ticker.")
199
- elif not google_api_key:
200
  st.error("Please provide a valid Google API Key.")
201
  else:
202
  try:
203
- with st.spinner("Fetching and processing data..."):
204
- # Get stock data from Alpha Vantage
205
- history = get_stock_data_alpha_vantage(ticker, "656HG6SEB317EFAB", period)
206
-
207
- st.subheader(f"{ticker} - {ticker}")
208
-
209
- # Plot historical Close price
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  fig = go.Figure()
211
  fig.add_trace(go.Scatter(x=history.index, y=history['Close'], mode='lines', name='Close Price'))
212
 
@@ -214,17 +142,21 @@ if button:
214
  if sma_checkbox:
215
  sma = calculate_sma(history['Close'], window=20)
216
  fig.add_trace(go.Scatter(x=history.index, y=sma, mode='lines', name='SMA (20)'))
 
217
  if ema_checkbox:
218
  ema = calculate_ema(history['Close'], window=20)
219
  fig.add_trace(go.Scatter(x=history.index, y=ema, mode='lines', name='EMA (20)'))
 
220
  if rsi_checkbox:
221
  rsi = calculate_rsi(history['Close'], window=14)
222
  fig.add_trace(go.Scatter(x=history.index, y=rsi, mode='lines', name='RSI (14)', yaxis='y2'))
223
  fig.update_layout(yaxis2=dict(title='RSI', overlaying='y', side='right'))
 
224
  if macd_checkbox:
225
  macd, signal = calculate_macd(history['Close'])
226
  fig.add_trace(go.Scatter(x=history.index, y=macd, mode='lines', name='MACD'))
227
  fig.add_trace(go.Scatter(x=history.index, y=signal, mode='lines', name='Signal Line'))
 
228
  if bollinger_checkbox:
229
  upper_band, lower_band = calculate_bollinger_bands(history['Close'], window=20)
230
  fig.add_trace(go.Scatter(x=history.index, y=upper_band, mode='lines', name='Upper Band'))
@@ -238,79 +170,101 @@ if button:
238
  )
239
  st.plotly_chart(fig, use_container_width=True)
240
 
241
- # Get dummy stock info (replace with real API if available)
242
- info = get_stock_info_alpha_vantage(ticker)
243
-
244
  col1, col2, col3 = st.columns(3)
245
 
246
- # Stock info dataframe
 
 
 
 
 
 
 
247
  stock_info = [
248
  ("Stock Info", "Value"),
249
- ("Country", info["country"]),
250
- ("Sector", info["sector"]),
251
- ("Industry", info["industry"]),
252
- ("Market Cap", info["marketCap"]),
253
- ("Enterprise Value", info["enterpriseValue"]),
254
- ("Employees", info["fullTimeEmployees"])
255
  ]
256
- df_stock_info = pd.DataFrame(stock_info[1:], columns=stock_info[0])
257
- col1.dataframe(df_stock_info, width=400, hide_index=True)
258
-
259
- # Price info dataframe (mostly N/A here)
 
 
 
 
 
 
 
 
260
  price_info = [
261
  ("Price Info", "Value"),
262
- ("Current Price", info["currentPrice"]),
263
- ("Previous Close", info["previousClose"]),
264
- ("Day High", info["dayHigh"]),
265
- ("Day Low", info["dayLow"]),
266
- ("52 Week High", info["fiftyTwoWeekHigh"]),
267
- ("52 Week Low", info["fiftyTwoWeekLow"])
268
  ]
269
- df_price_info = pd.DataFrame(price_info[1:], columns=price_info[0])
270
- col2.dataframe(df_price_info, width=400, hide_index=True)
271
-
272
- # Business metrics dataframe (mostly N/A here)
 
 
 
 
 
 
 
 
273
  biz_metrics = [
274
  ("Business Metrics", "Value"),
275
- ("EPS (FWD)", info["forwardEps"]),
276
- ("P/E (FWD)", info["forwardPE"]),
277
- ("PEG Ratio", info["pegRatio"]),
278
- ("Div Rate (FWD)", info["dividendRate"]),
279
- ("Div Yield (FWD)", info["dividendYield"]),
280
- ("Recommendation", info["recommendationKey"])
281
  ]
282
- df_biz_metrics = pd.DataFrame(biz_metrics[1:], columns=biz_metrics[0])
283
- col3.dataframe(df_biz_metrics, width=400, hide_index=True)
 
284
 
285
- # Prepare data for forecasting
286
- forecast_df = history.reset_index()[['index', 'Close']].rename(columns={'index': 'ds', 'Close': 'y'})
 
 
 
287
 
288
  m = Prophet(daily_seasonality=True)
289
- m.fit(forecast_df)
290
 
291
  future = m.make_future_dataframe(periods=forecast_period)
292
  forecast = m.predict(future)
293
 
294
- st.subheader("Forecasted Stock Price")
295
  fig2 = go.Figure()
296
  fig2.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat'], mode='lines', name='Forecast'))
297
- fig2.add_trace(go.Scatter(x=forecast_df['ds'], y=forecast_df['y'], mode='lines', name='Actual'))
 
298
  fig2.update_layout(
299
- title="Prophet Forecast",
300
  xaxis_title="Date",
301
- yaxis_title="Price"
 
302
  )
303
  st.plotly_chart(fig2, use_container_width=True)
304
 
305
- # Generate AI-based reasons using Google Gemini
306
- fig_description = "Line chart of stock closing prices and technical indicators as shown above."
307
- reasons = generate_reasons(fig_description, df_stock_info.to_string(), df_price_info.to_string(), df_biz_metrics.to_string(), google_api_key)
308
 
309
- st.subheader("AI-based Stock Analysis and Recommendations")
310
  st.write(reasons)
311
 
312
  except Exception as e:
313
- st.error(f"Error: {e}")
314
-
315
- else:
316
- st.info("Enter details and click Submit to start analyzing the stock.")
 
1
  import streamlit as st
2
+ import yfinance as yf
3
  import pandas as pd
 
4
  from prophet import Prophet
5
  import plotly.graph_objs as go
6
  import google.generativeai as genai
7
+ import numpy as np
 
8
 
9
  # Streamlit app details
10
  st.set_page_config(page_title="TechyTrade", layout="wide")
11
 
12
+ # Custom CSS
13
  st.markdown("""
14
  <style>
15
  @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;700&display=swap');
 
38
  </style>
39
  """, unsafe_allow_html=True)
40
 
41
+ # Sidebar
42
  with st.sidebar:
43
  st.title("๐Ÿ“Š TechyTrade")
44
+ ticker = st.text_input("Enter a stock ticker (e.g. AAPL) ๐Ÿท๏ธ", "AAPL")
45
+ period = st.selectbox("Enter a time frame โณ", ("1D", "5D", "1M", "6M", "YTD", "1Y", "5Y"), index=2)
46
  forecast_period = st.slider("Select forecast period (days) ๐Ÿ”ฎ", min_value=1, max_value=365, value=30)
47
  st.write("Select Technical Indicators:")
48
  sma_checkbox = st.checkbox("Simple Moving Average (SMA)")
 
53
  google_api_key = st.text_input("Enter your Google API Key ๐Ÿ”‘", type="password")
54
  button = st.button("Submit ๐Ÿš€")
55
 
56
+ # Load generative model
57
  @st.cache_resource
58
  def load_model(api_key):
59
  genai.configure(api_key=api_key)
60
  return genai.GenerativeModel('gemini-1.5-flash')
61
 
62
+ # Function to generate reasons using the generative model
63
+ def generate_reasons(fig, stock_info, price_info, biz_metrics, api_key):
64
  model = load_model(api_key)
65
+ prompt = f"Based on the following stock price graph description:\n\n{fig}\n\n and the tables:\n\n{stock_info}\n\n and\n\n{price_info}\n\n and\n\n{biz_metrics}\n\n and analyze the trends and give recommendations and insights."
66
  response = model.generate_content(prompt)
67
  return response.text
68
 
69
+ # Function to format large numbers
70
  def format_value(value):
 
 
 
 
 
 
71
  suffixes = ["", "K", "M", "B", "T"]
72
  suffix_index = 0
73
  while value >= 1000 and suffix_index < len(suffixes) - 1:
 
75
  suffix_index += 1
76
  return f"${value:.1f}{suffixes[suffix_index]}"
77
 
78
+ # Technical Indicators Functions
79
  def calculate_sma(data, window):
80
  return data.rolling(window=window).mean()
81
 
 
103
  lower_band = sma - (std * 2)
104
  return upper_band, lower_band
105
 
106
+ # If Submit button is clicked
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  if button:
108
+ if not ticker.strip():
109
  st.error("Please provide a valid stock ticker.")
110
+ elif not google_api_key.strip():
111
  st.error("Please provide a valid Google API Key.")
112
  else:
113
  try:
114
+ with st.spinner('Please wait...'):
115
+ # Retrieve stock data
116
+ stock = yf.Ticker(ticker)
117
+ info = stock.info
118
+
119
+ st.subheader(f"{ticker} - {info.get('longName', 'N/A')}")
120
+
121
+ # Plot historical stock price data
122
+ if period == "1D":
123
+ history = stock.history(period="1d", interval="1h")
124
+ elif period == "5D":
125
+ history = stock.history(period="5d", interval="1d")
126
+ elif period == "1M":
127
+ history = stock.history(period="1mo", interval="1d")
128
+ elif period == "6M":
129
+ history = stock.history(period="6mo", interval="1wk")
130
+ elif period == "YTD":
131
+ history = stock.history(period="ytd", interval="1mo")
132
+ elif period == "1Y":
133
+ history = stock.history(period="1y", interval="1mo")
134
+ elif period == "5Y":
135
+ history = stock.history(period="5y", interval="3mo")
136
+
137
+ # Create a plotly figure
138
  fig = go.Figure()
139
  fig.add_trace(go.Scatter(x=history.index, y=history['Close'], mode='lines', name='Close Price'))
140
 
 
142
  if sma_checkbox:
143
  sma = calculate_sma(history['Close'], window=20)
144
  fig.add_trace(go.Scatter(x=history.index, y=sma, mode='lines', name='SMA (20)'))
145
+
146
  if ema_checkbox:
147
  ema = calculate_ema(history['Close'], window=20)
148
  fig.add_trace(go.Scatter(x=history.index, y=ema, mode='lines', name='EMA (20)'))
149
+
150
  if rsi_checkbox:
151
  rsi = calculate_rsi(history['Close'], window=14)
152
  fig.add_trace(go.Scatter(x=history.index, y=rsi, mode='lines', name='RSI (14)', yaxis='y2'))
153
  fig.update_layout(yaxis2=dict(title='RSI', overlaying='y', side='right'))
154
+
155
  if macd_checkbox:
156
  macd, signal = calculate_macd(history['Close'])
157
  fig.add_trace(go.Scatter(x=history.index, y=macd, mode='lines', name='MACD'))
158
  fig.add_trace(go.Scatter(x=history.index, y=signal, mode='lines', name='Signal Line'))
159
+
160
  if bollinger_checkbox:
161
  upper_band, lower_band = calculate_bollinger_bands(history['Close'], window=20)
162
  fig.add_trace(go.Scatter(x=history.index, y=upper_band, mode='lines', name='Upper Band'))
 
170
  )
171
  st.plotly_chart(fig, use_container_width=True)
172
 
 
 
 
173
  col1, col2, col3 = st.columns(3)
174
 
175
+ # Display stock information as a dataframe
176
+ country = info.get('country', 'N/A')
177
+ sector = info.get('sector', 'N/A')
178
+ industry = info.get('industry', 'N/A')
179
+ market_cap = info.get('marketCap', 'N/A')
180
+ ent_value = info.get('enterpriseValue', 'N/A')
181
+ employees = info.get('fullTimeEmployees', 'N/A')
182
+
183
  stock_info = [
184
  ("Stock Info", "Value"),
185
+ ("Country ", country),
186
+ ("Sector ", sector),
187
+ ("Industry ", industry),
188
+ ("Market Cap ", format_value(market_cap)),
189
+ ("Enterprise Value ", format_value(ent_value)),
190
+ ("Employees ", employees)
191
  ]
192
+
193
+ df = pd.DataFrame(stock_info[1:], columns=stock_info[0])
194
+ col1.dataframe(df, width=400, hide_index=True)
195
+
196
+ # Display price information as a dataframe
197
+ current_price = info.get('currentPrice', 'N/A')
198
+ prev_close = info.get('previousClose', 'N/A')
199
+ day_high = info.get('dayHigh', 'N/A')
200
+ day_low = info.get('dayLow', 'N/A')
201
+ ft_week_high = info.get('fiftyTwoWeekHigh', 'N/A')
202
+ ft_week_low = info.get('fiftyTwoWeekLow', 'N/A')
203
+
204
  price_info = [
205
  ("Price Info", "Value"),
206
+ ("Current Price ", f"${current_price:.2f}"),
207
+ ("Previous Close ", f"${prev_close:.2f}"),
208
+ ("Day High ", f"${day_high:.2f}"),
209
+ ("Day Low ", f"${day_low:.2f}"),
210
+ ("52 Week High ", f"${ft_week_high:.2f}"),
211
+ ("52 Week Low ", f"${ft_week_low:.2f}")
212
  ]
213
+
214
+ df = pd.DataFrame(price_info[1:], columns=price_info[0])
215
+ col2.dataframe(df, width=400, hide_index=True)
216
+
217
+ # Display business metrics as a dataframe
218
+ forward_eps = info.get('forwardEps', 'N/A')
219
+ forward_pe = info.get('forwardPE', 'N/A')
220
+ peg_ratio = info.get('pegRatio', 'N/A')
221
+ dividend_rate = info.get('dividendRate', 'N/A')
222
+ dividend_yield = info.get('dividendYield', 'N/A')
223
+ recommendation = info.get('recommendationKey', 'N/A')
224
+
225
  biz_metrics = [
226
  ("Business Metrics", "Value"),
227
+ ("EPS (FWD) ", f"{forward_eps:.2f}"),
228
+ ("P/E (FWD) ", f"{forward_pe:.2f}"),
229
+ ("PEG Ratio ", f"{peg_ratio:.2f}"),
230
+ ("Div Rate (FWD) ", f"${dividend_rate:.2f}"),
231
+ ("Div Yield (FWD) ", f"{dividend_yield * 100:.2f}%"),
232
+ ("Recommendation ", recommendation.capitalize())
233
  ]
234
+
235
+ df = pd.DataFrame(biz_metrics[1:], columns=biz_metrics[0])
236
+ col3.dataframe(df, width=400, hide_index=True)
237
 
238
+ # Forecasting
239
+ st.subheader("Stock Price Forecast ๐Ÿ”ฎ")
240
+ df_forecast = history.reset_index()[['Date', 'Close']]
241
+ df_forecast['Date'] = pd.to_datetime(df_forecast['Date']).dt.tz_localize(None) # Remove timezone information
242
+ df_forecast.columns = ['ds', 'y']
243
 
244
  m = Prophet(daily_seasonality=True)
245
+ m.fit(df_forecast)
246
 
247
  future = m.make_future_dataframe(periods=forecast_period)
248
  forecast = m.predict(future)
249
 
 
250
  fig2 = go.Figure()
251
  fig2.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat'], mode='lines', name='Forecast'))
252
+ fig2.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat_upper'], mode='lines', name='Upper Confidence Interval', line=dict(dash='dash')))
253
+ fig2.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat_lower'], mode='lines', name='Lower Confidence Interval', line=dict(dash='dash')))
254
  fig2.update_layout(
255
+ title=f"Stock Price Forecast for {ticker}",
256
  xaxis_title="Date",
257
+ yaxis_title="Predicted Close Price",
258
+ hovermode="x unified"
259
  )
260
  st.plotly_chart(fig2, use_container_width=True)
261
 
262
+ # Generate reasons based on forecast
263
+ graph_description = f"The stock price forecast graph for {ticker} shows the predicted close prices along with the upper and lower confidence intervals for the next {forecast_period} days."
264
+ reasons = generate_reasons(fig, stock_info, price_info, biz_metrics, google_api_key)
265
 
266
+ st.subheader("Investment Analysis")
267
  st.write(reasons)
268
 
269
  except Exception as e:
270
+ st.exception(f"An error occurred: {e}")