Spaces:
Sleeping
Sleeping
Update stock_analysis.py
Browse files- stock_analysis.py +92 -58
stock_analysis.py
CHANGED
@@ -1,59 +1,93 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
|
4 |
-
from
|
5 |
-
from
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
with demo:
|
16 |
-
d1 = gr.Dropdown(index_options, label='Please select Index...', info='Will be adding more indices later on', interactive=True)
|
17 |
-
d2 = gr.Dropdown(label='Please Select Stock from your selected index', interactive=True)
|
18 |
-
d3 = gr.Dropdown(time_intervals, label='Select Time Interval', value='1d', interactive=True)
|
19 |
-
d4 = gr.Radio(['Line Graph', 'Candlestick Graph'], label='Select Graph Type', value='Line Graph', interactive=True)
|
20 |
-
d5 = gr.Dropdown(['ARIMA', 'Prophet', 'LSTM'], label='Select Forecasting Method', value='ARIMA', interactive=True)
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import numpy as np
|
3 |
+
import plotly.graph_objects as go
|
4 |
+
from datetime import timedelta
|
5 |
+
from statsmodels.tsa.arima.model import ARIMA
|
6 |
+
from config import FORECAST_PERIOD, ticker_dict, CONFIDENCE_INTERVAL
|
7 |
+
from data_fetcher import get_stock_data, get_company_info
|
8 |
+
|
9 |
+
def is_business_day(a_date):
|
10 |
+
return a_date.weekday() < 5
|
11 |
+
|
12 |
+
def forecast_series(series, model="ARIMA", forecast_period=FORECAST_PERIOD):
|
13 |
+
predictions = []
|
14 |
+
confidence_intervals = []
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
+
if series.shape[1] > 1:
|
17 |
+
series = series['Close'].values.tolist()
|
18 |
+
|
19 |
+
if model == "ARIMA":
|
20 |
+
model = ARIMA(series, order=(5, 1, 0))
|
21 |
+
model_fit = model.fit()
|
22 |
+
forecast = model_fit.forecast(steps=forecast_period, alpha=(1 - CONFIDENCE_INTERVAL))
|
23 |
+
predictions = forecast.predicted_mean
|
24 |
+
confidence_intervals = forecast.conf_int()
|
25 |
+
elif model == "Prophet":
|
26 |
+
# Implement Prophet forecasting method
|
27 |
+
pass
|
28 |
+
elif model == "LSTM":
|
29 |
+
# Implement LSTM forecasting method
|
30 |
+
pass
|
31 |
+
|
32 |
+
return predictions, confidence_intervals
|
33 |
+
|
34 |
+
def get_stock_graph_and_info(idx, stock, interval, graph_type, forecast_method, start_date, end_date):
|
35 |
+
stock_name, ticker_name = stock.split(":")
|
36 |
+
|
37 |
+
if ticker_dict[idx] == 'FTSE 100':
|
38 |
+
ticker_name += '.L' if ticker_name[-1] != '.' else 'L'
|
39 |
+
elif ticker_dict[idx] == 'CAC 40':
|
40 |
+
ticker_name += '.PA'
|
41 |
+
|
42 |
+
series = get_stock_data(ticker_name, interval, start_date, end_date)
|
43 |
+
predictions, confidence_intervals = forecast_series(series, model=forecast_method)
|
44 |
+
|
45 |
+
last_date = pd.to_datetime(series['Date'].values[-1])
|
46 |
+
forecast_dates = pd.date_range(start=last_date + timedelta(days=1), periods=FORECAST_PERIOD)
|
47 |
+
forecast_dates = [date for date in forecast_dates if is_business_day(date)]
|
48 |
+
|
49 |
+
forecast = pd.DataFrame({
|
50 |
+
"Date": forecast_dates,
|
51 |
+
"Forecast": predictions,
|
52 |
+
"Lower_CI": confidence_intervals.iloc[:, 0],
|
53 |
+
"Upper_CI": confidence_intervals.iloc[:, 1]
|
54 |
+
})
|
55 |
+
|
56 |
+
if graph_type == 'Line Graph':
|
57 |
+
fig = go.Figure()
|
58 |
+
fig.add_trace(go.Scatter(x=series['Date'], y=series['Close'], mode='lines', name='Historical'))
|
59 |
+
fig.add_trace(go.Scatter(x=forecast['Date'], y=forecast['Forecast'], mode='lines', name='Forecast'))
|
60 |
+
fig.add_trace(go.Scatter(
|
61 |
+
x=forecast['Date'].tolist() + forecast['Date'].tolist()[::-1],
|
62 |
+
y=forecast['Upper_CI'].tolist() + forecast['Lower_CI'].tolist()[::-1],
|
63 |
+
fill='toself',
|
64 |
+
fillcolor='rgba(0,100,80,0.2)',
|
65 |
+
line=dict(color='rgba(255,255,255,0)'),
|
66 |
+
hoverinfo="skip",
|
67 |
+
showlegend=False
|
68 |
+
))
|
69 |
+
else: # Candlestick Graph
|
70 |
+
fig = go.Figure(data=[go.Candlestick(x=series['Date'],
|
71 |
+
open=series['Open'],
|
72 |
+
high=series['High'],
|
73 |
+
low=series['Low'],
|
74 |
+
close=series['Close'],
|
75 |
+
name='Historical')])
|
76 |
+
fig.add_trace(go.Scatter(x=forecast['Date'], y=forecast['Forecast'], mode='lines', name='Forecast'))
|
77 |
+
fig.add_trace(go.Scatter(
|
78 |
+
x=forecast['Date'].tolist() + forecast['Date'].tolist()[::-1],
|
79 |
+
y=forecast['Upper_CI'].tolist() + forecast['Lower_CI'].tolist()[::-1],
|
80 |
+
fill='toself',
|
81 |
+
fillcolor='rgba(0,100,80,0.2)',
|
82 |
+
line=dict(color='rgba(255,255,255,0)'),
|
83 |
+
hoverinfo="skip",
|
84 |
+
showlegend=False
|
85 |
+
))
|
86 |
+
|
87 |
+
fig.update_layout(title=f"Stock Price of {stock_name}",
|
88 |
+
xaxis_title="Date",
|
89 |
+
yaxis_title="Price")
|
90 |
+
|
91 |
+
fundamentals = get_company_info(ticker_name)
|
92 |
+
|
93 |
+
return fig, fundamentals
|