Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -13,12 +13,12 @@ from sklearn.metrics import mean_squared_error
|
|
13 |
|
14 |
# Define periods
|
15 |
PERIODS = {
|
16 |
-
"1 Month": "1mo",
|
17 |
-
"3 Months": "3mo",
|
18 |
-
"6 Months": "6mo",
|
19 |
-
"1 Year": "1y",
|
20 |
-
"5 Years": "5y",
|
21 |
-
"10 Years": "10y",
|
22 |
"Max": "max"
|
23 |
}
|
24 |
|
@@ -39,6 +39,21 @@ def update_output_type(analysis_type):
|
|
39 |
else:
|
40 |
return gr.update(visible=False), gr.update(visible=True)
|
41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
def summarize_asset(ticker):
|
43 |
if ticker.strip() == "":
|
44 |
return "Invalid input: Ticker symbol cannot be empty."
|
@@ -46,18 +61,55 @@ def summarize_asset(ticker):
|
|
46 |
stock = yf.Ticker(ticker)
|
47 |
try:
|
48 |
info = stock.info
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
return summary
|
62 |
except Exception as e:
|
63 |
return str(e)
|
@@ -233,18 +285,18 @@ def train_linear_regression_model(ticker, period, future_days):
|
|
233 |
|
234 |
data['Close'] = data['Close'].fillna(method='ffill')
|
235 |
close_prices = data['Close'].values.reshape(-1, 1)
|
236 |
-
|
237 |
X = np.array(range(len(close_prices))).reshape(-1, 1)
|
238 |
y = close_prices
|
239 |
-
|
240 |
model = LinearRegression()
|
241 |
model.fit(X, y)
|
242 |
-
|
243 |
future_X = np.array(range(len(close_prices), len(close_prices) + future_days)).reshape(-1, 1)
|
244 |
future_predictions = model.predict(future_X)
|
245 |
-
|
246 |
predictions = model.predict(X)
|
247 |
-
|
248 |
fig = go.Figure()
|
249 |
fig.add_trace(go.Scatter(x=data.index, y=close_prices.flatten(), mode='lines', name='Actual'))
|
250 |
fig.add_trace(go.Scatter(x=data.index, y=predictions.flatten(), mode='lines', name='Predicted'))
|
@@ -265,18 +317,18 @@ def train_random_forest_model(ticker, period, future_days, n_estimators):
|
|
265 |
|
266 |
data['Close'] = data['Close'].fillna(method='ffill')
|
267 |
close_prices = data['Close'].values.reshape(-1, 1)
|
268 |
-
|
269 |
X = np.array(range(len(close_prices))).reshape(-1, 1)
|
270 |
y = close_prices
|
271 |
-
|
272 |
model = RandomForestRegressor(n_estimators=n_estimators)
|
273 |
model.fit(X, y.ravel())
|
274 |
-
|
275 |
future_X = np.array(range(len(close_prices), len(close_prices) + future_days)).reshape(-1, 1)
|
276 |
future_predictions = model.predict(future_X)
|
277 |
-
|
278 |
predictions = model.predict(X)
|
279 |
-
|
280 |
fig = go.Figure()
|
281 |
fig.add_trace(go.Scatter(x=data.index, y=close_prices.flatten(), mode='lines', name='Actual'))
|
282 |
fig.add_trace(go.Scatter(x=data.index, y=predictions.flatten(), mode='lines', name='Predicted'))
|
@@ -289,14 +341,14 @@ def train_random_forest_model(ticker, period, future_days, n_estimators):
|
|
289 |
with gr.Blocks() as demo:
|
290 |
gr.Markdown("# Stock Analysis Tool")
|
291 |
with gr.Tab("Summary"):
|
292 |
-
ticker = gr.Textbox(label="Ticker
|
293 |
summary_button = gr.Button("Generate Summary")
|
294 |
summary_output = gr.Markdown()
|
295 |
summary_button.click(fn=summarize_asset, inputs=ticker, outputs=summary_output)
|
296 |
-
|
297 |
with gr.Tab("Technical Analysis"):
|
298 |
with gr.Column():
|
299 |
-
ticker = gr.Textbox(label="Ticker
|
300 |
period = gr.Dropdown(label="Period", choices=list(PERIODS.keys()), value="1 Year")
|
301 |
analysis_type = gr.Radio(label="Analysis Type", choices=["Candlestick", "Moving Average", "Bollinger Bands", "RSI", "MACD", "ADX"], value="Candlestick")
|
302 |
ma_length = gr.Number(label="Moving Average Length", value=20, visible=False)
|
@@ -312,7 +364,7 @@ with gr.Blocks() as demo:
|
|
312 |
plot_button.click(fn=plot_technical_analysis, inputs=[ticker, period, analysis_type, ma_length, candle_period, adx_period], outputs=plot_output)
|
313 |
|
314 |
with gr.Tab("Fundamental Analysis"):
|
315 |
-
ticker = gr.Textbox(label="Ticker
|
316 |
analysis_type = gr.Radio(label="Analysis Type", choices=["Financials", "Balance Sheet", "Cash Flow", "Dividends"], value="Financials")
|
317 |
plot_button = gr.Button("Show Fundamental Data")
|
318 |
plot_output = gr.Plot(visible=False)
|
@@ -322,7 +374,7 @@ with gr.Blocks() as demo:
|
|
322 |
plot_button.click(fn=plot_fundamental_analysis, inputs=[ticker, analysis_type], outputs=[plot_output, html_output])
|
323 |
|
324 |
with gr.Tab("Predictive Model"):
|
325 |
-
ticker = gr.Textbox(label="Ticker
|
326 |
period = gr.Dropdown(label="Period", choices=list(PERIODS.keys()), value="1 Year")
|
327 |
epochs = gr.Number(label="Epochs", value=10)
|
328 |
batch_size = gr.Number(label="Batch Size", value=32)
|
@@ -345,4 +397,4 @@ with gr.Blocks() as demo:
|
|
345 |
train_rf_button.click(fn=train_random_forest_model, inputs=[ticker, period, future_days_rf, n_estimators], outputs=rf_output)
|
346 |
|
347 |
# Launch the interface
|
348 |
-
demo.launch()
|
|
|
13 |
|
14 |
# Define periods
|
15 |
PERIODS = {
|
16 |
+
"1 Month": "1mo",
|
17 |
+
"3 Months": "3mo",
|
18 |
+
"6 Months": "6mo",
|
19 |
+
"1 Year": "1y",
|
20 |
+
"5 Years": "5y",
|
21 |
+
"10 Years": "10y",
|
22 |
"Max": "max"
|
23 |
}
|
24 |
|
|
|
39 |
else:
|
40 |
return gr.update(visible=False), gr.update(visible=True)
|
41 |
|
42 |
+
def fetch_news(ticker):
|
43 |
+
try:
|
44 |
+
stock = yf.Ticker(ticker)
|
45 |
+
news = stock.news
|
46 |
+
news_summary = ""
|
47 |
+
for article in news[:5]: # Limiting to 5 news articles
|
48 |
+
news_summary += f"### {article['title']}\n"
|
49 |
+
news_summary += f"**Source:** {article['publisher']} \n"
|
50 |
+
news_summary += f"**Published At:** {article['providerPublishTime']} \n"
|
51 |
+
news_summary += f"{article['summary']} \n"
|
52 |
+
news_summary += f"[Read more]({article['link']}) \n\n"
|
53 |
+
return news_summary
|
54 |
+
except Exception as e:
|
55 |
+
return str(e)
|
56 |
+
|
57 |
def summarize_asset(ticker):
|
58 |
if ticker.strip() == "":
|
59 |
return "Invalid input: Ticker symbol cannot be empty."
|
|
|
61 |
stock = yf.Ticker(ticker)
|
62 |
try:
|
63 |
info = stock.info
|
64 |
+
asset_type = info.get('quoteType', 'N/A')
|
65 |
+
|
66 |
+
summary = f"**Summary for {info.get('shortName', 'N/A')} ({ticker}):**\n\n"
|
67 |
+
|
68 |
+
current_price = info.get('currentPrice')
|
69 |
+
if current_price:
|
70 |
+
summary += f"- **Current Price:** ${current_price}\n"
|
71 |
+
|
72 |
+
market_cap = info.get('marketCap')
|
73 |
+
if market_cap:
|
74 |
+
summary += f"- **Market Cap:** ${market_cap}\n"
|
75 |
+
|
76 |
+
trailing_pe = info.get('trailingPE')
|
77 |
+
if trailing_pe:
|
78 |
+
summary += f"- **PE Ratio (TTM):** {trailing_pe}\n"
|
79 |
+
|
80 |
+
trailing_eps = info.get('trailingEps')
|
81 |
+
if trailing_eps:
|
82 |
+
summary += f"- **EPS (TTM):** {trailing_eps}\n"
|
83 |
+
|
84 |
+
dividend_yield = info.get('dividendYield')
|
85 |
+
if dividend_yield:
|
86 |
+
summary += f"- **Dividend Yield:** {dividend_yield * 100}%\n"
|
87 |
+
|
88 |
+
fifty_two_week_high = info.get('fiftyTwoWeekHigh')
|
89 |
+
if fifty_two_week_high:
|
90 |
+
summary += f"- **52 Week High:** ${fifty_two_week_high}\n"
|
91 |
+
|
92 |
+
fifty_two_week_low = info.get('fiftyTwoWeekLow')
|
93 |
+
if fifty_two_week_low:
|
94 |
+
summary += f"- **52 Week Low:** ${fifty_two_week_low}\n"
|
95 |
+
|
96 |
+
volume = info.get('volume')
|
97 |
+
if volume:
|
98 |
+
summary += f"- **Volume:** {volume}\n"
|
99 |
+
|
100 |
+
if asset_type == "ETF" or asset_type == "MUTUALFUND":
|
101 |
+
total_assets = info.get('totalAssets')
|
102 |
+
if total_assets:
|
103 |
+
summary += f"- **Total Assets:** ${total_assets}\n"
|
104 |
+
|
105 |
+
nav_price = info.get('navPrice')
|
106 |
+
if nav_price:
|
107 |
+
summary += f"- **NAV:** ${nav_price}\n"
|
108 |
+
|
109 |
+
expense_ratio = info.get('annualReportExpenseRatio')
|
110 |
+
if expense_ratio:
|
111 |
+
summary += f"- **Expense Ratio:** {expense_ratio * 100}%\n"
|
112 |
+
|
113 |
return summary
|
114 |
except Exception as e:
|
115 |
return str(e)
|
|
|
285 |
|
286 |
data['Close'] = data['Close'].fillna(method='ffill')
|
287 |
close_prices = data['Close'].values.reshape(-1, 1)
|
288 |
+
|
289 |
X = np.array(range(len(close_prices))).reshape(-1, 1)
|
290 |
y = close_prices
|
291 |
+
|
292 |
model = LinearRegression()
|
293 |
model.fit(X, y)
|
294 |
+
|
295 |
future_X = np.array(range(len(close_prices), len(close_prices) + future_days)).reshape(-1, 1)
|
296 |
future_predictions = model.predict(future_X)
|
297 |
+
|
298 |
predictions = model.predict(X)
|
299 |
+
|
300 |
fig = go.Figure()
|
301 |
fig.add_trace(go.Scatter(x=data.index, y=close_prices.flatten(), mode='lines', name='Actual'))
|
302 |
fig.add_trace(go.Scatter(x=data.index, y=predictions.flatten(), mode='lines', name='Predicted'))
|
|
|
317 |
|
318 |
data['Close'] = data['Close'].fillna(method='ffill')
|
319 |
close_prices = data['Close'].values.reshape(-1, 1)
|
320 |
+
|
321 |
X = np.array(range(len(close_prices))).reshape(-1, 1)
|
322 |
y = close_prices
|
323 |
+
|
324 |
model = RandomForestRegressor(n_estimators=n_estimators)
|
325 |
model.fit(X, y.ravel())
|
326 |
+
|
327 |
future_X = np.array(range(len(close_prices), len(close_prices) + future_days)).reshape(-1, 1)
|
328 |
future_predictions = model.predict(future_X)
|
329 |
+
|
330 |
predictions = model.predict(X)
|
331 |
+
|
332 |
fig = go.Figure()
|
333 |
fig.add_trace(go.Scatter(x=data.index, y=close_prices.flatten(), mode='lines', name='Actual'))
|
334 |
fig.add_trace(go.Scatter(x=data.index, y=predictions.flatten(), mode='lines', name='Predicted'))
|
|
|
341 |
with gr.Blocks() as demo:
|
342 |
gr.Markdown("# Stock Analysis Tool")
|
343 |
with gr.Tab("Summary"):
|
344 |
+
ticker = gr.Textbox(label="Enter Yahoo Finance Asset Ticker", value="AAPL")
|
345 |
summary_button = gr.Button("Generate Summary")
|
346 |
summary_output = gr.Markdown()
|
347 |
summary_button.click(fn=summarize_asset, inputs=ticker, outputs=summary_output)
|
348 |
+
|
349 |
with gr.Tab("Technical Analysis"):
|
350 |
with gr.Column():
|
351 |
+
ticker = gr.Textbox(label="Enter Yahoo Finance Asset Ticker", value="AAPL")
|
352 |
period = gr.Dropdown(label="Period", choices=list(PERIODS.keys()), value="1 Year")
|
353 |
analysis_type = gr.Radio(label="Analysis Type", choices=["Candlestick", "Moving Average", "Bollinger Bands", "RSI", "MACD", "ADX"], value="Candlestick")
|
354 |
ma_length = gr.Number(label="Moving Average Length", value=20, visible=False)
|
|
|
364 |
plot_button.click(fn=plot_technical_analysis, inputs=[ticker, period, analysis_type, ma_length, candle_period, adx_period], outputs=plot_output)
|
365 |
|
366 |
with gr.Tab("Fundamental Analysis"):
|
367 |
+
ticker = gr.Textbox(label="Enter Yahoo Finance Asset Ticker", value="AAPL")
|
368 |
analysis_type = gr.Radio(label="Analysis Type", choices=["Financials", "Balance Sheet", "Cash Flow", "Dividends"], value="Financials")
|
369 |
plot_button = gr.Button("Show Fundamental Data")
|
370 |
plot_output = gr.Plot(visible=False)
|
|
|
374 |
plot_button.click(fn=plot_fundamental_analysis, inputs=[ticker, analysis_type], outputs=[plot_output, html_output])
|
375 |
|
376 |
with gr.Tab("Predictive Model"):
|
377 |
+
ticker = gr.Textbox(label="Enter Yahoo Finance Asset Ticker", value="AAPL")
|
378 |
period = gr.Dropdown(label="Period", choices=list(PERIODS.keys()), value="1 Year")
|
379 |
epochs = gr.Number(label="Epochs", value=10)
|
380 |
batch_size = gr.Number(label="Batch Size", value=32)
|
|
|
397 |
train_rf_button.click(fn=train_random_forest_model, inputs=[ticker, period, future_days_rf, n_estimators], outputs=rf_output)
|
398 |
|
399 |
# Launch the interface
|
400 |
+
demo.launch(debug=True)
|