-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2194 lines (2031 loc) · 102 KB
/
app.py
File metadata and controls
2194 lines (2031 loc) · 102 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
from flask import Flask, render_template, request, jsonify
import yfinance as yf
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from datetime import datetime, timedelta
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVR
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.decomposition import PCA
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import MinMaxScaler
from statsmodels.tsa.arima.model import ARIMA
from arch import arch_model
import xgboost as xgb
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Conv1D, MaxPooling1D, Flatten, SimpleRNN, GRU
import json
import os
from datetime import datetime, timedelta
from sklearn.cluster import KMeans
import logging
# 设置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
app = Flask(__name__)
# 扩展股票代码选项,至少 50 条
STOCK_OPTIONS = [
{'code': 'AAPL', 'name': 'Apple Inc.'},
{'code': 'MSFT', 'name': 'Microsoft Corporation'},
{'code': 'GOOGL', 'name': 'Alphabet Inc.'},
{'code': 'AMZN', 'name': 'Amazon.com Inc.'},
{'code': 'TSLA', 'name': 'Tesla Inc.'},
{'code': 'NVDA', 'name': 'NVIDIA Corporation'},
{'code': 'META', 'name': 'Meta Platforms Inc.'},
{'code': 'JPM', 'name': 'JPMorgan Chase & Co.'},
{'code': 'V', 'name': 'Visa Inc.'},
{'code': 'MA', 'name': 'Mastercard Incorporated'},
{'code': 'PYPL', 'name': 'PayPal Holdings Inc.'},
{'code': 'INTC', 'name': 'Intel Corporation'},
{'code': 'AMD', 'name': 'Advanced Micro Devices Inc.'},
{'code': 'NFLX', 'name': 'Netflix Inc.'},
{'code': 'DIS', 'name': 'Walt Disney Company'},
{'code': 'BA', 'name': 'Boeing Co.'},
{'code': 'GE', 'name': 'General Electric Company'},
{'code': 'F', 'name': 'Ford Motor Company'},
{'code': 'GM', 'name': 'General Motors Company'},
{'code': 'CAT', 'name': 'Caterpillar Inc.'},
{'code': 'XOM', 'name': 'Exxon Mobil Corporation'},
{'code': 'CVX', 'name': 'Chevron Corporation'},
{'code': 'PFE', 'name': 'Pfizer Inc.'},
{'code': 'MRNA', 'name': 'Moderna Inc.'},
{'code': 'JNJ', 'name': 'Johnson & Johnson'},
{'code': 'WMT', 'name': 'Walmart Inc.'},
{'code': 'TGT', 'name': 'Target Corporation'},
{'code': 'COST', 'name': 'Costco Wholesale Corporation'},
{'code': 'HD', 'name': 'Home Depot Inc.'},
{'code': 'LOW', 'name': "Lowe's Companies Inc."},
{'code': 'NKE', 'name': 'NIKE Inc.'},
{'code': 'SBUX', 'name': 'Starbucks Corporation'},
{'code': 'MCD', 'name': "McDonald's Corporation"},
{'code': 'KO', 'name': 'Coca-Cola Company'},
{'code': 'PEP', 'name': 'PepsiCo Inc.'},
{'code': 'PG', 'name': 'Procter & Gamble Company'},
{'code': 'UNH', 'name': 'UnitedHealth Group Incorporated'},
{'code': 'CSCO', 'name': 'Cisco Systems Inc.'},
{'code': 'ORCL', 'name': 'Oracle Corporation'},
{'code': 'IBM', 'name': 'International Business Machines Corporation'},
{'code': 'CRM', 'name': 'Salesforce Inc.'},
{'code': 'ADBE', 'name': 'Adobe Inc.'},
{'code': 'QCOM', 'name': 'Qualcomm Incorporated'},
{'code': 'TXN', 'name': 'Texas Instruments Incorporated'},
{'code': 'GS', 'name': 'Goldman Sachs Group Inc.'},
{'code': 'MS', 'name': 'Morgan Stanley'},
{'code': 'BAC', 'name': 'Bank of America Corporation'},
{'code': 'WFC', 'name': 'Wells Fargo & Company'},
{'code': 'C', 'name': 'Citigroup Inc.'},
{'code': 'UBER', 'name': 'Uber Technologies Inc.'},
{'code': 'LYFT', 'name': 'Lyft Inc.'}
]
def create_candlestick_chart(stock_data_dict):
"""创建K线图"""
fig = make_subplots(rows=4, cols=1, shared_xaxes=True,
vertical_spacing=0.05,
subplot_titles=('K线图', '成交量', 'MACD', 'RSI'),
row_heights=[0.4, 0.2, 0.2, 0.2])
stock_colors = {
'kline_increasing': '#FF0000',
'kline_decreasing': '#00FF00',
'ma5': '#FFA500',
'ma20': '#800080',
'volume': '#808080',
'macd': '#0000FF',
'signal': '#FF4500',
'macd_hist': '#A9A9A9',
'rsi': '#FF00FF'
}
for stock_code, df in stock_data_dict.items():
# 计算技术指标
df['ma5'] = df['close'].rolling(window=5).mean()
df['ma20'] = df['close'].rolling(window=20).mean()
ema12 = df['close'].ewm(span=12, adjust=False).mean()
ema26 = df['close'].ewm(span=26, adjust=False).mean()
df['macd'] = ema12 - ema26
df['signal'] = df['macd'].ewm(span=9, adjust=False).mean()
df['macd_hist'] = df['macd'] - df['signal']
delta = df['close'].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
rs = gain / loss
df['rsi'] = 100 - (100 / (1 + rs))
fig.add_trace(go.Candlestick(
x=df['trade_date'],
open=df['open'],
high=df['high'],
low=df['low'],
close=df['close'],
name=f'{stock_code} K线',
increasing_line_color=stock_colors['kline_increasing'],
decreasing_line_color=stock_colors['kline_decreasing'],
increasing_fillcolor=stock_colors['kline_increasing'],
decreasing_fillcolor=stock_colors['kline_decreasing']
), row=1, col=1)
fig.add_trace(go.Scatter(
x=df['trade_date'], y=df['ma5'], name=f'{stock_code} MA5',
line=dict(color=stock_colors['ma5'], dash='dash')
), row=1, col=1)
fig.add_trace(go.Scatter(
x=df['trade_date'], y=df['ma20'], name=f'{stock_code} MA20',
line=dict(color=stock_colors['ma20'], dash='dot')
), row=1, col=1)
fig.add_trace(go.Bar(
x=df['trade_date'], y=df['vol'], name=f'{stock_code} 成交量',
marker_color=stock_colors['volume'], opacity=0.5
), row=2, col=1)
fig.add_trace(go.Scatter(
x=df['trade_date'], y=df['macd'], name=f'{stock_code} MACD',
line=dict(color=stock_colors['macd'])
), row=3, col=1)
fig.add_trace(go.Scatter(
x=df['trade_date'], y=df['signal'], name=f'{stock_code} Signal',
line=dict(color=stock_colors['signal'], dash='dash')
), row=3, col=1)
fig.add_trace(go.Bar(
x=df['trade_date'], y=df['macd_hist'], name=f'{stock_code} MACD Hist',
marker_color=stock_colors['macd_hist'], opacity=0.5
), row=3, col=1)
fig.add_trace(go.Scatter(
x=df['trade_date'], y=df['rsi'], name=f'{stock_code} RSI',
line=dict(color=stock_colors['rsi'])
), row=4, col=1)
fig.update_layout(
title='多股对比分析',
yaxis_title='价格',
template='plotly_white',
xaxis_rangeslider_visible=False,
height=1200,
showlegend=True,
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
updatemenus=[
dict(
type="buttons",
direction="left",
buttons=[
dict(label="导出PNG", method="relayout", args=[{"export": "png"}]),
dict(label="全屏", method="relayout", args=[{"fullscreen": True}])
],
pad={"r": 10, "t": 10},
showactive=True,
x=0.11,
xanchor="left",
y=1.1,
yanchor="top"
)
],
plot_bgcolor='#F5F5F5',
paper_bgcolor='#FFFFFF'
)
fig.update_xaxes(title_text='日期', row=4, col=1, gridcolor='#E0E0E0')
fig.update_yaxes(title_text='价格', row=1, col=1, gridcolor='#E0E0E0')
fig.update_yaxes(title_text='成交量', row=2, col=1, gridcolor='#E0E0E0')
fig.update_yaxes(title_text='MACD', row=3, col=1, gridcolor='#E0E0E0')
fig.update_yaxes(title_text='RSI', row=4, col=1, range=[0, 100], gridcolor='#E0E0E0')
return fig.to_json()
# 获取股票数据
def get_stock_data(stock_codes, start_date, end_date, look_back_days=None, multi_stock=False):
try:
if isinstance(stock_codes, str):
stock_codes = [stock_codes]
fetch_start = start_date
if look_back_days:
fetch_start = (pd.to_datetime(start_date) - timedelta(days=look_back_days)).strftime('%Y-%m-%d')
data = {}
for code in stock_codes:
ticker = yf.Ticker(code)
df = ticker.history(start=fetch_start, end=end_date)
if df.empty:
logger.warning(f"{code} 数据为空")
continue
df = df.reset_index()
df = df.rename(columns={
'Date': 'trade_date',
'Open': 'open',
'High': 'high',
'Low': 'low',
'Close': 'close',
'Volume': 'vol'
})
df['trade_date'] = pd.to_datetime(df['trade_date'])
# 计算 MA20 和 MA50
df['MA20'] = df['close'].rolling(window=20).mean()
df['MA50'] = df['close'].rolling(window=50).mean()
# 检查数据是否足够计算 MA20 和 MA50
if len(df) < 50:
logger.warning(f"{code} 数据不足以计算 MA50 (需要至少 50 天数据),当前数据量: {len(df)}")
df['MA20'] = df['MA20'].fillna(method='ffill') # 前向填充
df['MA50'] = df['MA50'].fillna(method='ffill')
if df['MA20'].isna().all() or df['MA50'].isna().all():
logger.warning(f"{code} 无法计算有效的 MA20 或 MA50,跳过")
continue
data[code] = df
if not data:
logger.error("所有股票数据获取失败")
return None
if multi_stock:
return data
elif look_back_days:
code = stock_codes[0]
df_look_back = data[code][data[code]['trade_date'] < pd.to_datetime(start_date)]
df_main = data[code][data[code]['trade_date'] >= pd.to_datetime(start_date)]
return df_look_back, df_main
else:
code = stock_codes[0]
return data[code]
except Exception as e:
logger.error(f"获取股票数据失败: {e}")
return None
# 获取股票信息
def get_stock_info(stock_code):
try:
ticker = yf.Ticker(stock_code)
info = ticker.info
return {
'code': stock_code,
'name': info.get('longName', 'N/A'),
'industry': info.get('industry', 'N/A'),
'market': info.get('exchange', 'N/A'),
'pe_ratio': info.get('trailingPE', None),
'market_cap': info.get('marketCap', None),
'dividend_yield': info.get('dividendYield', None)
}
except Exception as e:
logger.error(f"获取 {stock_code} 信息失败: {e}")
return None
def prepare_data(df, look_back=60, train_ratio=0.8):
data = df['open'].values.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
X, y = [], []
for i in range(look_back, len(scaled_data)):
X.append(scaled_data[i - look_back:i, 0])
y.append(scaled_data[i, 0])
X, y = np.array(X), np.array(y)
train_size = int(len(X) * train_ratio)
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]
train_start = df['trade_date'][look_back].strftime('%Y-%m-%d')
train_end = df['trade_date'][look_back + train_size - 1].strftime('%Y-%m-%d')
test_start = df['trade_date'][look_back + train_size].strftime('%Y-%m-%d')
test_end = df['trade_date'].iloc[-1].strftime('%Y-%m-%d')
split_info = {
'train_start': train_start,
'train_end': train_end,
'train_size': len(y_train),
'test_start': test_start,
'test_end': test_end,
'test_size': len(y_test)
}
return X_train, X_test, y_train, y_test, scaler, data, split_info
# 统一的 calculate_metrics 函数
def calculate_metrics(data, initial_cash=None, y_true=None, y_pred=None, mode='simulation'):
try:
if mode == 'simulation':
if initial_cash is None:
raise ValueError("仿真模式需要提供 initial_cash")
if isinstance(data, pd.DataFrame):
if 'Portfolio_Value' not in data.columns:
raise ValueError("仿真模式需要提供包含 'Portfolio_Value' 列的 DataFrame")
portfolio_value = data['Portfolio_Value']
elif isinstance(data, pd.Series):
portfolio_value = data
else:
raise ValueError("仿真模式的 data 必须是 DataFrame 或 Series")
portfolio_returns = portfolio_value.pct_change().dropna()
total_return = (portfolio_value.iloc[-1] - initial_cash) / initial_cash * 100
max_drawdown = ((portfolio_value.cummax() - portfolio_value) / portfolio_value.cummax()).max() * 100
sharpe_ratio = portfolio_returns.mean() / portfolio_returns.std() * np.sqrt(252) if portfolio_returns.std() != 0 else 0
metrics = {
'total_return': round(total_return, 2),
'max_drawdown': round(max_drawdown, 2),
'sharpe_ratio': round(sharpe_ratio, 2)
}
return metrics
elif mode == 'prediction':
if y_true is None or y_pred is None:
raise ValueError("预测模式需要提供 y_true 和 y_pred")
if len(y_true) != len(y_pred):
raise ValueError("y_true 和 y_pred 长度不匹配")
rmse = np.sqrt(mean_squared_error(y_true, y_pred))
mae = mean_absolute_error(y_true, y_pred)
r2 = r2_score(y_true, y_pred)
direction_accuracy = np.mean((np.sign(y_pred[1:] - y_pred[:-1]) == np.sign(y_true[1:] - y_true[:-1])).astype(int))
metrics = {
'rmse': round(rmse, 2),
'mae': round(mae, 2),
'r2': round(r2, 2),
'accuracy': round(direction_accuracy * 100, 2)
}
return metrics
else:
raise ValueError("未知模式,请指定 'simulation' 或 'prediction'")
except Exception as e:
logger.error(f"计算指标失败: {e}")
return None
def train_linear_regression(X_train, X_test, y_train, y_test, scaler, y_test_raw, params):
model = LinearRegression()
model.fit(X_train, y_train)
y_pred_train = model.predict(X_train)
y_pred_test = model.predict(X_test)
y_pred_train = scaler.inverse_transform(y_pred_train.reshape(-1, 1)).flatten()
y_pred_test = scaler.inverse_transform(y_pred_test.reshape(-1, 1)).flatten()
y_train = scaler.inverse_transform(y_train.reshape(-1, 1)).flatten()
y_test = scaler.inverse_transform(y_test.reshape(-1, 1)).flatten()
metrics = calculate_metrics(y_test, y_pred_test, y_test_raw)
return model, y_pred_train, y_pred_test, y_train, y_test, metrics
def train_arima(df, params):
p, d, q = int(params.get('p', 5)), int(params.get('d', 1)), int(params.get('q', 0))
model = ARIMA(df['open'], order=(p, d, q))
model_fit = model.fit()
train_size = int(len(df) * float(params.get('train_ratio', 0.8)))
y_train = df['open'][:train_size].values
y_test = df['open'][train_size:].values
y_pred_train = model_fit.predict(start=0, end=train_size - 1)
y_pred_test = model_fit.predict(start=train_size, end=len(df) - 1)
metrics = calculate_metrics(y_test, y_pred_test, y_test)
return model_fit, y_pred_train, y_pred_test, y_train, y_test, metrics
def train_garch(df, params):
train_size = int(len(df) * float(params.get('train_ratio', 0.8)))
train_data = df['open'][:train_size]
test_data = df['open'][train_size:]
model = arch_model(train_data, vol='Garch', p=int(params.get('garch_p', 1)), q=int(params.get('garch_q', 1)))
model_fit = model.fit(disp='off')
forecast = model_fit.forecast(horizon=len(test_data))
y_pred_test = train_data.iloc[-1] + np.cumsum(forecast.mean.values[-1, :])
y_pred_train = model_fit.conditional_volatility + train_data
y_train = train_data.values
y_test = test_data.values
metrics = calculate_metrics(y_test, y_pred_test, y_test)
return model_fit, y_pred_train, y_pred_test, y_train, y_test, metrics
def train_random_forest(X_train, X_test, y_train, y_test, scaler, y_test_raw, params):
model = RandomForestRegressor(n_estimators=int(params.get('n_estimators', 100)),
max_depth=int(params.get('max_depth', 10)), random_state=42)
model.fit(X_train, y_train)
y_pred_train = model.predict(X_train)
y_pred_test = model.predict(X_test)
y_pred_train = scaler.inverse_transform(y_pred_train.reshape(-1, 1)).flatten()
y_pred_test = scaler.inverse_transform(y_pred_test.reshape(-1, 1)).flatten()
y_train = scaler.inverse_transform(y_train.reshape(-1, 1)).flatten()
y_test = scaler.inverse_transform(y_test.reshape(-1, 1)).flatten()
metrics = calculate_metrics(y_test, y_pred_test, y_test_raw)
return model, y_pred_train, y_pred_test, y_train, y_test, metrics
def train_xgboost(X_train, X_test, y_train, y_test, scaler, y_test_raw, params):
model = xgb.XGBRegressor(objective='reg:squarederror', n_estimators=int(params.get('n_estimators', 100)),
max_depth=int(params.get('max_depth', 6)))
model.fit(X_train, y_train)
y_pred_train = model.predict(X_train)
y_pred_test = model.predict(X_test)
y_pred_train = scaler.inverse_transform(y_pred_train.reshape(-1, 1)).flatten()
y_pred_test = scaler.inverse_transform(y_pred_test.reshape(-1, 1)).flatten()
y_train = scaler.inverse_transform(y_train.reshape(-1, 1)).flatten()
y_test = scaler.inverse_transform(y_test.reshape(-1, 1)).flatten()
metrics = calculate_metrics(y_test, y_pred_test, y_test_raw)
return model, y_pred_train, y_pred_test, y_train, y_test, metrics
def train_svm(X_train, X_test, y_train, y_test, scaler, y_test_raw, params):
model = SVR(kernel=params.get('kernel', 'rbf'), C=float(params.get('C', 1.0)))
model.fit(X_train, y_train)
y_pred_train = model.predict(X_train)
y_pred_test = model.predict(X_test)
y_pred_train = scaler.inverse_transform(y_pred_train.reshape(-1, 1)).flatten()
y_pred_test = scaler.inverse_transform(y_pred_test.reshape(-1, 1)).flatten()
y_train = scaler.inverse_transform(y_train.reshape(-1, 1)).flatten()
y_test = scaler.inverse_transform(y_test.reshape(-1, 1)).flatten()
metrics = calculate_metrics(y_test, y_pred_test, y_test_raw)
return model, y_pred_train, y_pred_test, y_train, y_test, metrics
def train_lstm(X_train, X_test, y_train, y_test, scaler, y_test_raw, params):
X_train_3d = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
X_test_3d = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
model = Sequential()
model.add(LSTM(int(params.get('units', 50)), return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(LSTM(int(params.get('units', 50))))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
model.fit(X_train_3d, y_train, epochs=int(params.get('epochs', 50)), batch_size=32, verbose=0)
y_pred_train = model.predict(X_train_3d)
y_pred_test = model.predict(X_test_3d)
y_pred_train = scaler.inverse_transform(y_pred_train).flatten()
y_pred_test = scaler.inverse_transform(y_pred_test).flatten()
y_train = scaler.inverse_transform(y_train.reshape(-1, 1)).flatten()
y_test = scaler.inverse_transform(y_test.reshape(-1, 1)).flatten()
metrics = calculate_metrics(y_test, y_pred_test, y_test_raw)
return model, y_pred_train, y_pred_test, y_train, y_test, metrics
def train_cnn(X_train, X_test, y_train, y_test, scaler, y_test_raw, params):
X_train_3d = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
X_test_3d = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
model = Sequential()
model.add(
Conv1D(filters=int(params.get('filters', 32)), kernel_size=int(params.get('kernel_size', 3)), activation='relu',
input_shape=(X_train.shape[1], 1)))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(50, activation='relu'))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
model.fit(X_train_3d, y_train, epochs=int(params.get('epochs', 50)), batch_size=32, verbose=0)
y_pred_train = model.predict(X_train_3d)
y_pred_test = model.predict(X_test_3d)
y_pred_train = scaler.inverse_transform(y_pred_train).flatten()
y_pred_test = scaler.inverse_transform(y_pred_test).flatten()
y_train = scaler.inverse_transform(y_train.reshape(-1, 1)).flatten()
y_test = scaler.inverse_transform(y_test.reshape(-1, 1)).flatten()
metrics = calculate_metrics(y_test, y_pred_test, y_test_raw)
return model, y_pred_train, y_pred_test, y_train, y_test, metrics
def train_rnn(X_train, X_test, y_train, y_test, scaler, y_test_raw, params):
X_train_3d = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
X_test_3d = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
model = Sequential()
model.add(SimpleRNN(int(params.get('units', 50)), return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(SimpleRNN(int(params.get('units', 50))))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
model.fit(X_train_3d, y_train, epochs=int(params.get('epochs', 50)), batch_size=32, verbose=0)
y_pred_train = model.predict(X_train_3d)
y_pred_test = model.predict(X_test_3d)
y_pred_train = scaler.inverse_transform(y_pred_train).flatten()
y_pred_test = scaler.inverse_transform(y_pred_test).flatten()
y_train = scaler.inverse_transform(y_train.reshape(-1, 1)).flatten()
y_test = scaler.inverse_transform(y_test.reshape(-1, 1)).flatten()
metrics = calculate_metrics(y_test, y_pred_test, y_test_raw)
return model, y_pred_train, y_pred_test, y_train, y_test, metrics
def train_gru(X_train, X_test, y_train, y_test, scaler, y_test_raw, params):
X_train_3d = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
X_test_3d = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
model = Sequential()
model.add(GRU(int(params.get('units', 50)), return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(GRU(int(params.get('units', 50))))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
model.fit(X_train_3d, y_train, epochs=int(params.get('epochs', 50)), batch_size=32, verbose=0)
y_pred_train = model.predict(X_train_3d)
y_pred_test = model.predict(X_test_3d)
y_pred_train = scaler.inverse_transform(y_pred_train).flatten()
y_pred_test = scaler.inverse_transform(y_pred_test).flatten()
y_train = scaler.inverse_transform(y_train.reshape(-1, 1)).flatten()
y_test = scaler.inverse_transform(y_test.reshape(-1, 1)).flatten()
metrics = calculate_metrics(y_test, y_pred_test, y_test_raw)
return model, y_pred_train, y_pred_test, y_train, y_test, metrics
def predict_future(model, last_sequence, scaler, days, is_sequence_model=False):
future_preds = []
current_sequence = last_sequence.copy()
for _ in range(days):
if is_sequence_model:
pred = model.predict(current_sequence.reshape(1, current_sequence.shape[0], 1), verbose=0)
else:
pred = model.predict(current_sequence.reshape(1, -1))
future_preds.append(pred[0] if is_sequence_model else pred)
current_sequence = np.roll(current_sequence, -1)
current_sequence[-1] = pred[0] if is_sequence_model else pred
future_preds = scaler.inverse_transform(np.array(future_preds).reshape(-1, 1)).flatten()
return future_preds
def create_forecast_chart(df, y_train, y_pred_train, y_test, y_pred_test, future_preds, future_dates):
fig = go.Figure()
fig.add_trace(go.Scatter(x=df['trade_date'], y=df['open'], name='历史开盘价', line=dict(color='blue')))
train_dates = df['trade_date'][60:60 + len(y_train)]
fig.add_trace(go.Scatter(x=train_dates, y=y_pred_train, name='训练集预测', line=dict(color='orange', dash='dash')))
test_dates = df['trade_date'][60 + len(y_train):]
fig.add_trace(go.Scatter(x=test_dates, y=y_pred_test, name='测试集预测', line=dict(color='green', dash='dash')))
fig.add_trace(go.Scatter(x=future_dates, y=future_preds, name='未来预测', line=dict(color='red')))
fig.update_layout(
title='开盘价时间序列预测',
xaxis_title='日期',
yaxis_title='开盘价',
template='plotly_white',
height=600,
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
)
return fig.to_json()
# MACD 策略(引入买入成本)
def macd_strategy(df, initial_cash, max_holding, params, stock_code=''):
short_period = int(params.get('macd_short', 12))
long_period = int(params.get('macd_long', 26))
signal_period = int(params.get('macd_signal', 9))
df['EMA_short'] = df['close'].ewm(span=short_period, adjust=False).mean()
df['EMA_long'] = df['close'].ewm(span=long_period, adjust=False).mean()
df['MACD'] = df['EMA_short'] - df['EMA_long']
df['Signal'] = df['MACD'].ewm(span=signal_period, adjust=False).mean()
df['Position'] = 0
cash = initial_cash
holdings = 0
portfolio_value = [initial_cash]
trade_log = []
total_cost = 0 # 累计买入成本
total_shares = 0 # 累计买入股数
for i in range(1, len(df)):
prev_holdings = holdings
if df['MACD'].iloc[i] > df['Signal'].iloc[i] and df['MACD'].iloc[i-1] <= df['Signal'].iloc[i-1] and holdings < max_holding:
shares_to_buy = min(max_holding - holdings, int(cash / df['close'].iloc[i]))
if shares_to_buy > 0:
cost = shares_to_buy * df['close'].iloc[i]
cash -= cost
holdings += shares_to_buy
total_cost += cost
total_shares += shares_to_buy
trade_log.append({
'date': df['trade_date'].iloc[i],
'stock': stock_code,
'action': 'Buy',
'shares': shares_to_buy,
'price': round(df['close'].iloc[i], 2),
'profit': 0,
'holding_value': round(holdings * df['close'].iloc[i], 2)
})
elif df['MACD'].iloc[i] < df['Signal'].iloc[i] and df['MACD'].iloc[i-1] >= df['Signal'].iloc[i-1] and holdings > 0:
avg_cost = total_cost / total_shares if total_shares > 0 else 0
profit = (df['close'].iloc[i] - avg_cost) * holdings
cash += holdings * df['close'].iloc[i]
trade_log.append({
'date': df['trade_date'].iloc[i],
'stock': stock_code,
'action': 'Sell',
'shares': holdings,
'price': round(df['close'].iloc[i], 2),
'profit': round(profit, 2),
'holding_value': 0
})
total_cost = 0
total_shares = 0
holdings = 0
df.loc[df.index[i], 'Position'] = holdings
portfolio_value.append(cash + holdings * df['close'].iloc[i])
df['Portfolio_Value'] = pd.Series(portfolio_value, index=df.index)
return df, trade_log
# 多因子评分策略(引入买入成本)
def multi_factor_strategy(df, initial_cash, max_holding, params, stock_code=''):
momentum_period = int(params.get('momentum_period', 20))
df['Momentum'] = df['close'].pct_change(momentum_period)
df['Volatility'] = df['close'].rolling(momentum_period).std()
df['Score'] = (df['Momentum'] / df['Volatility']).rank()
df['Position'] = 0
cash = initial_cash
holdings = 0
portfolio_value = [initial_cash] * momentum_period
trade_log = []
total_cost = 0
total_shares = 0
for i in range(momentum_period, len(df)):
prev_holdings = holdings
if df['Score'].iloc[i] > df['Score'].quantile(0.75) and holdings < max_holding:
shares_to_buy = min(max_holding - holdings, int(cash / df['close'].iloc[i]))
if shares_to_buy > 0:
cost = shares_to_buy * df['close'].iloc[i]
cash -= cost
holdings += shares_to_buy
total_cost += cost
total_shares += shares_to_buy
trade_log.append({
'date': df['trade_date'].iloc[i],
'stock': stock_code,
'action': 'Buy',
'shares': shares_to_buy,
'price': round(df['close'].iloc[i], 2),
'profit': 0,
'holding_value': round(holdings * df['close'].iloc[i], 2)
})
elif df['Score'].iloc[i] < df['Score'].quantile(0.25) and holdings > 0:
avg_cost = total_cost / total_shares if total_shares > 0 else 0
profit = (df['close'].iloc[i] - avg_cost) * holdings
cash += holdings * df['close'].iloc[i]
trade_log.append({
'date': df['trade_date'].iloc[i],
'stock': stock_code,
'action': 'Sell',
'shares': holdings,
'price': round(df['close'].iloc[i], 2),
'profit': round(profit, 2),
'holding_value': 0
})
total_cost = 0
total_shares = 0
holdings = 0
df.loc[df.index[i], 'Position'] = holdings
portfolio_value.append(cash + holdings * df['close'].iloc[i])
df['Portfolio_Value'] = pd.Series(portfolio_value, index=df.index)
return df, trade_log
# 换手率和成交量策略(引入买入成本)
def turnover_volume_strategy(df, initial_cash, max_holding, params, stock_code=''):
volume_period = int(params.get('volume_period', 20))
df['Turnover'] = df['vol'] / df['close']
df['Volume_MA'] = df['vol'].rolling(volume_period).mean()
df['Position'] = 0
cash = initial_cash
holdings = 0
portfolio_value = [initial_cash] * volume_period
trade_log = []
total_cost = 0
total_shares = 0
for i in range(volume_period, len(df)):
prev_holdings = holdings
if df['Turnover'].iloc[i] > df['Turnover'].quantile(0.75) and df['vol'].iloc[i] > df['Volume_MA'].iloc[i] and holdings < max_holding:
shares_to_buy = min(max_holding - holdings, int(cash / df['close'].iloc[i]))
if shares_to_buy > 0:
cost = shares_to_buy * df['close'].iloc[i]
cash -= cost
holdings += shares_to_buy
total_cost += cost
total_shares += shares_to_buy
trade_log.append({
'date': df['trade_date'].iloc[i],
'stock': stock_code,
'action': 'Buy',
'shares': shares_to_buy,
'price': round(df['close'].iloc[i], 2),
'profit': 0,
'holding_value': round(holdings * df['close'].iloc[i], 2)
})
elif df['Turnover'].iloc[i] < df['Turnover'].quantile(0.25) and holdings > 0:
avg_cost = total_cost / total_shares if total_shares > 0 else 0
profit = (df['close'].iloc[i] - avg_cost) * holdings
cash += holdings * df['close'].iloc[i]
trade_log.append({
'date': df['trade_date'].iloc[i],
'stock': stock_code,
'action': 'Sell',
'shares': holdings,
'price': round(df['close'].iloc[i], 2),
'profit': round(profit, 2),
'holding_value': 0
})
total_cost = 0
total_shares = 0
holdings = 0
df.loc[df.index[i], 'Position'] = holdings
portfolio_value.append(cash + holdings * df['close'].iloc[i])
df['Portfolio_Value'] = pd.Series(portfolio_value, index=df.index)
return df, trade_log
# 均线交叉策略(引入买入成本)
def ma_crossover_strategy(df, initial_cash, max_holding, params, stock_code=''):
short_period = int(params.get('ma_short', 10))
long_period = int(params.get('ma_long', 50))
df['MA_short'] = df['close'].rolling(short_period).mean()
df['MA_long'] = df['close'].rolling(long_period).mean()
df['Position'] = 0
cash = initial_cash
holdings = 0
portfolio_value = [initial_cash] * long_period
trade_log = []
total_cost = 0
total_shares = 0
for i in range(long_period, len(df)):
prev_holdings = holdings
if df['MA_short'].iloc[i] > df['MA_long'].iloc[i] and df['MA_short'].iloc[i-1] <= df['MA_long'].iloc[i-1] and holdings < max_holding:
shares_to_buy = min(max_holding - holdings, int(cash / df['close'].iloc[i]))
if shares_to_buy > 0:
cost = shares_to_buy * df['close'].iloc[i]
cash -= cost
holdings += shares_to_buy
total_cost += cost
total_shares += shares_to_buy
trade_log.append({
'date': df['trade_date'].iloc[i],
'stock': stock_code,
'action': 'Buy',
'shares': shares_to_buy,
'price': round(df['close'].iloc[i], 2),
'profit': 0,
'holding_value': round(holdings * df['close'].iloc[i], 2)
})
elif df['MA_short'].iloc[i] < df['MA_long'].iloc[i] and df['MA_short'].iloc[i-1] >= df['MA_long'].iloc[i-1] and holdings > 0:
avg_cost = total_cost / total_shares if total_shares > 0 else 0
profit = (df['close'].iloc[i] - avg_cost) * holdings
cash += holdings * df['close'].iloc[i]
trade_log.append({
'date': df['trade_date'].iloc[i],
'stock': stock_code,
'action': 'Sell',
'shares': holdings,
'price': round(df['close'].iloc[i], 2),
'profit': round(profit, 2),
'holding_value': 0
})
total_cost = 0
total_shares = 0
holdings = 0
df.loc[df.index[i], 'Position'] = holdings
portfolio_value.append(cash + holdings * df['close'].iloc[i])
df['Portfolio_Value'] = pd.Series(portfolio_value, index=df.index)
return df, trade_log
# RSI 策略(引入买入成本)
def rsi_strategy(df, initial_cash, max_holding, params, stock_code=''):
period = int(params.get('rsi_period', 14))
df['Change'] = df['close'].diff()
df['Gain'] = df['Change'].apply(lambda x: x if x > 0 else 0)
df['Loss'] = df['Change'].apply(lambda x: -x if x < 0 else 0)
df['Avg_Gain'] = df['Gain'].rolling(period).mean()
df['Avg_Loss'] = df['Loss'].rolling(period).mean()
df['RS'] = df['Avg_Gain'] / df['Avg_Loss'].replace(0, np.nan)
df['RSI'] = 100 - (100 / (1 + df['RS']))
df['Position'] = 0
cash = initial_cash
holdings = 0
portfolio_value = [initial_cash] * period
trade_log = []
total_cost = 0
total_shares = 0
for i in range(period, len(df)):
prev_holdings = holdings
if df['RSI'].iloc[i] < 30 and holdings < max_holding:
shares_to_buy = min(max_holding - holdings, int(cash / df['close'].iloc[i]))
if shares_to_buy > 0:
cost = shares_to_buy * df['close'].iloc[i]
cash -= cost
holdings += shares_to_buy
total_cost += cost
total_shares += shares_to_buy
trade_log.append({
'date': df['trade_date'].iloc[i],
'stock': stock_code,
'action': 'Buy',
'shares': shares_to_buy,
'price': round(df['close'].iloc[i], 2),
'profit': 0,
'holding_value': round(holdings * df['close'].iloc[i], 2)
})
elif df['RSI'].iloc[i] > 70 and holdings > 0:
avg_cost = total_cost / total_shares if total_shares > 0 else 0
profit = (df['close'].iloc[i] - avg_cost) * holdings
cash += holdings * df['close'].iloc[i]
trade_log.append({
'date': df['trade_date'].iloc[i],
'stock': stock_code,
'action': 'Sell',
'shares': holdings,
'price': round(df['close'].iloc[i], 2),
'profit': round(profit, 2),
'holding_value': 0
})
total_cost = 0
total_shares = 0
holdings = 0
df.loc[df.index[i], 'Position'] = holdings
portfolio_value.append(cash + holdings * df['close'].iloc[i])
df['Portfolio_Value'] = pd.Series(portfolio_value, index=df.index)
return df, trade_log
# 布林带策略(引入买入成本)
def bollinger_strategy(df, initial_cash, max_holding, params, stock_code=''):
period = int(params.get('bb_period', 20))
std_dev = float(params.get('bb_std', 2))
df['MA'] = df['close'].rolling(period).mean()
df['Std'] = df['close'].rolling(period).std()
df['Upper'] = df['MA'] + std_dev * df['Std']
df['Lower'] = df['MA'] - std_dev * df['Std']
df['Position'] = 0
cash = initial_cash
holdings = 0
portfolio_value = [initial_cash] * period
trade_log = []
total_cost = 0
total_shares = 0
for i in range(period, len(df)):
prev_holdings = holdings
if df['close'].iloc[i] < df['Lower'].iloc[i] and holdings < max_holding:
shares_to_buy = min(max_holding - holdings, int(cash / df['close'].iloc[i]))
if shares_to_buy > 0:
cost = shares_to_buy * df['close'].iloc[i]
cash -= cost
holdings += shares_to_buy
total_cost += cost
total_shares += shares_to_buy
trade_log.append({
'date': df['trade_date'].iloc[i],
'stock': stock_code,
'action': 'Buy',
'shares': shares_to_buy,
'price': round(df['close'].iloc[i], 2),
'profit': 0,
'holding_value': round(holdings * df['close'].iloc[i], 2)
})
elif df['close'].iloc[i] > df['Upper'].iloc[i] and holdings > 0:
avg_cost = total_cost / total_shares if total_shares > 0 else 0
profit = (df['close'].iloc[i] - avg_cost) * holdings
cash += holdings * df['close'].iloc[i]
trade_log.append({
'date': df['trade_date'].iloc[i],
'stock': stock_code,
'action': 'Sell',
'shares': holdings,
'price': round(df['close'].iloc[i], 2),
'profit': round(profit, 2),
'holding_value': 0
})
total_cost = 0
total_shares = 0
holdings = 0
df.loc[df.index[i], 'Position'] = holdings
portfolio_value.append(cash + holdings * df['close'].iloc[i])
df['Portfolio_Value'] = pd.Series(portfolio_value, index=df.index)
return df, trade_log
# 多股票仿真
def multi_stock_simulation(data, initial_cash, max_holding_per_stock, strategy, params):
total_cash = initial_cash
portfolio = {code: {'df': df, 'holdings': 0} for code, df in data.items()}
portfolio_value = []
for date in data[list(data.keys())[0]]['trade_date']:
daily_value = 0
for code, stock in portfolio.items():
df = stock['df']
if date in df['trade_date'].values:
idx = df[df['trade_date'] == date].index[0]
if strategy == 'macd':
df = macd_strategy(df, total_cash / len(data), max_holding_per_stock, params)
elif strategy == 'multi_factor':
df = multi_factor_strategy(df, total_cash / len(data), max_holding_per_stock, params)
elif strategy == 'turnover_volume':
df = turnover_volume_strategy(df, total_cash / len(data), max_holding_per_stock, params)
elif strategy == 'ma_crossover':
df = ma_crossover_strategy(df, total_cash / len(data), max_holding_per_stock, params)
elif strategy == 'rsi':
df = rsi_strategy(df, total_cash / len(data), max_holding_per_stock, params)
elif strategy == 'bollinger':
df = bollinger_strategy(df, total_cash / len(data), max_holding_per_stock, params)
stock['df'] = df
daily_value += df['Portfolio_Value'].iloc[idx]
portfolio_value.append(daily_value)
combined_df = pd.DataFrame({
'trade_date': data[list(data.keys())[0]]['trade_date'],
'Portfolio_Value': portfolio_value
})
return combined_df
# 计算指标
# 生成仿真图表
def create_simulation_chart(df, stock_data):
fig = go.Figure()
fig.add_trace(go.Scatter(x=df['trade_date'], y=df['Portfolio_Value'], name='投资组合价值', line=dict(color='blue')))
for code, data in stock_data.items():
fig.add_trace(go.Scatter(x=data['trade_date'], y=data['close'], name=f'{code} 收盘价',
line=dict(color='gray', dash='dash'), yaxis='y2'))
fig.update_layout(
title='量化策略仿真结果',
xaxis_title='日期',
yaxis_title='投资组合价值',
yaxis2=dict(title='收盘价', overlaying='y', side='right'),
template='plotly_white',
height=600,
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
)
return fig.to_json()
# 计算技术指标
def calculate_technical_indicators(df):
try:
# 确保基础列存在
if 'close' not in df.columns:
logger.error("缺少 'close' 列,无法计算技术指标")
return df
# 计算 MA20 和 MA50(如果尚未计算)
if 'MA20' not in df.columns:
df['MA20'] = df['close'].rolling(window=20).mean()
if 'MA50' not in df.columns:
df['MA50'] = df['close'].rolling(window=50).mean()
# 计算 MACD
ema12 = df['close'].ewm(span=12, adjust=False).mean()
ema26 = df['close'].ewm(span=26, adjust=False).mean()
df['MACD'] = ema12 - ema26
df['Signal'] = df['MACD'].ewm(span=9, adjust=False).mean()
# 计算 RSI
delta = df['close'].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
rs = gain / loss
df['RSI'] = 100 - (100 / (1 + rs))
# 计算波动率和动量
df['Volatility'] = df['close'].rolling(window=20).std()
df['Momentum'] = df['close'].pct_change(periods=20)
return df
except Exception as e:
logger.error(f"计算技术指标时出错: {str(e)}")
return df
# 创建 K 线图
def create_candlestick_chart1(df, stock_info, strategy):
try:
# 确保 df 包含必要的列
required_columns = ['trade_date', 'open', 'high', 'low', 'close', 'vol']
if not all(col in df.columns for col in required_columns):
logger.error("数据缺少必要列,无法生成K线图")
return None
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1,
subplot_titles=(f"{stock_info['code']} K线图", "成交量"), row_heights=[0.7, 0.3])
# 添加K线图