Knight-coderr commited on
Commit
6ed8b7e
·
verified ·
1 Parent(s): debb65c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -31
app.py CHANGED
@@ -5,27 +5,25 @@ from textblob import TextBlob
5
  import joblib
6
  import matplotlib.pyplot as plt
7
  from datetime import datetime
 
8
 
9
  # Function to load stock data using yfinance
10
  @st.cache_data(ttl=86400)
11
  def load_stock_data(tickers, start_date, end_date):
12
- import yfinance as yf
13
- import pandas as pd
14
-
15
- data = yf.download(tickers, start=start_date, end=end_date, group_by='ticker', auto_adjust=True)
16
-
17
- all_data = []
18
- for ticker in tickers:
19
- df = data[ticker].copy().reset_index()
20
- df['Stock Name'] = ticker
21
- all_data.append(df)
22
-
23
- merged_data = pd.concat(all_data, ignore_index=True)
24
  return merged_data
25
 
26
-
27
  tickers = ['TSLA', 'MSFT', 'PG', 'META', 'AMZN', 'GOOG', 'AMD', 'AAPL', 'NFLX', 'TSM',
28
- 'KO', 'F', 'COST', 'DIS', 'VZ', 'CRM', 'INTC', 'BA', 'BX', 'NOC', 'PYPL', 'ENPH', 'NIO', 'ZS', 'XPEV']
29
  start_date = (datetime.today() - pd.DateOffset(years=1)).strftime('%Y-%m-%d')
30
  end_date = datetime.today().strftime('%Y-%m-%d')
31
 
@@ -51,7 +49,7 @@ daily_sentiment = tweets_data.groupby(['Date', 'Stock Name']).mean(numeric_only=
51
  daily_sentiment['Date'] = pd.to_datetime(daily_sentiment['Date'])
52
 
53
  # Merge stock data with sentiment data
54
- merged_data = pd.merge(data, daily_sentiment, how='left', on=['Date', 'Stock Name'])
55
 
56
  # Fill missing sentiment values with 0 (neutral sentiment)
57
  merged_data['Sentiment'] = merged_data['Sentiment'].fillna(0)
@@ -110,7 +108,7 @@ st.write(latest_data_df)
110
  st.write("Use the inputs above to predict the next days close prices of the stock.")
111
  if st.button("Predict"):
112
  predictions = []
113
- latest_date = datetime.datetime.now()
114
 
115
  for i in range(days_to_predict):
116
  X_future = pd.DataFrame({
@@ -139,22 +137,20 @@ if st.button("Predict"):
139
  })
140
 
141
  st.subheader("Predicted Prices")
142
- # st.write(prediction_df)
143
  st.dataframe(prediction_df)
 
144
  # Plot predictions using Plotly
145
- import plotly.express as px
146
- fig = px.line(prediction_df, x='Date', y='Predicted Close Price',
147
- markers=True, title=f"{selected_stock} Predicted Close Prices")
148
  st.plotly_chart(fig, use_container_width=True)
149
 
150
  # ----------------------------------------
151
  # Enhanced Visualizations
152
- st.header(" Enhanced Stock Analysis")
153
- stock_history = data[data['Stock Name'] == selected_stock]
154
 
155
  # Date filter slider
156
- min_date = pd.to_datetime(data['Date'].min()).date()
157
- max_date = pd.to_datetime(data['Date'].max()).date()
158
 
159
  date_range = st.slider(
160
  "Select Date Range for Visualizations",
@@ -166,30 +162,29 @@ if st.button("Predict"):
166
 
167
  filtered_data = stock_history[(stock_history['Date'] >= date_range[0]) & (stock_history['Date'] <= date_range[1])]
168
 
169
- with st.expander(" Price vs Sentiment Trend"):
170
  fig1 = px.line(filtered_data, x='Date', y=['Close', 'Sentiment'],
171
  labels={'value': 'Price / Sentiment', 'variable': 'Metric'},
172
  title=f"{selected_stock} - Close Price & Sentiment")
173
  st.plotly_chart(fig1, use_container_width=True)
174
 
175
- with st.expander(" Volatility Over Time"):
176
  fig2 = px.line(filtered_data, x='Date', y='Volatility',
177
  title=f"{selected_stock} - 7-Day Rolling Volatility")
178
  st.plotly_chart(fig2, use_container_width=True)
179
 
180
- with st.expander(" Moving Averages (MA7 vs MA14)"):
181
- fig3 = px.line(filtered_data, x='Date',
182
- y=['MA7', 'MA14'],
183
  labels={'value': 'Price', 'variable': 'Moving Average'},
184
  title=f"{selected_stock} - Moving Averages")
185
  st.plotly_chart(fig3, use_container_width=True)
186
 
187
- with st.expander(" Daily Price Change"):
188
  fig4 = px.line(filtered_data, x='Date', y='Daily_Change',
189
  title=f"{selected_stock} - Daily Price Change")
190
  st.plotly_chart(fig4, use_container_width=True)
191
 
192
- with st.expander(" Sentiment Distribution"):
193
  fig5 = px.histogram(filtered_data, x='Sentiment', nbins=30,
194
  title=f"{selected_stock} - Sentiment Score Distribution")
195
  st.plotly_chart(fig5, use_container_width=True)
 
5
  import joblib
6
  import matplotlib.pyplot as plt
7
  from datetime import datetime
8
+ import plotly.express as px
9
 
10
  # Function to load stock data using yfinance
11
  @st.cache_data(ttl=86400)
12
  def load_stock_data(tickers, start_date, end_date):
13
+ with st.spinner('Downloading stock data...'):
14
+ data = yf.download(tickers, start=start_date, end=end_date, group_by='ticker', auto_adjust=True)
15
+
16
+ all_data = []
17
+ for ticker in tickers:
18
+ df = data[ticker].copy().reset_index()
19
+ df['Stock Name'] = ticker
20
+ all_data.append(df)
21
+
22
+ merged_data = pd.concat(all_data, ignore_index=True)
 
 
23
  return merged_data
24
 
 
25
  tickers = ['TSLA', 'MSFT', 'PG', 'META', 'AMZN', 'GOOG', 'AMD', 'AAPL', 'NFLX', 'TSM',
26
+ 'KO', 'F', 'COST', 'DIS', 'VZ', 'CRM', 'INTC', 'BA', 'BX', 'NOC', 'PYPL', 'ENPH', 'NIO', 'ZS', 'XPEV']
27
  start_date = (datetime.today() - pd.DateOffset(years=1)).strftime('%Y-%m-%d')
28
  end_date = datetime.today().strftime('%Y-%m-%d')
29
 
 
49
  daily_sentiment['Date'] = pd.to_datetime(daily_sentiment['Date'])
50
 
51
  # Merge stock data with sentiment data
52
+ merged_data = pd.merge(stock_data, daily_sentiment, how='left', on=['Date', 'Stock Name'])
53
 
54
  # Fill missing sentiment values with 0 (neutral sentiment)
55
  merged_data['Sentiment'] = merged_data['Sentiment'].fillna(0)
 
108
  st.write("Use the inputs above to predict the next days close prices of the stock.")
109
  if st.button("Predict"):
110
  predictions = []
111
+ latest_date = datetime.now()
112
 
113
  for i in range(days_to_predict):
114
  X_future = pd.DataFrame({
 
137
  })
138
 
139
  st.subheader("Predicted Prices")
 
140
  st.dataframe(prediction_df)
141
+
142
  # Plot predictions using Plotly
143
+ fig = px.line(prediction_df, x='Date', y='Predicted Close Price', markers=True, title=f"{selected_stock} Predicted Close Prices")
 
 
144
  st.plotly_chart(fig, use_container_width=True)
145
 
146
  # ----------------------------------------
147
  # Enhanced Visualizations
148
+ st.header("Enhanced Stock Analysis")
149
+ stock_history = merged_data[merged_data['Stock Name'] == selected_stock]
150
 
151
  # Date filter slider
152
+ min_date = pd.to_datetime(merged_data['Date'].min()).date()
153
+ max_date = pd.to_datetime(merged_data['Date'].max()).date()
154
 
155
  date_range = st.slider(
156
  "Select Date Range for Visualizations",
 
162
 
163
  filtered_data = stock_history[(stock_history['Date'] >= date_range[0]) & (stock_history['Date'] <= date_range[1])]
164
 
165
+ with st.expander("Price vs Sentiment Trend"):
166
  fig1 = px.line(filtered_data, x='Date', y=['Close', 'Sentiment'],
167
  labels={'value': 'Price / Sentiment', 'variable': 'Metric'},
168
  title=f"{selected_stock} - Close Price & Sentiment")
169
  st.plotly_chart(fig1, use_container_width=True)
170
 
171
+ with st.expander("Volatility Over Time"):
172
  fig2 = px.line(filtered_data, x='Date', y='Volatility',
173
  title=f"{selected_stock} - 7-Day Rolling Volatility")
174
  st.plotly_chart(fig2, use_container_width=True)
175
 
176
+ with st.expander("Moving Averages (MA7 vs MA14)"):
177
+ fig3 = px.line(filtered_data, x='Date', y=['MA7', 'MA14'],
 
178
  labels={'value': 'Price', 'variable': 'Moving Average'},
179
  title=f"{selected_stock} - Moving Averages")
180
  st.plotly_chart(fig3, use_container_width=True)
181
 
182
+ with st.expander("Daily Price Change"):
183
  fig4 = px.line(filtered_data, x='Date', y='Daily_Change',
184
  title=f"{selected_stock} - Daily Price Change")
185
  st.plotly_chart(fig4, use_container_width=True)
186
 
187
+ with st.expander("Sentiment Distribution"):
188
  fig5 = px.histogram(filtered_data, x='Sentiment', nbins=30,
189
  title=f"{selected_stock} - Sentiment Score Distribution")
190
  st.plotly_chart(fig5, use_container_width=True)