File size: 5,089 Bytes
31ac823
 
2e79a3d
31ac823
 
 
 
2e2dfb4
31ac823
2e2dfb4
31ac823
 
 
 
 
2e2dfb4
 
31ac823
 
 
2e2dfb4
31ac823
 
 
 
 
 
2e2dfb4
 
 
31ac823
 
 
 
 
 
2e2dfb4
31ac823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e2dfb4
31ac823
2e79a3d
31ac823
 
2e79a3d
 
31ac823
 
 
 
 
 
2e79a3d
2e2dfb4
31ac823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a50720
31ac823
 
 
 
2e79a3d
2e2dfb4
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
 import datetime
import gradio as gr
import pandas as pd
import yfinance as yf
import seaborn as sns
sns.set()
import matplotlib.pyplot as plt
import plotly.graph_objects as go

from datetime import date, timedelta
from matplotlib import pyplot as plt
from plotly.subplots import make_subplots
from pytickersymbols import PyTickerSymbols
from statsmodels.tsa.arima.model import ARIMA
from pandas.plotting import autocorrelation_plot
from dateutil.relativedelta import relativedelta

index_options = ['FTSE 100(UK)', 'NASDAQ(USA)', 'CAC 40(FRANCE)']
ticker_dict = {'FTSE 100(UK)': 'FTSE 100', 'NASDAQ(USA)': 'NASDAQ 100', 'CAC 40(FRANCE)': 'CAC 40'}
time_intervals = ['1d', '1m', '5m', '15m', '60m']

global START_DATE, END_DATE
END_DATE = date.today()
START_DATE = END_DATE - relativedelta(years=1)
FORECAST_PERIOD = 7
demo = gr.Blocks()
stock_names = []



with demo:
    d1 = gr.Dropdown(index_options, label='Please select Index...', info='Will be adding more indices later on', interactive=True)
    d2 = gr.Dropdown([], label='Please Select Stock from your selected index', interactive=True)
    d3 = gr.Dropdown(time_intervals, label='Select Time Interval', value='1d', interactive=True)
    d4 = gr.Radio(['Line Graph', 'Candlestick Graph'], label='Select Graph Type', value='Line Graph', interactive=True)
    d5 = gr.Dropdown(['ARIMA', 'Prophet', 'LSTM'], label='Select Forecasting Method', value='ARIMA', interactive=True)

    def forecast_series(series, model="ARIMA", forecast_period=7):
        predictions = list()
        if series.shape[1] > 1:
            series = series['Close'].values.tolist()
        
        if model == "ARIMA":
            for i in range(forecast_period):
                model = ARIMA(series, order=(5, 1, 0))
                model_fit = model.fit()
                output = model_fit.forecast()
                yhat = output[0]
                predictions.append(yhat)
                series.append(yhat)
        elif model == "Prophet":
            # Implement Prophet forecasting method
            pass
        elif model == "LSTM":
            # Implement LSTM forecasting method
            pass

        return predictions

    def is_business_day(a_date):
        return a_date.weekday() < 5


    def get_stocks_from_index(idx):
        stock_data = PyTickerSymbols()
        index = ticker_dict[idx]
        stocks = list(stock_data.get_stocks_by_index(index))
        stock_names = [f"{stock['name']}:{stock['symbol']}" for stock in stocks]
        return gr.Dropdown(choices=stock_names, label='Please Select Stock from your selected index', interactive=True)


    d1.input(get_stocks_from_index, d1, d2)
    
    def get_stock_graph(idx, stock, interval, graph_type, forecast_method):
        stock_name, ticker_name = stock.split(":")
        
        if ticker_dict[idx] == 'FTSE 100':
            ticker_name += '.L' if ticker_name[-1] != '.' else 'L'
        elif ticker_dict[idx] == 'CAC 40':
            ticker_name += '.PA'
    
        series = yf.download(tickers=ticker_name, start=START_DATE, end=END_DATE, interval=interval)
        series = series.reset_index()
    
        predictions = forecast_series(series, model=forecast_method)
    
        last_date = pd.to_datetime(series['Date'].values[-1])
        forecast_week = []
        i = 1
        while len(forecast_week) < FORECAST_PERIOD:
            next_date = last_date + timedelta(days=i)
            if is_business_day(next_date):
                forecast_week.append(next_date)
            i += 1
    
        # Ensure predictions and forecast_week have the same length
        predictions = predictions[:len(forecast_week)]
        forecast_week = forecast_week[:len(predictions)]
    
        forecast = pd.DataFrame({"Date": forecast_week, "Forecast": predictions})
    
        if graph_type == 'Line Graph':
            fig = go.Figure()
            fig.add_trace(go.Scatter(x=series['Date'], y=series['Close'], mode='lines', name='Historical'))
            fig.add_trace(go.Scatter(x=forecast['Date'], y=forecast['Forecast'], mode='lines', name='Forecast'))
        else:  # Candlestick Graph
            fig = go.Figure(data=[go.Candlestick(x=series['Date'],
                                                 open=series['Open'],
                                                 high=series['High'],
                                                 low=series['Low'],
                                                 close=series['Close'],
                                                 name='Historical')])
            fig.add_trace(go.Scatter(x=forecast['Date'], y=forecast['Forecast'], mode='lines', name='Forecast'))
    
        fig.update_layout(title=f"Stock Price of {stock_name}",
                          xaxis_title="Date",
                          yaxis_title="Price")
    
        return fig
    out = gr.Plot()
    inputs = [d1, d2, d3, d4, d5]
    d2.input(get_stock_graph, inputs, out)
    d3.input(get_stock_graph, inputs, out)
    d4.input(get_stock_graph, inputs, out)
    d5.input(get_stock_graph, inputs, out)


demo.launch()