Spaces:
Runtime error
Runtime error
mouliraj56
commited on
Commit
•
ad37ff6
1
Parent(s):
ef4d957
Upload 2 files
Browse files- app.py +130 -0
- requirements.txt +9 -0
app.py
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
import pandas as pd
|
4 |
+
import matplotlib.pyplot as plt
|
5 |
+
from statsmodels.tsa.seasonal import seasonal_decompose
|
6 |
+
from sklearn.preprocessing import MinMaxScaler
|
7 |
+
from keras.preprocessing.sequence import TimeseriesGenerator
|
8 |
+
from keras.models import Sequential
|
9 |
+
from keras.layers import Dense, LSTM
|
10 |
+
import yfinance as yf
|
11 |
+
|
12 |
+
|
13 |
+
|
14 |
+
# Function to execute the entire code, handling potential errors
|
15 |
+
def forecast_stock(ticker, period, interval):
|
16 |
+
try:
|
17 |
+
# Download data
|
18 |
+
df = yf.download(ticker, period=period, interval=interval)
|
19 |
+
df = df.asfreq('D').fillna(method='ffill')
|
20 |
+
|
21 |
+
# Filter columns
|
22 |
+
ts = df[['Close']]
|
23 |
+
|
24 |
+
# Perform seasonal decomposition
|
25 |
+
decomposition = seasonal_decompose(ts, model='additive')
|
26 |
+
|
27 |
+
# Train/test split
|
28 |
+
ts_train = ts.iloc[:int(ts.size * .8)]
|
29 |
+
ts_test = ts.iloc[int(ts.size * .8):]
|
30 |
+
|
31 |
+
# Normalize the data
|
32 |
+
scaler = MinMaxScaler()
|
33 |
+
scaler.fit(ts_train.values)
|
34 |
+
scaled_ts_train_values = scaler.transform(ts_train.values)
|
35 |
+
scaled_ts_test_values = scaler.transform(ts_test.values)
|
36 |
+
|
37 |
+
# Create LSTM model
|
38 |
+
n_input = 24
|
39 |
+
n_features = 1
|
40 |
+
generator = TimeseriesGenerator(scaled_ts_train_values, scaled_ts_train_values, length=n_input, batch_size=1)
|
41 |
+
model = Sequential()
|
42 |
+
model.add(LSTM(100, activation='relu', input_shape=(n_input, n_features)))
|
43 |
+
model.add(Dense(1))
|
44 |
+
model.compile(optimizer='adam', loss='mse')
|
45 |
+
model.fit(generator, epochs=50, verbose=0)
|
46 |
+
|
47 |
+
# Make predictions
|
48 |
+
test_predictions = []
|
49 |
+
first_eval_batch = scaled_ts_train_values[-n_input:]
|
50 |
+
current_batch = first_eval_batch.reshape((1, n_input, n_features))
|
51 |
+
for i in range(len(ts_test)):
|
52 |
+
current_pred = model.predict(current_batch, verbose=0)[0]
|
53 |
+
test_predictions.append(current_pred)
|
54 |
+
current_batch = np.append(current_batch[:, 1:, :], [[current_pred]], axis=1)
|
55 |
+
|
56 |
+
true_predictions = scaler.inverse_transform(test_predictions)
|
57 |
+
|
58 |
+
|
59 |
+
fig = plt.figure(figsize=(10, 6))
|
60 |
+
plt.plot(ts.index, ts.values, label='Original Data')
|
61 |
+
plt.plot(ts_test.index, true_predictions, label='Forecasted Data')
|
62 |
+
plt.legend()
|
63 |
+
plt.xlabel('Time')
|
64 |
+
plt.ylabel('Value')
|
65 |
+
plt.title('Stock Price Forecast')
|
66 |
+
|
67 |
+
return fig
|
68 |
+
|
69 |
+
|
70 |
+
except Exception as e:
|
71 |
+
print(f"An error occurred: {e}")
|
72 |
+
return gr.Markdown(f"An error occurred: {e}") # Display error in interface
|
73 |
+
|
74 |
+
tickers_info="""
|
75 |
+
**Ticker Examples**
|
76 |
+
---
|
77 |
+
**Common Stocks**
|
78 |
+
|
79 |
+
- **AAPL:** Apple Inc.
|
80 |
+
- **MSFT:** Microsoft Corp.
|
81 |
+
- **GOOG:** Alphabet Inc. (Google)
|
82 |
+
- **AMZN:** Amazon.com Inc.
|
83 |
+
- **TSLA:** Tesla Inc.
|
84 |
+
- **FB:** Meta Platforms Inc.
|
85 |
+
|
86 |
+
**Indices**
|
87 |
+
|
88 |
+
- **^GSPC:** S&P 500 Index
|
89 |
+
- **^IXIC:** Nasdaq Composite Index
|
90 |
+
- **^DJI:** Dow Jones Industrial Average
|
91 |
+
|
92 |
+
**ETFs ️**
|
93 |
+
|
94 |
+
- **SPY:** SPDR S&P 500 ETF Trust
|
95 |
+
- **QQQ:** Invesco QQQ Trust
|
96 |
+
- **IWM:** iShares Russell 2000 ETF
|
97 |
+
"""
|
98 |
+
|
99 |
+
|
100 |
+
|
101 |
+
with gr.Blocks() as demo:
|
102 |
+
gr.Interface(
|
103 |
+
forecast_stock, # Function to execute on submit
|
104 |
+
[
|
105 |
+
gr.Textbox(label="Ticker", placeholder="e.g., AAPL, MSFT, GOOG"),
|
106 |
+
gr.Textbox(label="Period", placeholder="e.g., 1mo, 5y, max"),
|
107 |
+
gr.Textbox(label="Interval", placeholder="e.g., 1d, 1wk, 1h"),
|
108 |
+
|
109 |
+
],
|
110 |
+
"plot", # Output type
|
111 |
+
live=False, # Disable live updates
|
112 |
+
title="Stock Price Forecast",
|
113 |
+
description="Enter a stock ticker, desired data period, and interval to generate a forecast.",
|
114 |
+
examples = [
|
115 |
+
["AAPL", "2mo", "1d"], # Apple stock, data for 2 months, daily intervals
|
116 |
+
["GOOG", "1y", "1d"], # Google stock, data for 1 year, daily intervals
|
117 |
+
["MSFT", "5y", "1wk"], # Microsoft stock, data for 5 years, weekly intervals
|
118 |
+
["TSLA", "max", "1h"], # Tesla stock, maximum available data, hourly intervals
|
119 |
+
["AMZN", "1y", "1h"], # Amazon stock, data for 1 year, hourly intervals
|
120 |
+
["NVDA", "3mo", "1d"], # NVIDIA stock, data for 3 months, daily intervals
|
121 |
+
["FB", "1y", "1wk"], # Meta Platforms (Facebook) stock, data for 1 year, weekly intervals
|
122 |
+
["JNJ", "2y", "1d"], # Johnson & Johnson stock, data for 2 years, daily intervals
|
123 |
+
["BAC", "6mo", "1d"], # Bank of America stock, data for 6 months, daily intervals
|
124 |
+
["XOM", "1y", "1wk"], # Exxon Mobil stock, data for 1 year, weekly intervals
|
125 |
+
]
|
126 |
+
)
|
127 |
+
with gr.Accordion("Open for More info"):
|
128 |
+
gr.Markdown(tickers_info)
|
129 |
+
|
130 |
+
demo.launch()
|
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
numpy
|
3 |
+
pandas
|
4 |
+
matplotlib
|
5 |
+
statsmodels
|
6 |
+
scikit-learn
|
7 |
+
keras
|
8 |
+
yfinance
|
9 |
+
tensorflow
|