-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2406 lines (1953 loc) · 85.7 KB
/
app.py
File metadata and controls
2406 lines (1953 loc) · 85.7 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# app.py
# Note: Remember to modify the api_key as described in the system documentation
# Authors: Du Hongzhou & Qi Legan (Team: Studio 6324)
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
from sklearn.preprocessing import MinMaxScaler, RobustScaler, StandardScaler
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, mean_absolute_percentage_error
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor, VotingRegressor
from sklearn.svm import SVR
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit, cross_val_score
import xgboost as xgb
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout, Bidirectional, GRU, Conv1D, MaxPooling1D, Flatten
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from tensorflow.keras.optimizers import Adam
import datetime
import joblib
import os
import tensorflow as tf
import time
from alpha_vantage.timeseries import TimeSeries
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.feature_selection import SelectKBest, f_regression, mutual_info_regression
import shap
import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller, acf, pacf
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.seasonal import seasonal_decompose
from scipy import stats
import ta
# Set Seaborn theme
sns.set_style('darkgrid') # or use sns.set_theme()
plt.rcParams['font.sans-serif'] = ['Arial']
plt.rcParams['axes.unicode_minus'] = False
# Function: Download stock data (Alpha Vantage)
@st.cache_data(ttl=3600) # Cache data for one hour
def download_stock_data_alpha_vantage(ticker, start_date, end_date, api_key, retries=3, delay=5):
ts = TimeSeries(key=api_key, output_format='pandas')
for attempt in range(retries):
try:
# Get daily stock data
data, meta_data = ts.get_daily(symbol=ticker, outputsize='full')
# Rename columns to match yfinance format
data = data.rename(columns={
'1. open': 'Open',
'2. high': 'High',
'3. low': 'Low',
'4. close': 'Close',
'5. volume': 'Volume'
})
# Convert index to datetime
data.index = pd.to_datetime(data.index)
# Filter date range
data = data[(data.index >= pd.to_datetime(start_date)) & (data.index <= pd.to_datetime(end_date))]
if data.empty:
st.error(
f"Could not download data for {ticker}. Please check if the ticker symbol is correct or adjust the date range.")
return data
except Exception as e:
st.warning(f"Error downloading data: {e}, attempting to download again ({attempt + 1}/{retries})...")
time.sleep(delay)
st.error(
"Could not download data after multiple attempts. Please try again later or check your network connection.")
return pd.DataFrame()
# Function: Get macroeconomic data (example)
@st.cache_data
def get_macro_data():
if os.path.exists('macro_data.csv'):
macro_data = pd.read_csv('macro_data.csv', parse_dates=['Date'])
return macro_data
else:
st.warning("Macroeconomic data file 'macro_data.csv' does not exist.")
return None
# Function: Check time series stationarity
def check_stationarity(time_series, window=12):
# Perform Augmented Dickey-Fuller test
result = adfuller(time_series.dropna())
# Create result dictionary
adf_result = {
'ADF Statistic': result[0],
'p-value': result[1],
'Lags': result[2],
'Observations': result[3],
'Critical Value (1%)': result[4]['1%'],
'Critical Value (5%)': result[4]['5%'],
'Critical Value (10%)': result[4]['10%']
}
# Perform seasonal decomposition
try:
decomposition = seasonal_decompose(time_series.dropna(), model='additive', period=window)
return adf_result, decomposition
except:
return adf_result, None
# Function: Calculate Commodity Channel Index (CCI)
def calculate_CCI(data, window=20):
TP = (data['High'] + data['Low'] + data['Close']) / 3
rolling_mean = TP.rolling(window=window).mean()
rolling_std = TP.rolling(window=window).std()
CCI = (TP - rolling_mean) / (0.015 * rolling_std)
return CCI
# Function: Calculate Average Directional Index (ADX)
def calculate_ADX(data, window=14):
plus_dm = data['High'].diff()
minus_dm = data['Low'].diff().abs() * -1
# Calculate directional movement indicators
plus_dm = plus_dm.where((plus_dm > minus_dm) & (plus_dm > 0), 0)
minus_dm = minus_dm.where((minus_dm < plus_dm) & (minus_dm < 0), 0)
# Calculate True Range (TR)
tr1 = data['High'] - data['Low']
tr2 = (data['High'] - data['Close'].shift(1)).abs()
tr3 = (data['Low'] - data['Close'].shift(1)).abs()
TR = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
# Calculate smoothed indicators
ATR = TR.rolling(window=window).mean()
plus_di = 100 * (plus_dm.rolling(window=window).mean() / ATR)
minus_di = 100 * (minus_dm.rolling(window=window).mean() / ATR)
# Calculate ADX
DX = 100 * (plus_di - minus_di).abs() / (plus_di + minus_di).abs()
ADX = DX.rolling(window=window).mean()
return ADX, plus_di, minus_di
# Function: Calculate Average True Range (ATR)
def calculate_ATR(data, window=14):
high_low = data['High'] - data['Low']
high_close_prev = np.abs(data['High'] - data['Close'].shift())
low_close_prev = np.abs(data['Low'] - data['Close'].shift())
TR = pd.concat([high_low, high_close_prev, low_close_prev], axis=1).max(axis=1)
ATR = TR.rolling(window=window, min_periods=window).mean()
return ATR
# Function: Calculate VWAP (Volume Weighted Average Price)
def calculate_VWAP(data):
data['TP'] = (data['High'] + data['Low'] + data['Close']) / 3
data['VWAP'] = (data['TP'] * data['Volume']).cumsum() / data['Volume'].cumsum()
return data['VWAP']
# Function: Calculate Accumulation/Distribution Line
def calculate_ADL(data):
mfm = ((data['Close'] - data['Low']) - (data['High'] - data['Close'])) / (data['High'] - data['Low'])
mfm = mfm.fillna(0.0) # Handle potential division by zero
mfv = mfm * data['Volume']
adl = mfv.cumsum()
return adl
# Function: Calculate Relative Strength Index (multiple periods)
def calculate_RSI(data, periods=[14, 7, 21]):
rsi_data = {}
close_delta = data['Close'].diff()
for period in periods:
# Calculate ups and downs
up = close_delta.clip(lower=0)
down = -1 * close_delta.clip(upper=0)
# Calculate EMA
ma_up = up.ewm(com=period - 1, adjust=True, min_periods=period).mean()
ma_down = down.ewm(com=period - 1, adjust=True, min_periods=period).mean()
# Calculate RSI
rsi = 100 - (100 / (1 + ma_up / ma_down))
rsi_data[f'RSI_{period}'] = rsi
return pd.DataFrame(rsi_data)
# Function: Data preprocessing
def preprocess_data(data, macro_data=None):
# Check and fill missing values
data = data.copy()
data.fillna(method='ffill', inplace=True)
# Ensure 'Close' is a one-dimensional Series
if isinstance(data['Close'].values, np.ndarray) and data['Close'].values.ndim > 1:
data['Close'] = pd.Series(data['Close'].values.squeeze(), index=data.index)
# Add debugging information
st.write(f"data['Close'] type: {type(data['Close'])}")
st.write(f"data['Close'] shape: {data['Close'].shape}")
# Calculate technical indicators
# Use Ta-Lib complete indicator library + custom indicators
# 1. Trend indicators
# RSI (multiple periods)
rsi_df = calculate_RSI(data, periods=[7, 14, 21])
for col in rsi_df.columns:
data[col] = rsi_df[col]
# MACD
data['EMA12'] = data['Close'].ewm(span=12, adjust=False).mean()
data['EMA26'] = data['Close'].ewm(span=26, adjust=False).mean()
data['MACD'] = data['EMA12'] - data['EMA26']
data['MACD_Signal'] = data['MACD'].ewm(span=9, adjust=False).mean()
data['MACD_Diff'] = data['MACD'] - data['MACD_Signal']
# Moving Averages (multiple periods)
windows = [5, 10, 20, 50, 100, 200]
for window in windows:
data[f'MA{window}'] = data['Close'].rolling(window=window).mean()
data[f'EMA{window}'] = data['Close'].ewm(span=window, adjust=False).mean()
# 2. Volatility indicators
# Bollinger Bands
for window in [20, 10, 50]:
data[f'Bollinger_Middle_{window}'] = data['Close'].rolling(window=window).mean()
data[f'Bollinger_Std_{window}'] = data['Close'].rolling(window=window).std()
data[f'Bollinger_High_{window}'] = data[f'Bollinger_Middle_{window}'] + (2 * data[f'Bollinger_Std_{window}'])
data[f'Bollinger_Low_{window}'] = data[f'Bollinger_Middle_{window}'] - (2 * data[f'Bollinger_Std_{window}'])
data[f'Bollinger_Width_{window}'] = data[f'Bollinger_High_{window}'] - data[f'Bollinger_Low_{window}']
data[f'Bollinger_%B_{window}'] = (data['Close'] - data[f'Bollinger_Low_{window}']) / (
data[f'Bollinger_High_{window}'] - data[f'Bollinger_Low_{window}'])
# 3. Momentum indicators
# Stochastic Oscillator
for window in [14, 7, 21]:
low_min = data['Low'].rolling(window=window).min()
high_max = data['High'].rolling(window=window).max()
data[f'Stochastic_%K_{window}'] = ((data['Close'] - low_min) / (high_max - low_min)) * 100
data[f'Stochastic_%D_{window}'] = data[f'Stochastic_%K_{window}'].rolling(window=3).mean()
# 4. Volume indicators
# On-Balance Volume (OBV)
obv = [0]
for i in range(1, len(data)):
if data['Close'].iloc[i] > data['Close'].iloc[i - 1]:
obv.append(obv[-1] + data['Volume'].iloc[i])
elif data['Close'].iloc[i] < data['Close'].iloc[i - 1]:
obv.append(obv[-1] - data['Volume'].iloc[i])
else:
obv.append(obv[-1])
data['OBV'] = obv
# Chaikin Money Flow (CMF)
for window in [20, 10, 30]:
mfv = ((data['Close'] - data['Low']) - (data['High'] - data['Close'])) / (
data['High'] - data['Low'] + 1e-12) # Avoid division by zero
mfv = mfv.fillna(0)
data[f'Chaikin_MF_{window}'] = (mfv * data['Volume']).rolling(window=window).sum() / data['Volume'].rolling(
window=window).sum()
# Accumulation/Distribution Line
data['ADL'] = calculate_ADL(data)
# VWAP
data['VWAP'] = calculate_VWAP(data)
# 5. Volatility indicators
# ATR
data['ATR'] = calculate_ATR(data)
# 6. Trend direction indicators
# ADX
data['ADX'], data['Plus_DI'], data['Minus_DI'] = calculate_ADX(data)
# 7. Other indicators
# Ichimoku Cloud
tenkan_window = 9
kijun_window = 26
senkou_span_b_window = 52
tenkan_sen = (data['High'].rolling(window=tenkan_window).max() + data['Low'].rolling(
window=tenkan_window).min()) / 2
kijun_sen = (data['High'].rolling(window=kijun_window).max() + data['Low'].rolling(window=kijun_window).min()) / 2
senkou_span_a = ((tenkan_sen + kijun_sen) / 2).shift(kijun_window)
senkou_span_b = ((data['High'].rolling(window=senkou_span_b_window).max() + data['Low'].rolling(
window=senkou_span_b_window).min()) / 2).shift(kijun_window)
data['Ichimoku_Tenkan'] = tenkan_sen
data['Ichimoku_Kijun'] = kijun_sen
data['Ichimoku_A'] = senkou_span_a
data['Ichimoku_B'] = senkou_span_b
data['Ichimoku_Chikou'] = data['Close'].shift(-kijun_window) # Lagging span
# CCI
data['CCI'] = calculate_CCI(data)
# Rate of Change (ROC) - multiple periods
for window in [1, 5, 10, 20, 60]:
data[f'ROC_{window}'] = data['Close'].pct_change(window) * 100
# Volatility
for window in [5, 10, 20, 30, 60]:
data[f'Volatility_{window}'] = data['Close'].rolling(window=window).std() / data['Close'].rolling(
window=window).mean() * 100
# Calculate trend change rate
for window in [5, 10, 20]:
data[f'Trend_Change_{window}'] = data['Close'].diff(window) / data['Close'].shift(window) * 100
# Calculate daily returns
data['Daily_Return'] = data['Close'].pct_change()
# Calculate log returns
data['Log_Return'] = np.log(data['Close'] / data['Close'].shift(1))
# Calculate cumulative returns
data['Cum_Return'] = (1 + data['Daily_Return']).cumprod()
# Position relative to N-day high/low
for window in [10, 20, 50, 100]:
data[f'Price_High_Ratio_{window}'] = data['Close'] / data['High'].rolling(window=window).max()
data[f'Price_Low_Ratio_{window}'] = data['Close'] / data['Low'].rolling(window=window).min()
# Volume relative change
data['Volume_Change'] = data['Volume'].pct_change()
data['Volume_MA10'] = data['Volume'].rolling(window=10).mean()
data['Volume_Ratio'] = data['Volume'] / data['Volume_MA10']
# Short-term mean reversion indicator
data['Mean_Reversion_3'] = (data['Close'] - data['Close'].rolling(window=3).mean()) / data['Close'].rolling(
window=3).std()
# Price pattern recognition features
data['Doji'] = ((data['Close'] - data['Open']).abs() / (data['High'] - data['Low'])) < 0.1
data['Long_Body'] = ((data['Close'] - data['Open']).abs() / (data['High'] - data['Low'])) > 0.7
# Remove missing values
data.dropna(inplace=True)
# If macroeconomic data is available, merge it
if macro_data is not None:
data = data.merge(macro_data, on='Date', how='left')
data.fillna(method='ffill', inplace=True)
data.dropna(inplace=True)
# Confirm 'ATR' was successfully added
if 'ATR' not in data.columns:
st.error("ATR calculation failed, 'ATR' column does not exist. Please check the data preprocessing steps.")
else:
st.write("'ATR' calculated successfully, data columns include:")
st.write(data.columns.tolist())
return data
# Function: Feature selection
def select_features(X, y, n_features=20):
# 1. F-test based feature selection
f_selector = SelectKBest(f_regression, k=n_features)
f_selector.fit(X, y)
f_scores = pd.DataFrame({'Feature': X.columns, 'F_Score': f_selector.scores_})
f_scores = f_scores.sort_values('F_Score', ascending=False)
# 2. Mutual information based feature selection
mi_selector = SelectKBest(mutual_info_regression, k=n_features)
mi_selector.fit(X, y)
mi_scores = pd.DataFrame({'Feature': X.columns, 'MI_Score': mi_selector.scores_})
mi_scores = mi_scores.sort_values('MI_Score', ascending=False)
# 3. Random Forest feature importance
rf = RandomForestRegressor(n_estimators=100, random_state=42)
rf.fit(X, y)
rf_importance = pd.DataFrame({'Feature': X.columns, 'RF_Importance': rf.feature_importances_})
rf_importance = rf_importance.sort_values('RF_Importance', ascending=False)
# 4. XGBoost feature importance
xgb_model = xgb.XGBRegressor(n_estimators=100, learning_rate=0.1, random_state=42)
xgb_model.fit(X, y)
xgb_importance = pd.DataFrame({'Feature': X.columns, 'XGB_Importance': xgb_model.feature_importances_})
xgb_importance = xgb_importance.sort_values('XGB_Importance', ascending=False)
# Combined ranking
combined_scores = f_scores.merge(mi_scores, on='Feature') \
.merge(rf_importance, on='Feature') \
.merge(xgb_importance, on='Feature')
# Normalize scores
for col in ['F_Score', 'MI_Score', 'RF_Importance', 'XGB_Importance']:
combined_scores[f'{col}_Norm'] = (combined_scores[col] - combined_scores[col].min()) / (
combined_scores[col].max() - combined_scores[col].min())
# Calculate total score
combined_scores['Total_Score'] = combined_scores['F_Score_Norm'] + combined_scores['MI_Score_Norm'] + \
combined_scores['RF_Importance_Norm'] + combined_scores['XGB_Importance_Norm']
# Sort by total score
combined_scores = combined_scores.sort_values('Total_Score', ascending=False)
# Select top n_features
selected_features = combined_scores.head(n_features)['Feature'].tolist()
return selected_features, combined_scores
# Function: Create LSTM dataset
def create_lstm_dataset(data, time_step=60, features=None, target='Close'):
"""
Create time series dataset for LSTM
"""
if features is None:
features = list(data.columns)
if target in features:
features.remove(target)
# Add target variable
features = [target] + features
# Extract feature data
dataset = data[features].values
X, y = [], []
for i in range(len(dataset) - time_step):
X.append(dataset[i:i + time_step])
y.append(dataset[i + time_step, 0]) # Target variable is the first column
return np.array(X), np.array(y)
# Function: Create dataset for traditional machine learning models
def create_ml_dataset(data, features, target='Close', lag_periods=[1, 5, 10, 20]):
"""
Create dataset for traditional machine learning models, including lagged features
"""
X = data[features].copy()
y = data[target]
# Add lagged features
for period in lag_periods:
for feature in features:
if feature != target: # Avoid lagging the target variable
X[f'{feature}_lag_{period}'] = data[feature].shift(period)
# Remove missing values
X = X.dropna()
y = y.loc[X.index]
return X, y
# Function: Build and train advanced LSTM model
def build_and_train_advanced_lstm(X_train, y_train, X_val, y_val, epochs=50, batch_size=64, patience=10):
"""
Build and train advanced LSTM model, including bidirectional LSTM and attention mechanism
"""
# Define early stopping and learning rate reduction callbacks
early_stopping = EarlyStopping(monitor='val_loss', patience=patience, restore_best_weights=True)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=patience // 2, min_lr=0.0001)
# Create model
model = Sequential()
# First layer: Bidirectional LSTM
model.add(Bidirectional(LSTM(64, return_sequences=True), input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dropout(0.3))
# Second layer: Regular LSTM
model.add(LSTM(64, return_sequences=False))
model.add(Dropout(0.3))
# Fully connected layers
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(16, activation='relu'))
model.add(Dense(1)) # Output layer
# Compile model
optimizer = Adam(learning_rate=0.001)
model.compile(optimizer=optimizer, loss='mean_squared_error')
# Train model
history = model.fit(
X_train, y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(X_val, y_val),
callbacks=[early_stopping, reduce_lr],
verbose=1
)
return model, history
# Function: Build and train CNN-LSTM hybrid model
def build_and_train_cnn_lstm(X_train, y_train, X_val, y_val, epochs=50, batch_size=64, patience=10):
"""
Build and train CNN-LSTM hybrid model for capturing local and global patterns in time series
"""
# Define early stopping and learning rate reduction callbacks
early_stopping = EarlyStopping(monitor='val_loss', patience=patience, restore_best_weights=True)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=patience // 2, min_lr=0.0001)
# Create model
model = Sequential()
# Convolutional layers for extracting local features
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', padding='same',
input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(MaxPooling1D(pool_size=2))
model.add(Conv1D(filters=128, kernel_size=3, activation='relu', padding='same'))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.3))
# LSTM layers for capturing sequential features
model.add(LSTM(100, return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(50, return_sequences=False))
model.add(Dropout(0.3))
# Fully connected layers
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(16, activation='relu'))
model.add(Dense(1)) # Output layer
# Compile model
optimizer = Adam(learning_rate=0.001)
model.compile(optimizer=optimizer, loss='mean_squared_error')
# Train model
history = model.fit(
X_train, y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(X_val, y_val),
callbacks=[early_stopping, reduce_lr],
verbose=1
)
return model, history
# Function: Build and train GRU model
def build_and_train_gru(X_train, y_train, X_val, y_val, epochs=50, batch_size=64, patience=10):
"""
Build and train GRU model as an alternative to LSTM
"""
# Define early stopping and learning rate reduction callbacks
early_stopping = EarlyStopping(monitor='val_loss', patience=patience, restore_best_weights=True)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=patience // 2, min_lr=0.0001)
# Create model
model = Sequential()
# GRU layers
model.add(GRU(64, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dropout(0.3))
model.add(GRU(64, return_sequences=False))
model.add(Dropout(0.3))
# Fully connected layers
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(16, activation='relu'))
model.add(Dense(1)) # Output layer
# Compile model
optimizer = Adam(learning_rate=0.001)
model.compile(optimizer=optimizer, loss='mean_squared_error')
# Train model
history = model.fit(
X_train, y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(X_val, y_val),
callbacks=[early_stopping, reduce_lr],
verbose=1
)
return model, history
# Function: Build and train enhanced traditional machine learning models
def build_and_train_advanced_ml_models(X_train, y_train, X_val=None, y_val=None, cv=5):
"""
Build and train enhanced traditional machine learning models, including hyperparameter tuning and model ensembling
"""
# Base models
base_models = {
'Random Forest': RandomForestRegressor(random_state=42),
'Gradient Boosting': GradientBoostingRegressor(random_state=42),
'Support Vector Machine': SVR(),
'XGBoost': xgb.XGBRegressor(random_state=42),
'AdaBoost': AdaBoostRegressor(random_state=42)
}
# Hyperparameter grids
param_grids = {
'Random Forest': {
'n_estimators': [50, 100, 200],
'max_depth': [None, 10, 20, 30],
'min_samples_split': [2, 5, 10],
'min_samples_leaf': [1, 2, 4]
},
'Gradient Boosting': {
'n_estimators': [50, 100, 200],
'learning_rate': [0.01, 0.1, 0.2],
'max_depth': [3, 5, 7],
'min_samples_split': [2, 5],
'min_samples_leaf': [1, 2]
},
'Support Vector Machine': {
'kernel': ['rbf', 'poly'],
'C': [0.1, 1, 10, 100],
'gamma': ['scale', 'auto', 0.1, 0.01]
},
'XGBoost': {
'n_estimators': [50, 100, 200],
'learning_rate': [0.01, 0.1, 0.2],
'max_depth': [3, 5, 7],
'colsample_bytree': [0.7, 0.8, 0.9]
},
'AdaBoost': {
'n_estimators': [50, 100, 200],
'learning_rate': [0.01, 0.1, 1.0]
}
}
# Time series cross-validation
tscv = TimeSeriesSplit(n_splits=cv)
# Train and tune models
trained_models = {}
best_params = {}
cv_scores = {}
for name, model in base_models.items():
# Use grid search for hyperparameter tuning
grid_search = GridSearchCV(
estimator=model,
param_grid=param_grids[name],
cv=tscv,
scoring='neg_mean_squared_error',
n_jobs=-1
)
grid_search.fit(X_train, y_train)
# Save best model and parameters
best_model = grid_search.best_estimator_
trained_models[name] = best_model
best_params[name] = grid_search.best_params_
# Calculate cross-validation scores
cv_score = cross_val_score(best_model, X_train, y_train, cv=tscv, scoring='neg_mean_squared_error')
cv_scores[name] = -cv_score.mean() # Convert back to MSE
# Create voting regressor
estimators = [(name, model) for name, model in trained_models.items()]
voting_regressor = VotingRegressor(estimators=estimators)
voting_regressor.fit(X_train, y_train)
# Add voting regressor to model dictionary
trained_models['Voting Ensemble'] = voting_regressor
# If validation set is provided, calculate validation scores
val_scores = {}
if X_val is not None and y_val is not None:
for name, model in trained_models.items():
predictions = model.predict(X_val)
val_scores[name] = mean_squared_error(y_val, predictions)
return trained_models, best_params, cv_scores, val_scores
# Function: Enhanced risk assessment
def assess_risk_advanced(real, predictions, window=20, threshold_volatility=1.5, threshold_drawdown=0.05,
confidence_level=0.95):
"""
Enhanced risk assessment, considering volatility, drawdown, and VaR
"""
# Create result DataFrame
df = pd.DataFrame({'Real': real, 'Predicted': predictions})
# Calculate prediction error
df['Error'] = df['Predicted'] - df['Real']
df['Percent_Error'] = df['Error'] / df['Real'] * 100
# Calculate volatility
df['Volatility'] = df['Real'].rolling(window=window).std() / df['Real'].rolling(window=window).mean()
# Calculate historical max versus current value (drawdown)
df['Cummax'] = df['Real'].cummax()
df['Drawdown'] = (df['Cummax'] - df['Real']) / df['Cummax']
# Calculate daily returns
df['Daily_Return'] = df['Real'].pct_change()
# Calculate historical VaR
df['VaR'] = df['Daily_Return'].rolling(window=window).quantile(1 - confidence_level)
# Risk assessment
# 1. Error-based risk
df['Risk_Error'] = np.where(np.abs(df['Percent_Error']) > threshold_volatility * df['Volatility'] * 100, 'High',
'Medium')
# 2. Volatility-based risk
df['Risk_Volatility'] = np.where(df['Volatility'] > threshold_volatility, 'High', 'Medium')
# 3. Drawdown-based risk
df['Risk_Drawdown'] = np.where(df['Drawdown'] > threshold_drawdown, 'High', 'Medium')
# 4. VaR-based risk
df['Risk_VaR'] = np.where(df['Daily_Return'] < df['VaR'], 'High', 'Medium')
# Comprehensive risk rating
risk_columns = ['Risk_Error', 'Risk_Volatility', 'Risk_Drawdown', 'Risk_VaR']
df['Risk_Count'] = df[risk_columns].apply(lambda x: (x == 'High').sum(), axis=1)
df['Risk_Level'] = pd.cut(
df['Risk_Count'],
bins=[-1, 0, 1, 2, 4],
labels=['Low', 'Medium', 'High', 'Very High']
)
return df
# Function: Calculate VaR and CVaR at different confidence levels
def calculate_var_cvar(returns, confidence_levels=[0.95, 0.99]):
"""
Calculate Value at Risk (VaR) and Conditional Value at Risk (CVaR) at different confidence levels
"""
var_results = {}
cvar_results = {}
for level in confidence_levels:
# Calculate VaR
var = returns.quantile(1 - level)
var_results[f'VaR_{int(level * 100)}'] = var
# Calculate CVaR (also known as Expected Shortfall)
cvar = returns[returns <= var].mean()
cvar_results[f'CVaR_{int(level * 100)}'] = cvar
return var_results, cvar_results
# Function: Monte Carlo simulation
def monte_carlo_simulation(data, n_simulations=1000, n_days=30, confidence_level=0.95):
"""
Use Monte Carlo simulation to forecast future stock price movements and risk
"""
# Calculate log returns
returns = np.log(1 + data['Close'].pct_change()).dropna()
# Calculate returns mean and standard deviation
mu = returns.mean()
sigma = returns.std()
# Last closing price
last_price = data['Close'].iloc[-1]
# Simulate paths
simulation_results = []
for _ in range(n_simulations):
# Generate random normal returns
random_returns = np.random.normal(mu, sigma, n_days)
# Calculate price path
price_path = [last_price]
for ret in random_returns:
price_path.append(price_path[-1] * np.exp(ret))
simulation_results.append(price_path)
# Convert to DataFrame
sim_df = pd.DataFrame(simulation_results).T
# Calculate daily VaR
daily_var = {}
for i in range(1, n_days + 1):
daily_prices = sim_df.loc[i]
daily_returns = (daily_prices - last_price) / last_price
var = np.percentile(daily_returns, (1 - confidence_level) * 100)
daily_var[i] = var
return sim_df, daily_var
# Function: Stress testing
def stress_test(model, data, features, target='Close', scenarios=None):
"""
Perform stress testing to simulate model performance under extreme market conditions
"""
if scenarios is None:
# Default stress scenarios
scenarios = {
'Mild Bear Market': {'factor': 0.95, 'volatility': 1.2}, # Price down 5%, volatility up 20%
'Severe Bear Market': {'factor': 0.8, 'volatility': 1.5}, # Price down 20%, volatility up 50%
'Market Crash': {'factor': 0.5, 'volatility': 2.0}, # Price down 50%, volatility doubled
'Mild Bull Market': {'factor': 1.05, 'volatility': 0.9}, # Price up 5%, volatility down 10%
'Strong Bull Market': {'factor': 1.2, 'volatility': 0.8} # Price up 20%, volatility down 20%
}
# Prepare test data
test_data = data.copy()
results = {}
for scenario_name, params in scenarios.items():
# Apply stress scenario
scenario_data = test_data.copy()
# Price-related features multiplied by factor
price_features = ['Open', 'High', 'Low', 'Close']
for feature in price_features:
if feature in scenario_data.columns:
scenario_data[feature] *= params['factor']
# Volatility-related features multiplied by volatility factor
volatility_features = [col for col in scenario_data.columns if
'volatility' in col.lower() or 'std' in col.lower()]
for feature in volatility_features:
scenario_data[feature] *= params['volatility']
# Prepare prediction data
X = scenario_data[features]
y_true = scenario_data[target]
# Prediction
y_pred = model.predict(X)
# Calculate evaluation metrics
mse = mean_squared_error(y_true, y_pred)
rmse = np.sqrt(mse)
mae = mean_absolute_error(y_true, y_pred)
mape = mean_absolute_percentage_error(y_true, y_pred)
r2 = r2_score(y_true, y_pred)
# Save results
results[scenario_name] = {
'MSE': mse,
'RMSE': rmse,
'MAE': mae,
'MAPE': mape,
'R2': r2,
'Predictions': y_pred
}
return results
# Function: Plot predictions (Plotly)
def plot_predictions(real, predictions, ticker, confidence_interval=None):
"""
Use Plotly to plot prediction results, optionally showing confidence intervals
"""
fig = go.Figure()
# Plot real values
fig.add_trace(go.Scatter(
x=real.index,
y=real,
mode='lines',
name='Actual Close Price',
line=dict(color='blue', width=2)
))
# Plot predicted values
fig.add_trace(go.Scatter(
x=predictions.index,
y=predictions,
mode='lines',
name='Predicted Close Price',
line=dict(color='red', width=2)
))
# If confidence interval is provided, add confidence bands
if confidence_interval is not None:
lower_bound = confidence_interval['lower']
upper_bound = confidence_interval['upper']
fig.add_trace(go.Scatter(
x=predictions.index,
y=upper_bound,
mode='lines',
line=dict(width=0),
showlegend=False
))
fig.add_trace(go.Scatter(
x=predictions.index,
y=lower_bound,
mode='lines',
line=dict(width=0),
fill='tonexty',
fillcolor='rgba(255, 0, 0, 0.2)',
name='95% Confidence Interval'
))
# Update layout
fig.update_layout(
title=f'{ticker} Close Price Prediction',
xaxis_title='Date',
yaxis_title='Price',
legend=dict(x=0, y=1),
template='plotly_white',
hovermode='x unified'
)
# Add range selector
fig.update_xaxes(
rangeslider_visible=True,
rangeselector=dict(
buttons=list([
dict(count=1, label="1m", step="month", stepmode="backward"),
dict(count=6, label="6m", step="month", stepmode="backward"),
dict(count=1, label="1y", step="year", stepmode="backward"),
dict(step="all")
])
)
)
st.plotly_chart(fig)
# Function: Plot risk heatmap
def plot_risk_heatmap(risk_df, ticker):
"""
Visualize risk distribution using a heatmap
"""
# Prepare heatmap data
heatmap_data = pd.crosstab(
risk_df['Risk_Volatility'],
risk_df['Risk_Error'],
values=risk_df['Drawdown'],
aggfunc='mean'
)
# Create heatmap
fig = px.imshow(
heatmap_data,
title=f'{ticker} Risk Heatmap (color represents average drawdown)',
color_continuous_scale='RdYlGn_r', # Red to green color map, red indicates high risk
labels=dict(x="Prediction Error Risk", y="Volatility Risk", color="Avg Drawdown")
)
# Update layout
fig.update_layout(
xaxis_title='Prediction Error Risk',
yaxis_title='Volatility Risk',
template='plotly_white'
)
st.plotly_chart(fig)
# Function: Plot Monte Carlo simulation results
def plot_monte_carlo(sim_df, ticker, last_price, confidence_level=0.95):
"""
Plot Monte Carlo simulation results
"""
fig = go.Figure()
# Add all simulation paths (to reduce clutter, only show 100 paths)
num_paths_to_show = min(100, sim_df.shape[1])
for i in range(num_paths_to_show):
fig.add_trace(go.Scatter(
y=sim_df[i],
mode='lines',
line=dict(width=0.5, color='rgba(70, 130, 180, 0.2)'),
showlegend=False
))
# Add mean path
mean_path = sim_df.mean(axis=1)
fig.add_trace(go.Scatter(
y=mean_path,
mode='lines',
line=dict(color='blue', width=2),
name='Mean Forecast Path'
))
# Add confidence interval
upper = sim_df.quantile(confidence_level, axis=1)
lower = sim_df.quantile(1 - confidence_level, axis=1)
fig.add_trace(go.Scatter(