Update app.py
Browse files
app.py
CHANGED
@@ -36,183 +36,80 @@ COMPANIES = [
|
|
36 |
]
|
37 |
|
38 |
class StockPredictor:
|
39 |
-
def __init__(self, data
|
40 |
self.data = data
|
41 |
-
self.model_type = model_type
|
42 |
self.model = None
|
43 |
-
self.scaler = None
|
44 |
-
self.lstm_scaler = None
|
45 |
|
46 |
def preprocess_data(self):
|
47 |
-
|
48 |
-
self.data = self.data.reset_index(
|
49 |
-
|
50 |
-
# Enhanced Feature Engineering
|
51 |
-
self.data['DayOfWeek'] = self.data['Date'].dt.dayofweek
|
52 |
-
self.data['Month'] = self.data['Date'].dt.month
|
53 |
-
self.data['Year'] = self.data['Date'].dt.year
|
54 |
-
self.data['IsMonthEnd'] = self.data['Date'].dt.is_month_end.astype(int)
|
55 |
-
|
56 |
-
# Technical Indicators
|
57 |
-
self.data['SMA_20'] = SMAIndicator(close=self.data['Close'], window=20).sma_indicator()
|
58 |
-
self.data['EMA_20'] = EMAIndicator(close=self.data['Close'], window=20).ema_indicator()
|
59 |
-
self.data['RSI'] = RSIIndicator(close=self.data['Close']).rsi()
|
60 |
-
bb = BollingerBands(close=self.data['Close'], window=20, window_dev=2)
|
61 |
-
self.data['BB_High'] = bb.bollinger_hband()
|
62 |
-
self.data['BB_Low'] = bb.bollinger_lband()
|
63 |
|
64 |
-
#
|
65 |
-
self.data['
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
self.features = ['Open', 'High', 'Low', 'Close', 'Volume', 'SMA_20', 'EMA_20', 'RSI', 'BB_High', 'BB_Low', 'LogReturn', 'DayOfWeek', 'Month', 'Year', 'IsMonthEnd']
|
72 |
-
|
73 |
-
# Apply scaling for XGBoost and RandomForest
|
74 |
-
if self.model_type in ['XGBoost', 'RandomForest']:
|
75 |
-
self.scaler = StandardScaler()
|
76 |
-
self.data[self.features] = self.scaler.fit_transform(self.data[self.features])
|
77 |
-
|
78 |
-
# Additional preprocessing for LSTM
|
79 |
-
if self.model_type == 'LSTM':
|
80 |
-
self.lstm_scaler = MinMaxScaler(feature_range=(0, 1))
|
81 |
-
self.data['Scaled_Close'] = self.lstm_scaler.fit_transform(self.data[['Close']])
|
82 |
|
83 |
-
def
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
return np.array(x), np.array(y)
|
90 |
|
91 |
def train_model(self):
|
92 |
try:
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
elif self.model_type == 'SARIMA':
|
110 |
-
train_data = self.data['Close']
|
111 |
-
# Use auto_arima to find optimal parameters
|
112 |
-
from pmdarima import auto_arima
|
113 |
-
auto_model = auto_arima(train_data, start_p=1, start_q=1, max_p=3, max_q=3, m=12,
|
114 |
-
start_P=0, seasonal=True, d=1, D=1, trace=True,
|
115 |
-
error_action='ignore', suppress_warnings=True, stepwise=True)
|
116 |
-
|
117 |
-
self.model = SARIMAX(train_data, order=auto_model.order, seasonal_order=auto_model.seasonal_order)
|
118 |
-
self.model = self.model.fit(disp=False)
|
119 |
-
|
120 |
-
elif self.model_type == 'Prophet':
|
121 |
-
df = self.data[['Date', 'Close']].rename(columns={'Date': 'ds', 'Close': 'y'})
|
122 |
-
self.model = Prophet(
|
123 |
-
changepoint_prior_scale=0.05,
|
124 |
-
seasonality_prior_scale=10,
|
125 |
-
holidays_prior_scale=10,
|
126 |
-
daily_seasonality=True,
|
127 |
-
weekly_seasonality=True,
|
128 |
-
yearly_seasonality=True
|
129 |
-
)
|
130 |
-
for feature in ['SMA_20', 'EMA_20', 'RSI', 'BB_High', 'BB_Low']:
|
131 |
-
self.model.add_regressor(feature)
|
132 |
-
df[feature] = self.data[feature]
|
133 |
-
self.model.fit(df)
|
134 |
-
|
135 |
-
elif self.model_type == 'XGBoost':
|
136 |
-
X = self.data[self.features]
|
137 |
-
y = self.data['Close']
|
138 |
-
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
|
139 |
-
|
140 |
-
param_grid = {
|
141 |
-
'max_depth': [3, 5],
|
142 |
-
'learning_rate': [0.01, 0.1],
|
143 |
-
'n_estimators': [100, 200]
|
144 |
-
}
|
145 |
-
model = xgb.XGBRegressor(objective='reg:squarederror')
|
146 |
-
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=3, n_jobs=-1, verbose=0)
|
147 |
-
grid_search.fit(X_train, y_train)
|
148 |
-
|
149 |
-
self.model = grid_search.best_estimator_
|
150 |
-
|
151 |
-
elif self.model_type == 'RandomForest':
|
152 |
-
X = self.data[self.features]
|
153 |
-
y = self.data['Close']
|
154 |
-
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
|
155 |
-
|
156 |
-
param_grid = {
|
157 |
-
'n_estimators': [100, 200],
|
158 |
-
'max_depth': [10, 20]
|
159 |
-
}
|
160 |
-
model = RandomForestRegressor(random_state=42)
|
161 |
-
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=3, n_jobs=-1, verbose=0)
|
162 |
-
grid_search.fit(X_train, y_train)
|
163 |
-
|
164 |
-
self.model = grid_search.best_estimator_
|
165 |
-
|
166 |
return True
|
167 |
-
|
168 |
except Exception as e:
|
169 |
-
print(f"Error training
|
170 |
return False
|
171 |
|
172 |
def predict(self, days=30):
|
173 |
try:
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
return self.lstm_scaler.inverse_transform(np.array(predictions).reshape(-1, 1)).flatten()
|
183 |
-
|
184 |
-
elif self.model_type == 'SARIMA':
|
185 |
-
forecast = self.model.get_forecast(steps=days)
|
186 |
-
return forecast.predicted_mean.values
|
187 |
-
|
188 |
-
elif self.model_type == 'Prophet':
|
189 |
-
future = self.model.make_future_dataframe(periods=days)
|
190 |
-
for feature in ['SMA_20', 'EMA_20', 'RSI', 'BB_High', 'BB_Low']:
|
191 |
-
future[feature] = self.data[feature].iloc[-1] # Use last known value
|
192 |
-
forecast = self.model.predict(future)
|
193 |
-
return forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']][-days:]
|
194 |
-
|
195 |
-
elif self.model_type in ['XGBoost', 'RandomForest']:
|
196 |
-
last_data = self.data[self.features].iloc[-1:].values
|
197 |
-
predictions = []
|
198 |
-
for _ in range(days):
|
199 |
-
pred = self.model.predict(last_data)
|
200 |
-
predictions.append(pred[0])
|
201 |
-
# Update last_data for next prediction
|
202 |
-
last_data = np.roll(last_data, -1, axis=1)
|
203 |
-
last_data[0, -5] = pred[0] # Assuming 'Close' is the 5th from last feature
|
204 |
-
return np.array(predictions)
|
205 |
-
|
206 |
except Exception as e:
|
207 |
-
print(f"Error predicting with
|
208 |
return None
|
209 |
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
216 |
|
217 |
def fetch_stock_data(ticker):
|
218 |
try:
|
@@ -349,7 +246,7 @@ def main():
|
|
349 |
predict_stock_prices()
|
350 |
|
351 |
def test_model():
|
352 |
-
st.header("Test
|
353 |
|
354 |
col1, col2 = st.columns(2)
|
355 |
|
@@ -357,9 +254,6 @@ def test_model():
|
|
357 |
company = st.selectbox("Select Company", [company for company, _ in COMPANIES])
|
358 |
test_split = st.slider("Test Data Split", 0.1, 0.5, 0.2, 0.05)
|
359 |
|
360 |
-
with col2:
|
361 |
-
model_type = st.selectbox("Select Model Type", ['Prophet', 'LSTM', 'SARIMA', 'XGBoost', 'RandomForest'])
|
362 |
-
|
363 |
if st.button("Train and Test Model"):
|
364 |
with st.spinner("Fetching data and training model..."):
|
365 |
company_name, ticker = next((name, symbol) for name, symbol in COMPANIES if name == company)
|
@@ -378,24 +272,30 @@ def test_model():
|
|
378 |
train_data = data.iloc[:split_index]
|
379 |
test_data = data.iloc[split_index:]
|
380 |
|
381 |
-
predictor = StockPredictor(train_data
|
382 |
predictor.preprocess_data()
|
383 |
if predictor.train_model():
|
384 |
test_pred = predictor.predict(days=len(test_data))
|
385 |
|
386 |
if test_pred is not None:
|
387 |
mse, mape, rmse = predictor.evaluate_model(test_data)
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
397 |
else:
|
398 |
-
st.error(
|
399 |
|
400 |
def predict_stock_prices():
|
401 |
st.header("Predict Stock Prices")
|
@@ -406,9 +306,6 @@ def predict_stock_prices():
|
|
406 |
company = st.selectbox("Select Company", [company for company, _ in COMPANIES])
|
407 |
days_to_predict = st.slider("Days to Predict", 1, 365, 30)
|
408 |
|
409 |
-
with col2:
|
410 |
-
model_type = st.selectbox("Select Model Type", ['Prophet', 'LSTM', 'SARIMA', 'XGBoost', 'RandomForest'])
|
411 |
-
|
412 |
if st.button("Predict Stock Prices"):
|
413 |
with st.spinner("Fetching data and making predictions..."):
|
414 |
company_name, ticker = next((name, symbol) for name, symbol in COMPANIES if name == company)
|
@@ -423,7 +320,7 @@ def predict_stock_prices():
|
|
423 |
|
424 |
st.markdown(get_table_download_link(data), unsafe_allow_html=True)
|
425 |
|
426 |
-
predictor = StockPredictor(data
|
427 |
predictor.preprocess_data()
|
428 |
if predictor.train_model():
|
429 |
predictions = predictor.predict(days=days_to_predict)
|
@@ -444,8 +341,10 @@ def predict_stock_prices():
|
|
444 |
st.subheader("Latest News")
|
445 |
for item in news:
|
446 |
st.markdown(f"[{item['title']}]({item['link']}) ({item['pubDate']})")
|
|
|
|
|
447 |
else:
|
448 |
-
st.error(
|
449 |
|
450 |
def explore_data():
|
451 |
st.header("Explore Stock Data")
|
|
|
36 |
]
|
37 |
|
38 |
class StockPredictor:
|
39 |
+
def __init__(self, data):
|
40 |
self.data = data
|
|
|
41 |
self.model = None
|
|
|
|
|
42 |
|
43 |
def preprocess_data(self):
|
44 |
+
# Prophet requires columns named 'ds' and 'y'
|
45 |
+
self.data = self.data.reset_index()
|
46 |
+
self.data = self.data.rename(columns={'Date': 'ds', 'Close': 'y'})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
|
48 |
+
# Add any additional features you want to use
|
49 |
+
self.data['SMA_20'] = self.data['y'].rolling(window=20).mean()
|
50 |
+
self.data['EMA_20'] = self.data['y'].ewm(span=20, adjust=False).mean()
|
51 |
+
self.data['RSI'] = self.calculate_rsi(self.data['y'], periods=14)
|
52 |
+
|
53 |
+
# Handle NaN values
|
54 |
+
self.data = self.data.dropna()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
+
def calculate_rsi(self, prices, periods=14):
|
57 |
+
delta = prices.diff()
|
58 |
+
gain = (delta.where(delta > 0, 0)).rolling(window=periods).mean()
|
59 |
+
loss = (-delta.where(delta < 0, 0)).rolling(window=periods).mean()
|
60 |
+
rs = gain / loss
|
61 |
+
return 100 - (100 / (1 + rs))
|
|
|
62 |
|
63 |
def train_model(self):
|
64 |
try:
|
65 |
+
self.model = Prophet(
|
66 |
+
changepoint_prior_scale=0.05,
|
67 |
+
seasonality_prior_scale=10,
|
68 |
+
holidays_prior_scale=10,
|
69 |
+
daily_seasonality=True,
|
70 |
+
weekly_seasonality=True,
|
71 |
+
yearly_seasonality=True
|
72 |
+
)
|
73 |
+
|
74 |
+
# Add additional regressors
|
75 |
+
self.model.add_regressor('SMA_20')
|
76 |
+
self.model.add_regressor('EMA_20')
|
77 |
+
self.model.add_regressor('RSI')
|
78 |
+
|
79 |
+
self.model.fit(self.data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
return True
|
|
|
81 |
except Exception as e:
|
82 |
+
print(f"Error training Prophet model: {str(e)}")
|
83 |
return False
|
84 |
|
85 |
def predict(self, days=30):
|
86 |
try:
|
87 |
+
future = self.model.make_future_dataframe(periods=days)
|
88 |
+
|
89 |
+
# Add regressor values for future dates
|
90 |
+
for feature in ['SMA_20', 'EMA_20', 'RSI']:
|
91 |
+
future[feature] = self.data[feature].iloc[-1] # Use last known value
|
92 |
+
|
93 |
+
forecast = self.model.predict(future)
|
94 |
+
return forecast
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
except Exception as e:
|
96 |
+
print(f"Error predicting with Prophet model: {str(e)}")
|
97 |
return None
|
98 |
|
99 |
+
def evaluate_model(self, test_data):
|
100 |
+
predictions = self.predict(days=len(test_data))
|
101 |
+
|
102 |
+
if predictions is None:
|
103 |
+
return None, None, None
|
104 |
+
|
105 |
+
actual = test_data['Close'].values
|
106 |
+
predicted = predictions['yhat'].values[-len(test_data):]
|
107 |
+
|
108 |
+
mse = mean_squared_error(actual, predicted)
|
109 |
+
mape = mean_absolute_percentage_error(actual, predicted)
|
110 |
+
rmse = np.sqrt(mse)
|
111 |
+
|
112 |
+
return mse, mape, rmse
|
113 |
|
114 |
def fetch_stock_data(ticker):
|
115 |
try:
|
|
|
246 |
predict_stock_prices()
|
247 |
|
248 |
def test_model():
|
249 |
+
st.header("Test Prophet Model")
|
250 |
|
251 |
col1, col2 = st.columns(2)
|
252 |
|
|
|
254 |
company = st.selectbox("Select Company", [company for company, _ in COMPANIES])
|
255 |
test_split = st.slider("Test Data Split", 0.1, 0.5, 0.2, 0.05)
|
256 |
|
|
|
|
|
|
|
257 |
if st.button("Train and Test Model"):
|
258 |
with st.spinner("Fetching data and training model..."):
|
259 |
company_name, ticker = next((name, symbol) for name, symbol in COMPANIES if name == company)
|
|
|
272 |
train_data = data.iloc[:split_index]
|
273 |
test_data = data.iloc[split_index:]
|
274 |
|
275 |
+
predictor = StockPredictor(train_data)
|
276 |
predictor.preprocess_data()
|
277 |
if predictor.train_model():
|
278 |
test_pred = predictor.predict(days=len(test_data))
|
279 |
|
280 |
if test_pred is not None:
|
281 |
mse, mape, rmse = predictor.evaluate_model(test_data)
|
282 |
+
|
283 |
+
if mse is not None and mape is not None and rmse is not None:
|
284 |
+
accuracy = 100 - mape * 100
|
285 |
+
|
286 |
+
st.subheader("Model Performance")
|
287 |
+
st.metric("Prediction Accuracy", f"{accuracy:.2f}%")
|
288 |
+
st.metric("Mean Squared Error", f"{mse:.4f}")
|
289 |
+
st.metric("Root Mean Squared Error", f"{rmse:.4f}")
|
290 |
+
|
291 |
+
plot = create_test_plot(predictor.data, test_data, test_pred, company_name)
|
292 |
+
st.plotly_chart(plot, use_container_width=True)
|
293 |
+
else:
|
294 |
+
st.error("Failed to evaluate the model. The evaluation metrics are None.")
|
295 |
+
else:
|
296 |
+
st.error("Failed to generate predictions. The predicted data is None.")
|
297 |
else:
|
298 |
+
st.error("Failed to train the Prophet model. Please try a different dataset.")
|
299 |
|
300 |
def predict_stock_prices():
|
301 |
st.header("Predict Stock Prices")
|
|
|
306 |
company = st.selectbox("Select Company", [company for company, _ in COMPANIES])
|
307 |
days_to_predict = st.slider("Days to Predict", 1, 365, 30)
|
308 |
|
|
|
|
|
|
|
309 |
if st.button("Predict Stock Prices"):
|
310 |
with st.spinner("Fetching data and making predictions..."):
|
311 |
company_name, ticker = next((name, symbol) for name, symbol in COMPANIES if name == company)
|
|
|
320 |
|
321 |
st.markdown(get_table_download_link(data), unsafe_allow_html=True)
|
322 |
|
323 |
+
predictor = StockPredictor(data)
|
324 |
predictor.preprocess_data()
|
325 |
if predictor.train_model():
|
326 |
predictions = predictor.predict(days=days_to_predict)
|
|
|
341 |
st.subheader("Latest News")
|
342 |
for item in news:
|
343 |
st.markdown(f"[{item['title']}]({item['link']}) ({item['pubDate']})")
|
344 |
+
else:
|
345 |
+
st.error("Failed to generate predictions. The predicted data is None.")
|
346 |
else:
|
347 |
+
st.error("Failed to train the Prophet model. Please try a different dataset.")
|
348 |
|
349 |
def explore_data():
|
350 |
st.header("Explore Stock Data")
|