Kr08 commited on
Commit
b27f230
·
verified ·
1 Parent(s): 4df22ff

Update stock_analysis.py

Browse files
Files changed (1) hide show
  1. stock_analysis.py +58 -92
stock_analysis.py CHANGED
@@ -1,93 +1,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
 
1
+ import gradio as gr
2
+ from datetime import datetime, date, timedelta
3
+ from config import index_options, time_intervals, START_DATE, END_DATE, FORECAST_PERIOD
4
+ from data_fetcher import get_stocks_from_index
5
+ from stock_analysis import get_stock_graph_and_info
6
+
7
+ def validate_date(date_string):
8
+ try:
9
+ return datetime.strptime(date_string, "%Y-%m-%d").date()
10
+ except ValueError:
11
+ return None
12
+
13
+ demo = gr.Blocks()
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
+ # New date inputs using Textbox
23
+ date_start = gr.Textbox(label="Start Date (YYYY-MM-DD)", value=START_DATE.strftime("%Y-%m-%d"))
24
+ date_end = gr.Textbox(label="End Date (YYYY-MM-DD)", value=END_DATE.strftime("%Y-%m-%d"))
25
+
26
+ out_graph = gr.Plot()
27
+ out_fundamentals = gr.DataFrame()
28
+
29
+ inputs = [d1, d2, d3, d4, d5, date_start, date_end]
30
+ outputs = [out_graph, out_fundamentals]
31
+
32
+ def update_stock_options(index):
33
+ stocks = get_stocks_from_index(index)
34
+ return gr.Dropdown(choices=stocks)
35
+
36
+ def process_inputs(*args):
37
+ idx, stock, interval, graph_type, forecast_method, start_date, end_date = args
38
+
39
+ start = validate_date(start_date)
40
+ end = validate_date(end_date)
41
+
42
+ if start is None or end is None:
43
+ return gr.Textbox(value="Invalid date format. Please use YYYY-MM-DD."), None
44
+
45
+ if start > end:
46
+ return gr.Textbox(value="Start date must be before end date."), None
47
+
48
+ return get_stock_graph_and_info(idx, stock, interval, graph_type, forecast_method, start, end)
49
+
50
+ d1.change(update_stock_options, d1, d2)
51
+ d2.change(process_inputs, inputs, outputs)
52
+ d3.change(process_inputs, inputs, outputs)
53
+ d4.change(process_inputs, inputs, outputs)
54
+ d5.change(process_inputs, inputs, outputs)
55
+ date_start.change(process_inputs, inputs, outputs)
56
+ date_end.change(process_inputs, inputs, outputs)
57
+
58
+ if __name__ == "__main__":
59
+ demo.launch()