Ritvik
commited on
Commit
Β·
004ad50
1
Parent(s):
e6a85c2
Updated app
Browse files
app.py
CHANGED
|
@@ -110,22 +110,35 @@ def save_to_db(df, ticker):
|
|
| 110 |
|
| 111 |
|
| 112 |
def plot_sentiment(df, ticker, interval):
|
| 113 |
-
""" Generates sentiment trend plots
|
| 114 |
if df.empty:
|
| 115 |
return None
|
| 116 |
|
| 117 |
df['datetime'] = pd.to_datetime(df['datetime'])
|
| 118 |
df = df.set_index('datetime')
|
| 119 |
|
| 120 |
-
# β
|
| 121 |
-
|
|
|
|
|
|
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,7 +155,6 @@ def analyze_stock_sentiment(ticker, days):
|
|
| 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,13 +164,12 @@ def analyze_stock_sentiment(ticker, 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,27 +178,14 @@ def analyze_stock_sentiment(ticker, days):
|
|
| 167 |
return f"β
Analysis for {ticker.upper()} (Last {days} Days) Complete!", df_scored, fig_hourly, fig_daily
|
| 168 |
|
| 169 |
|
| 170 |
-
# Gradio
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 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 |
-
iface.launch()
|
| 193 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
|
| 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 |
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 |
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)
|