Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,85 +1,128 @@
|
|
1 |
-
import
|
|
|
2 |
import pandas as pd
|
|
|
|
|
|
|
|
|
3 |
import plotly.graph_objects as go
|
4 |
-
|
5 |
from datetime import date, timedelta
|
|
|
|
|
|
|
|
|
|
|
6 |
from dateutil.relativedelta import relativedelta
|
7 |
|
8 |
-
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
"Company Name": info.get("longName", "N/A"),
|
17 |
-
"Sector": info.get("sector", "N/A"),
|
18 |
-
"Industry": info.get("industry", "N/A"),
|
19 |
-
"Market Cap": f"${info.get('marketCap', 'N/A'):,}",
|
20 |
-
"P/E Ratio": round(info.get("trailingPE", 0), 2),
|
21 |
-
"EPS": round(info.get("trailingEps", 0), 2),
|
22 |
-
"52 Week High": f"${info.get('fiftyTwoWeekHigh', 'N/A'):,}",
|
23 |
-
"52 Week Low": f"${info.get('fiftyTwoWeekLow', 'N/A'):,}",
|
24 |
-
"Dividend Yield": f"{info.get('dividendYield', 0) * 100:.2f}%",
|
25 |
-
"Beta": round(info.get("beta", 0), 2),
|
26 |
-
}
|
27 |
-
|
28 |
-
return pd.DataFrame(list(fundamentals.items()), columns=['Metric', 'Value'])
|
29 |
|
30 |
-
def get_stock_graph_and_info(idx, stock, interval, graph_type, forecast_method):
|
31 |
-
stock_name, ticker_name = stock.split(":")
|
32 |
-
|
33 |
-
if ticker_dict[idx] == 'FTSE 100':
|
34 |
-
ticker_name += '.L' if ticker_name[-1] != '.' else 'L'
|
35 |
-
elif ticker_dict[idx] == 'CAC 40':
|
36 |
-
ticker_name += '.PA'
|
37 |
|
38 |
-
# Get stock price data
|
39 |
-
series = yf.download(tickers=ticker_name, start=START_DATE, end=END_DATE, interval=interval)
|
40 |
-
series = series.reset_index()
|
41 |
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
|
|
|
|
46 |
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
-
|
62 |
-
xaxis_title="Date",
|
63 |
-
yaxis_title="Price")
|
64 |
|
65 |
-
|
66 |
-
|
67 |
|
68 |
-
return fig, fundamentals
|
69 |
|
70 |
-
|
71 |
-
|
72 |
-
|
|
|
|
|
|
|
73 |
|
74 |
-
out_graph = gr.Plot()
|
75 |
-
out_fundamentals = gr.DataFrame()
|
76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
inputs = [d1, d2, d3, d4, d5]
|
78 |
-
|
|
|
|
|
|
|
79 |
|
80 |
-
d2.input(get_stock_graph_and_info, inputs, outputs)
|
81 |
-
d3.input(get_stock_graph_and_info, inputs, outputs)
|
82 |
-
d4.input(get_stock_graph_and_info, inputs, outputs)
|
83 |
-
d5.input(get_stock_graph_and_info, inputs, outputs)
|
84 |
|
85 |
demo.launch()
|
|
|
1 |
+
import datetime
|
2 |
+
import gradio as gr
|
3 |
import pandas as pd
|
4 |
+
import yfinance as yf
|
5 |
+
import seaborn as sns
|
6 |
+
sns.set()
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
import plotly.graph_objects as go
|
9 |
+
|
10 |
from datetime import date, timedelta
|
11 |
+
from matplotlib import pyplot as plt
|
12 |
+
from plotly.subplots import make_subplots
|
13 |
+
from pytickersymbols import PyTickerSymbols
|
14 |
+
from statsmodels.tsa.arima.model import ARIMA
|
15 |
+
from pandas.plotting import autocorrelation_plot
|
16 |
from dateutil.relativedelta import relativedelta
|
17 |
|
18 |
+
index_options = ['FTSE 100(UK)', 'NASDAQ(USA)', 'CAC 40(FRANCE)']
|
19 |
+
ticker_dict = {'FTSE 100(UK)': 'FTSE 100', 'NASDAQ(USA)': 'NASDAQ 100', 'CAC 40(FRANCE)': 'CAC 40'}
|
20 |
+
time_intervals = ['1d', '1m', '5m', '15m', '60m']
|
21 |
|
22 |
+
global START_DATE, END_DATE
|
23 |
+
END_DATE = date.today()
|
24 |
+
START_DATE = END_DATE - relativedelta(years=1)
|
25 |
+
FORECAST_PERIOD = 7
|
26 |
+
demo = gr.Blocks()
|
27 |
+
stock_names = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
|
|
|
|
|
|
30 |
|
31 |
+
with demo:
|
32 |
+
d1 = gr.Dropdown(index_options, label='Please select Index...', info='Will be adding more indices later on', interactive=True)
|
33 |
+
d2 = gr.Dropdown([], label='Please Select Stock from your selected index', interactive=True)
|
34 |
+
d3 = gr.Dropdown(time_intervals, label='Select Time Interval', value='1d', interactive=True)
|
35 |
+
d4 = gr.Radio(['Line Graph', 'Candlestick Graph'], label='Select Graph Type', value='Line Graph', interactive=True)
|
36 |
+
d5 = gr.Dropdown(['ARIMA', 'Prophet', 'LSTM'], label='Select Forecasting Method', value='ARIMA', interactive=True)
|
37 |
|
38 |
+
def forecast_series(series, model="ARIMA", forecast_period=7):
|
39 |
+
predictions = list()
|
40 |
+
if series.shape[1] > 1:
|
41 |
+
series = series['Close'].values.tolist()
|
42 |
+
|
43 |
+
if model == "ARIMA":
|
44 |
+
for i in range(forecast_period):
|
45 |
+
model = ARIMA(series, order=(5, 1, 0))
|
46 |
+
model_fit = model.fit()
|
47 |
+
output = model_fit.forecast()
|
48 |
+
yhat = output[0]
|
49 |
+
predictions.append(yhat)
|
50 |
+
series.append(yhat)
|
51 |
+
elif model == "Prophet":
|
52 |
+
# Implement Prophet forecasting method
|
53 |
+
pass
|
54 |
+
elif model == "LSTM":
|
55 |
+
# Implement LSTM forecasting method
|
56 |
+
pass
|
57 |
|
58 |
+
return predictions
|
|
|
|
|
59 |
|
60 |
+
def is_business_day(a_date):
|
61 |
+
return a_date.weekday() < 5
|
62 |
|
|
|
63 |
|
64 |
+
def get_stocks_from_index(idx):
|
65 |
+
stock_data = PyTickerSymbols()
|
66 |
+
index = ticker_dict[idx]
|
67 |
+
stocks = list(stock_data.get_stocks_by_index(index))
|
68 |
+
stock_names = [f"{stock['name']}:{stock['symbol']}" for stock in stocks]
|
69 |
+
return gr.Dropdown(choices=stock_names, label='Please Select Stock from your selected index', interactive=True)
|
70 |
|
|
|
|
|
71 |
|
72 |
+
d1.input(get_stocks_from_index, d1, d2)
|
73 |
+
|
74 |
+
def get_stock_graph(idx, stock, interval, graph_type, forecast_method):
|
75 |
+
stock_name, ticker_name = stock.split(":")
|
76 |
+
|
77 |
+
if ticker_dict[idx] == 'FTSE 100':
|
78 |
+
ticker_name += '.L' if ticker_name[-1] != '.' else 'L'
|
79 |
+
elif ticker_dict[idx] == 'CAC 40':
|
80 |
+
ticker_name += '.PA'
|
81 |
+
|
82 |
+
series = yf.download(tickers=ticker_name, start=START_DATE, end=END_DATE, interval=interval)
|
83 |
+
series = series.reset_index()
|
84 |
+
|
85 |
+
predictions = forecast_series(series, model=forecast_method)
|
86 |
+
|
87 |
+
last_date = pd.to_datetime(series['Date'].values[-1])
|
88 |
+
forecast_week = []
|
89 |
+
i = 1
|
90 |
+
while len(forecast_week) < FORECAST_PERIOD:
|
91 |
+
next_date = last_date + timedelta(days=i)
|
92 |
+
if is_business_day(next_date):
|
93 |
+
forecast_week.append(next_date)
|
94 |
+
i += 1
|
95 |
+
|
96 |
+
# Ensure predictions and forecast_week have the same length
|
97 |
+
predictions = predictions[:len(forecast_week)]
|
98 |
+
forecast_week = forecast_week[:len(predictions)]
|
99 |
+
|
100 |
+
forecast = pd.DataFrame({"Date": forecast_week, "Forecast": predictions})
|
101 |
+
|
102 |
+
if graph_type == 'Line Graph':
|
103 |
+
fig = go.Figure()
|
104 |
+
fig.add_trace(go.Scatter(x=series['Date'], y=series['Close'], mode='lines', name='Historical'))
|
105 |
+
fig.add_trace(go.Scatter(x=forecast['Date'], y=forecast['Forecast'], mode='lines', name='Forecast'))
|
106 |
+
else: # Candlestick Graph
|
107 |
+
fig = go.Figure(data=[go.Candlestick(x=series['Date'],
|
108 |
+
open=series['Open'],
|
109 |
+
high=series['High'],
|
110 |
+
low=series['Low'],
|
111 |
+
close=series['Close'],
|
112 |
+
name='Historical')])
|
113 |
+
fig.add_trace(go.Scatter(x=forecast['Date'], y=forecast['Forecast'], mode='lines', name='Forecast'))
|
114 |
+
|
115 |
+
fig.update_layout(title=f"Stock Price of {stock_name}",
|
116 |
+
xaxis_title="Date",
|
117 |
+
yaxis_title="Price")
|
118 |
+
|
119 |
+
return fig
|
120 |
+
out = gr.Plot()
|
121 |
inputs = [d1, d2, d3, d4, d5]
|
122 |
+
d2.input(get_stock_graph, inputs, out)
|
123 |
+
d3.input(get_stock_graph, inputs, out)
|
124 |
+
d4.input(get_stock_graph, inputs, out)
|
125 |
+
d5.input(get_stock_graph, inputs, out)
|
126 |
|
|
|
|
|
|
|
|
|
127 |
|
128 |
demo.launch()
|