Ritvik commited on
Commit
65c6d06
Β·
1 Parent(s): 004ad50

Updated app

Browse files
Files changed (2) hide show
  1. app.py +35 -29
  2. sentiment_data.db +0 -0
app.py CHANGED
@@ -110,35 +110,22 @@ def save_to_db(df, ticker):
110
 
111
 
112
  def plot_sentiment(df, ticker, interval):
113
- """ Generates sentiment trend plots while ensuring correct date range. """
114
  if df.empty:
115
  return None
116
 
117
  df['datetime'] = pd.to_datetime(df['datetime'])
118
  df = df.set_index('datetime')
119
 
120
- # βœ… Ensure the graph strictly uses only the filtered range
121
- min_date = df.index.min()
122
- max_date = df.index.max()
123
- print(f"πŸ“… Graph Showing Data from {min_date} to {max_date}") # Debugging
124
 
125
- df_filtered = df.loc[min_date:max_date]
126
-
127
- if interval == 'h':
128
- df_grouped = df_filtered.resample('h').mean(numeric_only=True).dropna()
129
- elif interval == 'D':
130
- df_grouped = df_filtered.resample('D').mean(numeric_only=True).dropna()
131
- else:
132
- df_grouped = df_filtered
133
-
134
- df_grouped['rolling_avg'] = df_grouped['sentiment_score'].rolling(5, min_periods=1).mean()
135
-
136
- fig = px.line(df_grouped, x=df_grouped.index, y='sentiment_score',
137
- labels={"sentiment_score": "Sentiment Score"},
138
- title=f"{ticker} Sentiment Trends ({interval.capitalize()})")
139
-
140
- fig.add_scatter(x=df_grouped.index, y=df_grouped['rolling_avg'], mode='lines', name='Rolling Avg')
141
 
 
 
 
142
  return fig
143
 
144
 
@@ -155,6 +142,7 @@ def analyze_stock_sentiment(ticker, days):
155
 
156
  df_news = parse_news(news_table)
157
 
 
158
  days = int(days)
159
  today = datetime.datetime.today()
160
  start_date = today - datetime.timedelta(days=days)
@@ -164,12 +152,13 @@ def analyze_stock_sentiment(ticker, days):
164
  df_news['datetime'] = pd.to_datetime(df_news['datetime'])
165
  df_news = df_news[df_news['datetime'] >= start_date]
166
 
167
- print(f"πŸ“Š Filtered News Count: {len(df_news)}") # Debugging
168
-
169
  if df_news.empty:
170
  return f"⚠️ No news found for {ticker.upper()} in the last {days} days.", None, None, None
171
 
172
  df_scored = score_news(df_news).sort_values(by="datetime", ascending=False)
 
 
 
173
  save_to_db(df_scored, ticker.upper())
174
 
175
  fig_hourly = plot_sentiment(df_scored, ticker, interval='h')
@@ -178,14 +167,31 @@ def analyze_stock_sentiment(ticker, days):
178
  return f"βœ… Analysis for {ticker.upper()} (Last {days} Days) Complete!", df_scored, fig_hourly, fig_daily
179
 
180
 
181
- # βœ… Gradio UI
182
- iface = gr.Interface(
183
- fn=analyze_stock_sentiment,
184
- inputs=[gr.Textbox(label="Stock Ticker"), gr.Slider(1, 15, 7, label="Days of News History")],
185
- outputs=[gr.Textbox(label="Status"), gr.Dataframe(), gr.Plot(), gr.Plot()]
186
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
  # βœ… Keeps the App Running on Hugging Face
189
  if __name__ == "__main__":
190
  print("πŸš€ App is running on Hugging Face Spaces...")
191
  iface.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
110
 
111
 
112
  def plot_sentiment(df, ticker, interval):
113
+ """ Generates sentiment trend plots with correct filtering """
114
  if df.empty:
115
  return None
116
 
117
  df['datetime'] = pd.to_datetime(df['datetime'])
118
  df = df.set_index('datetime')
119
 
120
+ # βœ… Resample only within the available range
121
+ df = df.resample(interval).mean(numeric_only=True).dropna()
 
 
122
 
123
+ # βœ… Use rolling average to smooth the graph
124
+ df['rolling_avg'] = df['sentiment_score'].rolling(5, min_periods=1).mean()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
+ fig = px.line(df, x=df.index, y=['sentiment_score', 'rolling_avg'],
127
+ labels={"value": "Sentiment Score"},
128
+ title=f"{ticker} {interval.capitalize()} Sentiment Trends")
129
  return fig
130
 
131
 
 
142
 
143
  df_news = parse_news(news_table)
144
 
145
+ # βœ… Convert `days` to an integer and filter news based on the correct time range
146
  days = int(days)
147
  today = datetime.datetime.today()
148
  start_date = today - datetime.timedelta(days=days)
 
152
  df_news['datetime'] = pd.to_datetime(df_news['datetime'])
153
  df_news = df_news[df_news['datetime'] >= start_date]
154
 
 
 
155
  if df_news.empty:
156
  return f"⚠️ No news found for {ticker.upper()} in the last {days} days.", None, None, None
157
 
158
  df_scored = score_news(df_news).sort_values(by="datetime", ascending=False)
159
+
160
+ print(f"πŸ“Š Filtered News Count: {len(df_scored)}") # Debugging
161
+
162
  save_to_db(df_scored, ticker.upper())
163
 
164
  fig_hourly = plot_sentiment(df_scored, ticker, interval='h')
 
167
  return f"βœ… Analysis for {ticker.upper()} (Last {days} Days) Complete!", df_scored, fig_hourly, fig_daily
168
 
169
 
170
+ # Gradio Interface
171
+ with gr.Blocks(title="πŸ“ˆ Stock News Sentiment Analyzer") as iface:
172
+ with gr.Row():
173
+ gr.Markdown("## πŸ“ˆStock News Sentiment Analyzer")
174
+ gr.Markdown("Analyze stock news sentiment using VADER and TextBlob.")
175
+
176
+ ticker_dropdown = gr.Dropdown(choices=["AAPL", "TSLA", "AMZN", "MSFT"], label="Stock Ticker")
177
+ days_slider = gr.Slider(minimum=1, maximum=30, step=1, label="Days of News History", value=7, interactive=True)
178
+ status = gr.Textbox(label="Status", interactive=False)
179
+
180
+ with gr.Row():
181
+ submit_btn = gr.Button("Analyze", variant="primary")
182
+ clear_btn = gr.Button("Clear", variant="secondary")
183
+
184
+ table = gr.Dataframe(label="Sentiment Analysis", interactive=False)
185
+ hourly_plot = gr.Plot(label="Hourly Sentiment Scores")
186
+ daily_plot = gr.Plot(label="Daily Sentiment Scores")
187
+
188
+ submit_btn.click(fn=analyze_stock_sentiment, inputs=[ticker_dropdown, days_slider],
189
+ outputs=[status, table, hourly_plot, daily_plot])
190
+ clear_btn.click(fn=lambda: ("", None, None, None), inputs=None, outputs=[status, table, hourly_plot, daily_plot])
191
 
192
  # βœ… Keeps the App Running on Hugging Face
193
  if __name__ == "__main__":
194
  print("πŸš€ App is running on Hugging Face Spaces...")
195
  iface.launch(server_name="0.0.0.0", server_port=7860)
196
+
197
+
sentiment_data.db CHANGED
Binary files a/sentiment_data.db and b/sentiment_data.db differ