humblman commited on
Commit
ccd4d5a
·
verified ·
1 Parent(s): 575f64b

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. Kronos/.claude/settings.json +7 -0
  3. Kronos/.gitignore +76 -0
  4. Kronos/.vscode/settings.json +4 -0
  5. Kronos/LICENSE +21 -0
  6. Kronos/examples/get_akshare_date_2024-2025_x.py +629 -0
  7. Kronos/examples/get_date_new.py +661 -0
  8. Kronos/examples/prediction_akshare_2024-2025.py +545 -0
  9. Kronos/examples/prediction_batch_example.py +72 -0
  10. Kronos/examples/prediction_cn_markets_day.py +208 -0
  11. Kronos/examples/prediction_example.py +80 -0
  12. Kronos/examples/prediction_new.py +1333 -0
  13. Kronos/examples/prediction_new_GUI.py +1625 -0
  14. Kronos/examples/prediction_wo_vol_example.py +68 -0
  15. Kronos/examples/run_backtest_kronos.py +455 -0
  16. Kronos/examples/yuce/000021_comprehensive_analysis_report.json +60 -0
  17. Kronos/examples/yuce/000021_optimized_prediction.png +3 -0
  18. Kronos/examples/yuce/002354_comprehensive_analysis_report.json +60 -0
  19. Kronos/examples/yuce/002354_optimized_prediction.png +3 -0
  20. Kronos/examples/yuce/300207_comprehensive_analysis_report.json +70 -0
  21. Kronos/examples/yuce/300207_optimized_prediction.png +3 -0
  22. Kronos/examples/yuce/600580_comprehensive_analysis_report.json +96 -0
  23. Kronos/examples/yuce/600580_optimized_prediction.png +3 -0
  24. Kronos/examples/yuce/historical_backtest.py +384 -0
  25. Kronos/examples/yuce/market_analysis_report.json +41 -0
  26. Kronos/figures/backtest_result_example.png +3 -0
  27. Kronos/figures/logo.png +3 -0
  28. Kronos/figures/overview.png +3 -0
  29. Kronos/figures/prediction_example.png +3 -0
  30. Kronos/finetune/__pycache__/config.cpython-39.pyc +0 -0
  31. Kronos/finetune/__pycache__/qlib_test.cpython-39.pyc +0 -0
  32. Kronos/finetune/backtest_external_signal.py +41 -0
  33. Kronos/finetune/build_test_data.py +76 -0
  34. Kronos/finetune/check.py +79 -0
  35. Kronos/finetune/config copy.py +133 -0
  36. Kronos/finetune/config.py +138 -0
  37. Kronos/finetune/data/processed_datasets/test_data.pkl +3 -0
  38. Kronos/finetune/dataset.py +138 -0
  39. Kronos/finetune/merge_predictions.py +431 -0
  40. Kronos/finetune/outputs/backtest_results/finetune_backtest_demo/predictions.pkl +3 -0
  41. Kronos/finetune/qlib_data_preprocess.py +130 -0
  42. Kronos/finetune/qlib_test copy.py +438 -0
  43. Kronos/finetune/qlib_test.py +645 -0
  44. Kronos/finetune/train_predictor.py +244 -0
  45. Kronos/finetune/train_tokenizer.py +281 -0
  46. Kronos/finetune/utils/__init__.py +0 -0
  47. Kronos/finetune/utils/__pycache__/__init__.cpython-39.pyc +0 -0
  48. Kronos/finetune/utils/__pycache__/training_utils.cpython-39.pyc +0 -0
  49. Kronos/finetune/utils/training_utils.py +118 -0
  50. Kronos/finetune_csv/README.md +120 -0
.gitattributes CHANGED
@@ -58,3 +58,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/_libs/expanding.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
62
+ Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/_libs/rolling.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
Kronos/.claude/settings.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(python build_test_data.py)"
5
+ ]
6
+ }
7
+ }
Kronos/.gitignore ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+ MANIFEST
23
+
24
+ # Jupyter Notebook
25
+ .ipynb_checkpoints
26
+
27
+ # PyCharm
28
+ .idea/
29
+
30
+ # VS Code
31
+ .vscode/
32
+
33
+ # macOS
34
+ .DS_Store
35
+ .AppleDouble
36
+ .LSOverride
37
+
38
+ # Windows
39
+ Thumbs.db
40
+ ehthumbs.db
41
+ Desktop.ini
42
+
43
+ # Linux
44
+ *~
45
+
46
+ # Data files (large files)
47
+ *.feather
48
+ *.parquet
49
+ *.h5
50
+ *.hdf5
51
+
52
+ # Model files (large files)
53
+ *.pth
54
+ *.pt
55
+ *.ckpt
56
+ *.bin
57
+
58
+ # Logs
59
+ *.log
60
+ logs/
61
+
62
+ # Environment
63
+ .env
64
+ .venv
65
+ env/
66
+ venv/
67
+ ENV/
68
+ env.bak/
69
+ venv.bak/
70
+
71
+ # Temporary files
72
+ *.tmp
73
+ *.temp
74
+ temp/
75
+ tmp/
76
+ .python-version
Kronos/.vscode/settings.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "python-envs.defaultEnvManager": "ms-python.python:conda",
3
+ "python-envs.defaultPackageManager": "ms-python.python:conda"
4
+ }
Kronos/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 ShiYu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
Kronos/examples/get_akshare_date_2024-2025_x.py ADDED
@@ -0,0 +1,629 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import requests
3
+ import json
4
+ from datetime import datetime, timedelta
5
+ import os
6
+ import time
7
+ import random
8
+
9
+
10
+ def get_stock_market(stock_code):
11
+ """
12
+ 根据股票代码判断市场类型
13
+ 返回: 市场前缀 '0'-深交所, '1'-上交所
14
+ """
15
+ if stock_code.startswith(('0', '2', '3')):
16
+ return '0' # 深交所
17
+ elif stock_code.startswith(('6', '9')):
18
+ return '1' # 上交所
19
+ else:
20
+ return '1' # 默认上交所
21
+
22
+
23
+ def get_stock_data_eastmoney(stock_code="002354", start_year=2024, end_year=2025):
24
+ """
25
+ 使用东方财富网API获取指定年份范围的股票数据 - 修复版
26
+ """
27
+ try:
28
+ print(f"正在从东方财富网获取股票 {stock_code} 的 {start_year}-{end_year} 年数据...")
29
+
30
+ # 计算日期范围
31
+ start_date = f"{start_year}0101"
32
+ current_date = datetime.now()
33
+
34
+ if current_date.year > end_year:
35
+ end_date = f"{end_year}1231"
36
+ else:
37
+ end_date = current_date.strftime('%Y%m%d')
38
+
39
+ print(f"时间范围: {start_date} 到 {end_date}")
40
+
41
+ # 获取市场类型
42
+ market = get_stock_market(stock_code)
43
+ secid = f"{market}.{stock_code}"
44
+
45
+ # 使用更简单的东方财富API
46
+ url = "http://push2his.eastmoney.com/api/qt/stock/kline/get"
47
+
48
+ params = {
49
+ 'secid': secid,
50
+ 'fields1': 'f1,f2,f3,f4,f5,f6',
51
+ 'fields2': 'f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61',
52
+ 'klt': '101', # 日线
53
+ 'fqt': '1', # 前复权
54
+ 'beg': start_date,
55
+ 'end': end_date,
56
+ 'lmt': '10000',
57
+ 'ut': 'fa5fd1943c7b386f172d6893dbfba10b',
58
+ 'cb': f'jQuery{random.randint(1000000, 9999999)}_{int(time.time()*1000)}'
59
+ }
60
+
61
+ headers = {
62
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
63
+ 'Referer': 'https://quote.eastmoney.com/',
64
+ 'Accept': '*/*',
65
+ }
66
+
67
+ time.sleep(random.uniform(1, 2))
68
+
69
+ response = requests.get(url, params=params, headers=headers, timeout=10)
70
+
71
+ print(f"API响应状态码: {response.status_code}")
72
+
73
+ if response.status_code == 200:
74
+ # 处理JSONP响应
75
+ response_text = response.text
76
+
77
+ # 提取JSON数据(处理JSONP格式)
78
+ if response_text.startswith('/**/'):
79
+ response_text = response_text[4:]
80
+
81
+ # 查找JSON数据的开始和结束位置
82
+ start_idx = response_text.find('(')
83
+ end_idx = response_text.rfind(')')
84
+
85
+ if start_idx != -1 and end_idx != -1:
86
+ json_str = response_text[start_idx + 1:end_idx]
87
+ try:
88
+ data = json.loads(json_str)
89
+ except json.JSONDecodeError:
90
+ print("❌ JSON解析失败,尝试直接解析...")
91
+ # 如果JSON解析失败,尝试直接提取数据
92
+ return parse_kline_data_directly(response_text, stock_code, start_year, end_year)
93
+ else:
94
+ print("❌ 无法找到JSON数据边界")
95
+ return None
96
+
97
+ print(f"API返回数据状态: {data.get('rc', 'N/A')}")
98
+
99
+ if data and data.get('data') is not None:
100
+ klines = data['data'].get('klines', [])
101
+ print(f"获取到 {len(klines)} 条K线数据")
102
+
103
+ if not klines:
104
+ print("⚠️ K线数据为空")
105
+ return None
106
+
107
+ # 解析数据
108
+ stock_data = []
109
+ for kline in klines:
110
+ try:
111
+ items = kline.split(',')
112
+ if len(items) >= 6:
113
+ stock_data.append({
114
+ '日期': items[0],
115
+ '股票代码': stock_code,
116
+ '开盘价': float(items[1]),
117
+ '收盘价': float(items[2]),
118
+ '最高价': float(items[3]),
119
+ '最低价': float(items[4]),
120
+ '成交量': float(items[5]),
121
+ '成交额': float(items[6]) if len(items) > 6 else 0,
122
+ '振幅': float(items[7]) if len(items) > 7 else 0,
123
+ '涨跌幅': float(items[8]) if len(items) > 8 else 0,
124
+ '涨跌额': float(items[9]) if len(items) > 9 else 0,
125
+ '换手率': float(items[10]) if len(items) > 10 else 0
126
+ })
127
+ except (ValueError, IndexError) as e:
128
+ continue
129
+
130
+ if not stock_data:
131
+ print("❌ 解析后无有效数据")
132
+ return None
133
+
134
+ df = pd.DataFrame(stock_data)
135
+ df['日期'] = pd.to_datetime(df['日期'])
136
+ df.set_index('日期', inplace=True)
137
+ df = df.sort_index()
138
+
139
+ # 筛选指定年份的数据
140
+ df = df[(df.index.year >= start_year) & (df.index.year <= end_year)]
141
+
142
+ print(f"✅ 成功获取 {len(df)} 条有效数据")
143
+ print(f"实际时间范围: {df.index.min().strftime('%Y-%m-%d')} 到 {df.index.max().strftime('%Y-%m-%d')}")
144
+ return df
145
+ else:
146
+ print("❌ API返回数据为空")
147
+ return None
148
+ else:
149
+ print(f"❌ 请求失败,状态码: {response.status_code}")
150
+ return None
151
+
152
+ except Exception as e:
153
+ print(f"❌ 获取数据时出错: {str(e)}")
154
+ return None
155
+
156
+
157
+ def parse_kline_data_directly(response_text, stock_code, start_year, end_year):
158
+ """
159
+ 直接解析K线数据(当JSON解析失败时使用)
160
+ """
161
+ try:
162
+ # 尝试直接从响应文本中提取K线数据
163
+ if '"klines":[' in response_text:
164
+ start_idx = response_text.find('"klines":[') + 10
165
+ end_idx = response_text.find(']', start_idx)
166
+ klines_str = response_text[start_idx:end_idx]
167
+
168
+ # 清理字符串并分割
169
+ klines = klines_str.replace('"', '').split(',')
170
+
171
+ stock_data = []
172
+ for kline in klines:
173
+ if kline.strip():
174
+ items = kline.split(',')
175
+ if len(items) >= 6:
176
+ stock_data.append({
177
+ '日期': items[0],
178
+ '股票代码': stock_code,
179
+ '开盘价': float(items[1]),
180
+ '收盘价': float(items[2]),
181
+ '最高价': float(items[3]),
182
+ '最低价': float(items[4]),
183
+ '成交量': float(items[5]),
184
+ '成交额': float(items[6]) if len(items) > 6 else 0,
185
+ })
186
+
187
+ if stock_data:
188
+ df = pd.DataFrame(stock_data)
189
+ df['日期'] = pd.to_datetime(df['日期'])
190
+ df.set_index('日期', inplace=True)
191
+ df = df.sort_index()
192
+ df = df[(df.index.year >= start_year) & (df.index.year <= end_year)]
193
+ print(f"✅ 直接解析获取 {len(df)} 条数据")
194
+ return df
195
+ except Exception as e:
196
+ print(f"❌ 直接解析也失败: {e}")
197
+
198
+ return None
199
+
200
+
201
+ def get_stock_data_akshare(stock_code="002354", start_year=2024, end_year=2025):
202
+ """
203
+ 使用AKShare作为备用数据源 - 修复版
204
+ """
205
+ try:
206
+ print(f"尝试使用AKShare获取股票 {stock_code} 数据...")
207
+ import akshare as ak
208
+
209
+ # 计算日期范围
210
+ start_date = f"{start_year}0101"
211
+ end_date = datetime.now().strftime('%Y%m%d')
212
+
213
+ # 获取数据
214
+ df = ak.stock_zh_a_hist(symbol=stock_code, period="daily",
215
+ start_date=start_date, end_date=end_date,
216
+ adjust="qfq")
217
+
218
+ if df is not None and not df.empty:
219
+ # 重命名列以匹配我们的格式
220
+ column_mapping = {
221
+ '日期': '日期',
222
+ '开盘': '开盘价',
223
+ '收盘': '收盘价',
224
+ '最高': '最高价',
225
+ '最低': '最低价',
226
+ '成交量': '成交量',
227
+ '成交额': '成交额',
228
+ '振幅': '振幅',
229
+ '涨跌幅': '涨跌幅',
230
+ '涨跌额': '涨跌额',
231
+ '换手率': '换手率'
232
+ }
233
+
234
+ # 只映射存在的列
235
+ actual_mapping = {k: v for k, v in column_mapping.items() if k in df.columns}
236
+ df = df.rename(columns=actual_mapping)
237
+
238
+ # 添加股票代码列
239
+ df['股票代码'] = stock_code
240
+ df['日期'] = pd.to_datetime(df['日期'])
241
+ df.set_index('日期', inplace=True)
242
+ df = df.sort_index()
243
+
244
+ # 筛选指定年份
245
+ df = df[(df.index.year >= start_year) & (df.index.year <= end_year)]
246
+
247
+ print(f"✅ AKShare成功获取 {len(df)} 条数据")
248
+ return df
249
+ else:
250
+ print("❌ AKShare未返回数据")
251
+ return None
252
+
253
+ except ImportError:
254
+ print("⚠️ AKShare未安装,使用 pip install akshare 安装")
255
+ return None
256
+ except Exception as e:
257
+ print(f"❌ AKShare获取数据失败: {e}")
258
+ return None
259
+
260
+
261
+ def get_stock_data_baostock(stock_code="002354", start_year=2024, end_year=2025):
262
+ """
263
+ 使用Baostock作为第三个数据源
264
+ """
265
+ try:
266
+ print(f"尝试使用Baostock获取股票 {stock_code} 数据...")
267
+ import baostock as bs
268
+ import pandas as pd
269
+
270
+ # 登录系统
271
+ lg = bs.login()
272
+
273
+ # 计算日期范围
274
+ start_date = f"{start_year}-01-01"
275
+ end_date = datetime.now().strftime('%Y-%m-%d')
276
+
277
+ # 根据市场添加前缀
278
+ market = get_stock_market(stock_code)
279
+ if market == '0':
280
+ full_code = f"sz.{stock_code}"
281
+ else:
282
+ full_code = f"sh.{stock_code}"
283
+
284
+ # 获取数据
285
+ rs = bs.query_history_k_data_plus(
286
+ full_code,
287
+ "date,open,high,low,close,volume,amount,turn,pctChg",
288
+ start_date=start_date,
289
+ end_date=end_date,
290
+ frequency="d",
291
+ adjustflag="2" # 前复权
292
+ )
293
+
294
+ data_list = []
295
+ while (rs.error_code == '0') & rs.next():
296
+ data_list.append(rs.get_row_data())
297
+
298
+ # 退出系统
299
+ bs.logout()
300
+
301
+ if data_list:
302
+ df = pd.DataFrame(data_list, columns=rs.fields)
303
+
304
+ # 数据类型转换
305
+ df['date'] = pd.to_datetime(df['date'])
306
+ df['open'] = pd.to_numeric(df['open'])
307
+ df['high'] = pd.to_numeric(df['high'])
308
+ df['low'] = pd.to_numeric(df['low'])
309
+ df['close'] = pd.to_numeric(df['close'])
310
+ df['volume'] = pd.to_numeric(df['volume'])
311
+ df['amount'] = pd.to_numeric(df['amount'])
312
+ df['turn'] = pd.to_numeric(df['turn'])
313
+ df['pctChg'] = pd.to_numeric(df['pctChg'])
314
+
315
+ # 重命名列
316
+ df = df.rename(columns={
317
+ 'date': '日期',
318
+ 'open': '开盘价',
319
+ 'high': '最高价',
320
+ 'low': '最低价',
321
+ 'close': '收盘价',
322
+ 'volume': '成交量',
323
+ 'amount': '成交额',
324
+ 'turn': '换手率',
325
+ 'pctChg': '涨跌幅'
326
+ })
327
+
328
+ # 添加股票代码列
329
+ df['股票代码'] = stock_code
330
+ df.set_index('日期', inplace=True)
331
+ df = df.sort_index()
332
+
333
+ # 筛选指定年份
334
+ df = df[(df.index.year >= start_year) & (df.index.year <= end_year)]
335
+
336
+ # 计算涨跌额
337
+ df['涨跌额'] = df['收盘价'].diff()
338
+
339
+ print(f"✅ Baostock成功获取 {len(df)} 条数据")
340
+ return df
341
+ else:
342
+ print("❌ Baostock未返回数据")
343
+ return None
344
+
345
+ except ImportError:
346
+ print("⚠️ Baostock未安装,使用 pip install baostock 安装")
347
+ return None
348
+ except Exception as e:
349
+ print(f"❌ Baostock获取数据失败: {e}")
350
+ return None
351
+
352
+
353
+ def get_stock_data_with_retry(stock_code="002354", start_year=2024, end_year=2025, retry_count=2):
354
+ """
355
+ 带重试机制的数据获取 - 多数据源版本
356
+ """
357
+ data_sources = [
358
+ ("AKShare", get_stock_data_akshare),
359
+ ("Baostock", get_stock_data_baostock),
360
+ ("东方财富", get_stock_data_eastmoney)
361
+ ]
362
+
363
+ for source_name, data_func in data_sources:
364
+ print(f"\n🔍 尝试从 {source_name} 获取数据...")
365
+ data = data_func(stock_code, start_year, end_year)
366
+
367
+ if data is not None and not data.empty:
368
+ # 检查数据是否包含目标年份
369
+ available_years = data.index.year.unique()
370
+ print(f"获取到的数据年份: {sorted(available_years)}")
371
+
372
+ if any(year in available_years for year in range(start_year, end_year + 1)):
373
+ print(f"✅ {source_name} 数据获取成功!")
374
+ # 标记数据来源
375
+ data.attrs['data_source'] = source_name
376
+ return data
377
+ else:
378
+ print(f"⚠️ 数据未包含目标年份数据")
379
+
380
+ print("❌ 所有真实数据源都失败,使用示例数据...")
381
+ return create_sample_data(stock_code, start_year, end_year)
382
+
383
+
384
+ def create_sample_data(stock_code="002354", start_year=2024, end_year=2025):
385
+ """
386
+ 创建更真实的示例数据
387
+ """
388
+ print(f"📊 创建 {start_year}-{end_year} 年的示例数据...")
389
+
390
+ # 生成交易日(排除周末)
391
+ start_date = datetime(start_year, 1, 1)
392
+ end_date = datetime.now()
393
+ all_dates = pd.bdate_range(start=start_date, end=end_date, freq='B')
394
+
395
+ # 只保留目标年份的数据
396
+ trading_dates = [date for date in all_dates if start_year <= date.year <= end_year]
397
+
398
+ # 生成更真实的股价数据
399
+ import numpy as np
400
+ np.random.seed(42)
401
+
402
+ # 设置合理的基准价格
403
+ base_prices = {
404
+ '600580': 12.0, # 卧龙电驱 - 更合理的价格
405
+ '002354': 5.0, # 天娱数科
406
+ '300207': 15.0, # 欣旺达
407
+ }
408
+ base_price = base_prices.get(stock_code, 10.0)
409
+
410
+ stock_data = []
411
+ current_price = base_price
412
+
413
+ for i, date in enumerate(trading_dates):
414
+ # 更真实的股价波动
415
+ volatility = 0.015 # 1.5%的日波动率
416
+
417
+ if i > 0:
418
+ # 使用更真实的随���游走
419
+ daily_return = np.random.normal(0, volatility)
420
+ # 添加一些趋势
421
+ if i < len(trading_dates) * 0.3: # 前30%的时间
422
+ trend_bias = 0.0005 # 轻微上涨趋势
423
+ elif i < len(trading_dates) * 0.7: # 中间40%的时间
424
+ trend_bias = -0.0003 # 轻微下跌趋势
425
+ else: # 后30%的时间
426
+ trend_bias = 0.0002 # 轻微上涨趋势
427
+
428
+ daily_return += trend_bias
429
+ current_price = current_price * (1 + daily_return)
430
+
431
+ # 价格边界限制 - 更合理
432
+ current_price = max(base_price * 0.5, min(base_price * 2.0, current_price))
433
+ else:
434
+ current_price = base_price
435
+
436
+ # 生成OHLC数据
437
+ open_variation = np.random.normal(0, volatility * 0.2)
438
+ open_price = current_price * (1 + open_variation)
439
+
440
+ daily_range = abs(np.random.normal(volatility * 0.8, volatility * 0.3))
441
+ high_price = max(open_price, current_price) * (1 + daily_range)
442
+ low_price = min(open_price, current_price) * (1 - daily_range)
443
+ close_price = current_price
444
+
445
+ # 确保价格合理性
446
+ high_price = max(open_price, close_price, low_price, high_price)
447
+ low_price = min(open_price, close_price, high_price, low_price)
448
+
449
+ # 生成成交量(更合理)
450
+ base_volume = 500000 # 基础成交量
451
+ volume_variation = abs(daily_return) * 3000000 if i > 0 else 0
452
+ volume = int(base_volume + volume_variation + np.random.randint(-100000, 200000))
453
+ volume = max(100000, volume)
454
+
455
+ # 计算成交额(万元)
456
+ amount = volume * close_price / 10000
457
+
458
+ # 计算涨跌幅和涨跌额
459
+ if i > 0:
460
+ prev_close = stock_data[-1]['收盘价']
461
+ price_change = close_price - prev_close
462
+ pct_change = (price_change / prev_close) * 100
463
+ else:
464
+ price_change = 0
465
+ pct_change = 0
466
+
467
+ # 计算振幅
468
+ amplitude = ((high_price - low_price) / open_price) * 100
469
+
470
+ # 生成换手率(0.5%-8%之间)
471
+ turnover_rate = np.random.uniform(0.5, 8.0)
472
+
473
+ stock_data.append({
474
+ '日期': date,
475
+ '股票代码': stock_code,
476
+ '开盘价': round(open_price, 2),
477
+ '收盘价': round(close_price, 2),
478
+ '最高价': round(high_price, 2),
479
+ '最低价': round(low_price, 2),
480
+ '成交量': volume,
481
+ '成交额': round(amount, 2),
482
+ '振幅': round(amplitude, 2),
483
+ '涨跌幅': round(pct_change, 2),
484
+ '涨跌额': round(price_change, 2),
485
+ '换手率': round(turnover_rate, 2)
486
+ })
487
+
488
+ df = pd.DataFrame(stock_data)
489
+ df.set_index('日期', inplace=True)
490
+
491
+ print(f"✅ 已创建 {len(df)} 条 {start_year}-{end_year} 年的模拟数据")
492
+ print(f"时间范围: {df.index.min().strftime('%Y-%m-%d')} 到 {df.index.max().strftime('%Y-%m-%d')}")
493
+
494
+ # 标记为模拟数据
495
+ df.attrs['data_source'] = '模拟数据'
496
+
497
+ return df
498
+
499
+
500
+ def display_data_info(df, stock_code, start_year, end_year):
501
+ """显示数据信息"""
502
+ if df is None or df.empty:
503
+ print("没有数据可显示")
504
+ return
505
+
506
+ # 获取数据来源
507
+ data_source = df.attrs.get('data_source', '未知来源')
508
+
509
+ print(f"\n{'=' * 60}")
510
+ print(f"股票 {stock_code} {start_year}-{end_year} 年数据摘要")
511
+ print(f"{'=' * 60}")
512
+
513
+ print(f"数据时间范围: {df.index.min().strftime('%Y-%m-%d')} 到 {df.index.max().strftime('%Y-%m-%d')}")
514
+ print(f"总交易天数: {len(df)}")
515
+ print(f"数据来源: {data_source}")
516
+
517
+ # 按年份显示统计
518
+ for year in sorted(df.index.year.unique()):
519
+ year_data = df[df.index.year == year]
520
+ print(f"\n{year}年统计:")
521
+ print(f" 交易天数: {len(year_data)}")
522
+ print(f" 平均收盘价: {year_data['收盘价'].mean():.2f} 元")
523
+ print(f" 最高价: {year_data['最高价'].max():.2f} 元")
524
+ print(f" 最低价: {year_data['最低价'].min():.2f} 元")
525
+ if len(year_data) > 1:
526
+ year_return = (year_data['收盘价'].iloc[-1] / year_data['收盘价'].iloc[0] - 1) * 100
527
+ print(f" 年度涨跌幅: {year_return:+.2f}%")
528
+
529
+ # 显示最新交易日数据
530
+ latest_date = df.index.max()
531
+ print(f"\n最新交易日 ({latest_date.strftime('%Y-%m-%d')}) 数据:")
532
+ latest_data = df.loc[latest_date]
533
+ for col, value in latest_data.items():
534
+ if col != '股票代码':
535
+ if col in ['成交量']:
536
+ print(f" {col}: {value:,.0f}")
537
+ elif col in ['成交额']:
538
+ print(f" {col}: {value:,.2f} 万元")
539
+ else:
540
+ print(f" {col}: {value}")
541
+
542
+
543
+ def save_stock_data(df, stock_code, save_dir="D:/lianghuajiaoyi/Kronos/examples/data"):
544
+ """
545
+ 保存股票数据到指定目录
546
+ """
547
+ if df is not None and not df.empty:
548
+ # 确保保存目录存在
549
+ os.makedirs(save_dir, exist_ok=True)
550
+
551
+ # 保存CSV文件
552
+ csv_file = os.path.join(save_dir, f"{stock_code}_stock_data.csv")
553
+
554
+ # 重置索引以便保存日期列
555
+ df_reset = df.reset_index()
556
+ df_reset.to_csv(csv_file, encoding='utf-8-sig', index=False)
557
+
558
+ print(f"\n📁 股票数据已保存: {csv_file}")
559
+ return True
560
+ return False
561
+
562
+
563
+ def main(stock_code="002354", start_year=2024, end_year=2025):
564
+ """
565
+ 主函数:获取并保存股票数据 - 最终版
566
+ """
567
+ # 设置保存目录
568
+ save_directory = "D:/lianghuajiaoyi/Kronos/examples/data"
569
+
570
+ print("=" * 60)
571
+ print(f"开始获取股票 {stock_code} 的 {start_year}-{end_year} 年数据")
572
+ print("=" * 60)
573
+ print(f"数据将保存到: {save_directory}")
574
+
575
+ # 检查必要库
576
+ try:
577
+ import requests
578
+ import numpy as np
579
+ except ImportError:
580
+ print("正在安装必要库...")
581
+ import subprocess
582
+ subprocess.check_call(["pip", "install", "requests", "numpy", "pandas"])
583
+ import requests
584
+ import numpy as np
585
+
586
+ # 获取数据(多数据源)
587
+ stock_data = get_stock_data_with_retry(stock_code, start_year, end_year)
588
+
589
+ if stock_data is not None:
590
+ # 显示数据信息
591
+ display_data_info(stock_data, stock_code, start_year, end_year)
592
+
593
+ # 保存数据到指定目录
594
+ save_stock_data(stock_data, stock_code, save_directory)
595
+
596
+ print(f"\n🎉 股票 {stock_code} 数据处理完成!")
597
+ print(f"最新数据日期: {stock_data.index.max().strftime('%Y-%m-%d')}")
598
+
599
+ # 显示保存的文件
600
+ csv_file = os.path.join(save_directory, f"{stock_code}_stock_data.csv")
601
+ if os.path.exists(csv_file):
602
+ file_size = os.path.getsize(csv_file) / 1024 # KB
603
+ print(f"📄 生成的文件: {csv_file} ({file_size:.1f} KB)")
604
+ else:
605
+ print("❌ 未能获取股票数据")
606
+
607
+
608
+ # 使用方法说明
609
+ if __name__ == "__main__":
610
+ """
611
+ 使用方法:
612
+ 修改下面的参数来获取不同股票的数据
613
+ """
614
+
615
+ # ==================== 在这里修改参数 ====================
616
+ TARGET_STOCK_CODE = "300418" # 股票代码
617
+ START_YEAR = 2024 # 开始年份
618
+ END_YEAR = 2025 # 结束年份
619
+ # =====================================================
620
+
621
+ print("股票数据获取工具 - 终极优化版")
622
+ print("说明:修改代码中的 TARGET_STOCK_CODE 来获取不同股票的数据")
623
+ print(f"当前设置: 股票代码={TARGET_STOCK_CODE}, 年份范围={START_YEAR}-{END_YEAR}")
624
+ print()
625
+
626
+ # 运行主程序
627
+ main(stock_code=TARGET_STOCK_CODE, start_year=START_YEAR, end_year=END_YEAR)
628
+
629
+ print(f"\n💡 提示:要获取其他股票数据,请修改代码中的 TARGET_STOCK_CODE 变量")
Kronos/examples/get_date_new.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import requests
3
+ import json
4
+ from datetime import datetime, timedelta
5
+ import os
6
+ import time
7
+ import random
8
+
9
+
10
+ def get_stock_market(stock_code):
11
+ """
12
+ 根据股票代码判断市场类型
13
+ 返回: 市场前缀 '0'-深交所, '1'-上交所
14
+ """
15
+ if stock_code.startswith(('0', '2', '3')):
16
+ return '0' # 深交所
17
+ elif stock_code.startswith(('6', '9')):
18
+ return '1' # 上交所
19
+ else:
20
+ return '1' # 默认上交所
21
+
22
+
23
+ def get_stock_data_eastmoney_all_history(stock_code="002354"):
24
+ """
25
+ 使用东方财富网API获取股票所有历史数据
26
+ """
27
+ try:
28
+ print(f"正在从东方财富网获取股票 {stock_code} 的全部历史数据...")
29
+
30
+ # 获取市场类型
31
+ market = get_stock_market(stock_code)
32
+ secid = f"{market}.{stock_code}"
33
+
34
+ # 使用东方财富API获取所有历史数据
35
+ url = "http://push2his.eastmoney.com/api/qt/stock/kline/get"
36
+
37
+ # 设置足够早的起始日期(中国股市从1990年开始)
38
+ start_date = "19900101"
39
+ end_date = datetime.now().strftime('%Y%m%d')
40
+
41
+ params = {
42
+ 'secid': secid,
43
+ 'fields1': 'f1,f2,f3,f4,f5,f6',
44
+ 'fields2': 'f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61',
45
+ 'klt': '101', # 日线
46
+ 'fqt': '1', # 前复权
47
+ 'beg': start_date,
48
+ 'end': end_date,
49
+ 'lmt': '50000', # 增加限制数量以获取更多历史数据
50
+ 'ut': 'fa5fd1943c7b386f172d6893dbfba10b',
51
+ 'cb': f'jQuery{random.randint(1000000, 9999999)}_{int(time.time() * 1000)}'
52
+ }
53
+
54
+ headers = {
55
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
56
+ 'Referer': 'https://quote.eastmoney.com/',
57
+ 'Accept': '*/*',
58
+ }
59
+
60
+ time.sleep(random.uniform(1, 2))
61
+
62
+ response = requests.get(url, params=params, headers=headers, timeout=15)
63
+
64
+ print(f"API响应状态码: {response.status_code}")
65
+
66
+ if response.status_code == 200:
67
+ # 处理JSONP响应
68
+ response_text = response.text
69
+
70
+ # 提取JSON数据(处理JSONP格式)
71
+ if response_text.startswith('/**/'):
72
+ response_text = response_text[4:]
73
+
74
+ # 查找JSON数据的开始和结束位置
75
+ start_idx = response_text.find('(')
76
+ end_idx = response_text.rfind(')')
77
+
78
+ if start_idx != -1 and end_idx != -1:
79
+ json_str = response_text[start_idx + 1:end_idx]
80
+ try:
81
+ data = json.loads(json_str)
82
+ except json.JSONDecodeError:
83
+ print("❌ JSON解析失败,尝试直接解析...")
84
+ return parse_kline_data_directly_all_history(response_text, stock_code)
85
+ else:
86
+ print("❌ 无法找到JSON数据边界")
87
+ return None
88
+
89
+ print(f"API返回数据状态: {data.get('rc', 'N/A')}")
90
+
91
+ if data and data.get('data') is not None:
92
+ klines = data['data'].get('klines', [])
93
+ print(f"获取到 {len(klines)} 条历史K线数据")
94
+
95
+ if not klines:
96
+ print("⚠️ K线数据为空")
97
+ return None
98
+
99
+ # 解析数据
100
+ stock_data = []
101
+ for kline in klines:
102
+ try:
103
+ items = kline.split(',')
104
+ if len(items) >= 6:
105
+ stock_data.append({
106
+ '日期': items[0],
107
+ '股票代码': stock_code,
108
+ '开盘价': float(items[1]),
109
+ '收盘价': float(items[2]),
110
+ '最高价': float(items[3]),
111
+ '最低价': float(items[4]),
112
+ '成交量': float(items[5]),
113
+ '成交额': float(items[6]) if len(items) > 6 else 0,
114
+ '振幅': float(items[7]) if len(items) > 7 else 0,
115
+ '涨跌幅': float(items[8]) if len(items) > 8 else 0,
116
+ '涨跌额': float(items[9]) if len(items) > 9 else 0,
117
+ '换手率': float(items[10]) if len(items) > 10 else 0
118
+ })
119
+ except (ValueError, IndexError) as e:
120
+ continue
121
+
122
+ if not stock_data:
123
+ print("❌ 解析后无有效数据")
124
+ return None
125
+
126
+ df = pd.DataFrame(stock_data)
127
+ df['日期'] = pd.to_datetime(df['日期'])
128
+ df.set_index('日期', inplace=True)
129
+ df = df.sort_index()
130
+
131
+ print(f"✅ ���功获取 {len(df)} 条历史数据")
132
+ print(
133
+ f"历史数据时间范围: {df.index.min().strftime('%Y-%m-%d')} 到 {df.index.max().strftime('%Y-%m-%d')}")
134
+ return df
135
+ else:
136
+ print("❌ API返回数据为空")
137
+ return None
138
+ else:
139
+ print(f"❌ 请求失败,状态码: {response.status_code}")
140
+ return None
141
+
142
+ except Exception as e:
143
+ print(f"❌ 获取历史数据时出错: {str(e)}")
144
+ return None
145
+
146
+
147
+ def parse_kline_data_directly_all_history(response_text, stock_code):
148
+ """
149
+ 直接解析K线数据(当JSON解析失败时使用)- 全历史版本
150
+ """
151
+ try:
152
+ # 尝试直接从响应文本中提取K线数据
153
+ if '"klines":[' in response_text:
154
+ start_idx = response_text.find('"klines":[') + 10
155
+ end_idx = response_text.find(']', start_idx)
156
+ klines_str = response_text[start_idx:end_idx]
157
+
158
+ # 清理字符串并分割
159
+ klines = [k.strip().strip('"') for k in klines_str.split('","') if k.strip()]
160
+
161
+ stock_data = []
162
+ for kline in klines:
163
+ if kline.strip():
164
+ items = kline.split(',')
165
+ if len(items) >= 6:
166
+ stock_data.append({
167
+ '日期': items[0],
168
+ '股票代码': stock_code,
169
+ '开盘价': float(items[1]),
170
+ '收盘价': float(items[2]),
171
+ '最高价': float(items[3]),
172
+ '最低价': float(items[4]),
173
+ '成交量': float(items[5]),
174
+ '成交额': float(items[6]) if len(items) > 6 else 0,
175
+ })
176
+
177
+ if stock_data:
178
+ df = pd.DataFrame(stock_data)
179
+ df['日期'] = pd.to_datetime(df['日期'])
180
+ df.set_index('日期', inplace=True)
181
+ df = df.sort_index()
182
+ print(f"✅ 直接解析获取 {len(df)} 条历史数据")
183
+ return df
184
+ except Exception as e:
185
+ print(f"❌ 直接解析也失败: {e}")
186
+
187
+ return None
188
+
189
+
190
+ def get_stock_data_akshare_all_history(stock_code="002354"):
191
+ """
192
+ 使用AKShare作为备用数据源 - 全历史版本
193
+ """
194
+ try:
195
+ print(f"尝试使用AKShare获取股票 {stock_code} 全部历史数据...")
196
+ import akshare as ak
197
+
198
+ # 获取所有历史数据
199
+ df = ak.stock_zh_a_hist(symbol=stock_code, period="daily",
200
+ adjust="qfq")
201
+
202
+ if df is not None and not df.empty:
203
+ # 重命名列以匹配我们的格式
204
+ column_mapping = {
205
+ '日期': '日期',
206
+ '开盘': '开盘价',
207
+ '收盘': '收盘价',
208
+ '最高': '最高价',
209
+ '最低': '最低价',
210
+ '成交量': '成交量',
211
+ '成交额': '成交额',
212
+ '振幅': '振幅',
213
+ '涨跌幅': '涨跌幅',
214
+ '涨跌额': '涨跌额',
215
+ '换手率': '换手率'
216
+ }
217
+
218
+ # 只映射存在的列
219
+ actual_mapping = {k: v for k, v in column_mapping.items() if k in df.columns}
220
+ df = df.rename(columns=actual_mapping)
221
+
222
+ # 添加股票代码列
223
+ df['股票代码'] = stock_code
224
+ df['日期'] = pd.to_datetime(df['日期'])
225
+ df.set_index('日期', inplace=True)
226
+ df = df.sort_index()
227
+
228
+ print(f"✅ AKShare成功获取 {len(df)} 条历史数据")
229
+ print(f"时间范围: {df.index.min().strftime('%Y-%m-%d')} 到 {df.index.max().strftime('%Y-%m-%d')}")
230
+ return df
231
+ else:
232
+ print("❌ AKShare未返回数据")
233
+ return None
234
+
235
+ except ImportError:
236
+ print("⚠️ AKShare未安装,使用 pip install akshare 安装")
237
+ return None
238
+ except Exception as e:
239
+ print(f"❌ AKShare获取历史数据失败: {e}")
240
+ return None
241
+
242
+
243
+ def get_stock_data_baostock_all_history(stock_code="002354"):
244
+ """
245
+ 使用Baostock作为第三个数据源 - 全历史版本
246
+ """
247
+ try:
248
+ print(f"尝试使用Baostock获取股票 {stock_code} 全部历史数据...")
249
+ import baostock as bs
250
+ import pandas as pd
251
+
252
+ # 登录系统
253
+ lg = bs.login()
254
+
255
+ # 根据市场添加前缀
256
+ market = get_stock_market(stock_code)
257
+ if market == '0':
258
+ full_code = f"sz.{stock_code}"
259
+ else:
260
+ full_code = f"sh.{stock_code}"
261
+
262
+ # 获取上市日期
263
+ rs = bs.query_stock_basic(code=full_code)
264
+ if rs.error_code != '0':
265
+ print(f"❌ 获取股票基本信息失败: {rs.error_msg}")
266
+ bs.logout()
267
+ return None
268
+
269
+ # 获取上市��期
270
+ list_date = None
271
+ while (rs.error_code == '0') & rs.next():
272
+ list_date = rs.get_row_data()[2] # 上市日期在第三个字段
273
+
274
+ if not list_date:
275
+ print("❌ 无法获取上市日期")
276
+ bs.logout()
277
+ return None
278
+
279
+ print(f"股票上市日期: {list_date}")
280
+
281
+ # 获取从上市日期到现在的所有数据
282
+ end_date = datetime.now().strftime('%Y-%m-%d')
283
+
284
+ # 获取数据
285
+ rs = bs.query_history_k_data_plus(
286
+ full_code,
287
+ "date,open,high,low,close,volume,amount,turn,pctChg",
288
+ start_date=list_date,
289
+ end_date=end_date,
290
+ frequency="d",
291
+ adjustflag="2" # 前复权
292
+ )
293
+
294
+ data_list = []
295
+ while (rs.error_code == '0') & rs.next():
296
+ data_list.append(rs.get_row_data())
297
+
298
+ # 退出系统
299
+ bs.logout()
300
+
301
+ if data_list:
302
+ df = pd.DataFrame(data_list, columns=rs.fields)
303
+
304
+ # 数据类型转换
305
+ df['date'] = pd.to_datetime(df['date'])
306
+ df['open'] = pd.to_numeric(df['open'], errors='coerce')
307
+ df['high'] = pd.to_numeric(df['high'], errors='coerce')
308
+ df['low'] = pd.to_numeric(df['low'], errors='coerce')
309
+ df['close'] = pd.to_numeric(df['close'], errors='coerce')
310
+ df['volume'] = pd.to_numeric(df['volume'], errors='coerce')
311
+ df['amount'] = pd.to_numeric(df['amount'], errors='coerce')
312
+ df['turn'] = pd.to_numeric(df['turn'], errors='coerce')
313
+ df['pctChg'] = pd.to_numeric(df['pctChg'], errors='coerce')
314
+
315
+ # 重命名列
316
+ df = df.rename(columns={
317
+ 'date': '日期',
318
+ 'open': '开盘价',
319
+ 'high': '最高价',
320
+ 'low': '最低价',
321
+ 'close': '收盘价',
322
+ 'volume': '成交量',
323
+ 'amount': '成交额',
324
+ 'turn': '换手率',
325
+ 'pctChg': '涨跌幅'
326
+ })
327
+
328
+ # 添加股票代码列
329
+ df['股票代码'] = stock_code
330
+ df.set_index('日期', inplace=True)
331
+ df = df.sort_index()
332
+
333
+ # 计算涨跌额
334
+ df['涨跌额'] = df['收盘价'].diff()
335
+
336
+ # 清理无效数据
337
+ df = df.dropna()
338
+
339
+ print(f"✅ Baostock成功获取 {len(df)} 条历史数据")
340
+ print(f"时间范围: {df.index.min().strftime('%Y-%m-%d')} 到 {df.index.max().strftime('%Y-%m-%d')}")
341
+ return df
342
+ else:
343
+ print("❌ Baostock未返回数据")
344
+ return None
345
+
346
+ except ImportError:
347
+ print("⚠️ Baostock未安装,使用 pip install baostock 安装")
348
+ return None
349
+ except Exception as e:
350
+ print(f"❌ Baostock获取历史数据失败: {e}")
351
+ return None
352
+
353
+
354
+ def get_stock_data_with_retry_all_history(stock_code="002354", retry_count=2):
355
+ """
356
+ 带重试机制的数据获取 - 多数据源全历史版本
357
+ """
358
+ data_sources = [
359
+ ("AKShare", get_stock_data_akshare_all_history),
360
+ ("Baostock", get_stock_data_baostock_all_history),
361
+ ("东方财富", get_stock_data_eastmoney_all_history)
362
+ ]
363
+
364
+ for source_name, data_func in data_sources:
365
+ print(f"\n🔍 尝试从 {source_name} 获取全部历史数据...")
366
+ data = data_func(stock_code)
367
+
368
+ if data is not None and not data.empty:
369
+ print(f"✅ {source_name} 历史数据获取成功!")
370
+ # 标记数据来源
371
+ data.attrs['data_source'] = source_name
372
+ return data
373
+
374
+ print("❌ 所有真实数据源都失败,使用示例数据...")
375
+ return create_sample_data_all_history(stock_code)
376
+
377
+
378
+ def create_sample_data_all_history(stock_code="002354"):
379
+ """
380
+ 创建更真实的历史示例数据 - 从上市年份开始
381
+ """
382
+ # 模拟不同股票的上市年份
383
+ list_years = {
384
+ '600580': 2002, # 卧龙电驱
385
+ '002354': 2010, # 天娱数科
386
+ '300418': 2015, # 昆仑万维
387
+ '300207': 2011, # 欣旺达
388
+ }
389
+
390
+ list_year = list_years.get(stock_code, 2010)
391
+ current_year = datetime.now().year
392
+
393
+ print(f"📊 创建 {stock_code} 从 {list_year} 年上市至今的示例数据...")
394
+
395
+ # 生成从上市年份到现在的交易日(排除周末)
396
+ start_date = datetime(list_year, 1, 1)
397
+ end_date = datetime.now()
398
+ all_dates = pd.bdate_range(start=start_date, end=end_date, freq='B')
399
+
400
+ # 生成更真实的股价数据
401
+ import numpy as np
402
+ np.random.seed(42)
403
+
404
+ # 设置合理的基准价格(根据股票类型)
405
+ base_prices = {
406
+ '600580': 8.0, # 卧龙电驱
407
+ '002354': 15.0, # 天娱数科 - 上市时价格较高
408
+ '300418': 20.0, # 昆仑万维
409
+ '300207': 12.0, # 欣旺达
410
+ }
411
+ base_price = base_prices.get(stock_code, 10.0)
412
+
413
+ stock_data = []
414
+ current_price = base_price
415
+
416
+ for i, date in enumerate(all_dates):
417
+ # 模拟真实的市场波动
418
+ volatility = 0.02 # 2%的日波动率
419
+
420
+ if i > 0:
421
+ # 使用随机游走模拟价格变化
422
+ daily_return = np.random.normal(0, volatility)
423
+
424
+ # 模拟不同年份的市场趋势
425
+ year = date.year
426
+ if year <= list_year + 2: # 上市初期波动较大
427
+ daily_return += np.random.normal(0.001, 0.01)
428
+ elif year <= list_year + 5: # 成长期
429
+ daily_return += np.random.normal(0.0005, 0.005)
430
+ else: # 成熟期
431
+ daily_return += np.random.normal(0.0002, 0.003)
432
+
433
+ current_price = current_price * (1 + daily_return)
434
+
435
+ # 价格边界限制
436
+ current_price = max(base_price * 0.3, min(base_price * 10.0, current_price))
437
+ else:
438
+ current_price = base_price
439
+
440
+ # 生成OHLC数据
441
+ open_variation = np.random.normal(0, volatility * 0.2)
442
+ open_price = current_price * (1 + open_variation)
443
+
444
+ daily_range = abs(np.random.normal(volatility * 0.8, volatility * 0.3))
445
+ high_price = max(open_price, current_price) * (1 + daily_range)
446
+ low_price = min(open_price, current_price) * (1 - daily_range)
447
+ close_price = current_price
448
+
449
+ # 确保价格合理性
450
+ high_price = max(open_price, close_price, low_price, high_price)
451
+ low_price = min(open_price, close_price, high_price, low_price)
452
+
453
+ # 生成成交量(随年份增长)
454
+ base_volume = 100000 + (year - list_year) * 50000 # 成交量逐年增长
455
+ volume_variation = abs(daily_return) * 5000000 if i > 0 else 0
456
+ volume = int(base_volume + volume_variation + np.random.randint(-200000, 400000))
457
+ volume = max(50000, volume)
458
+
459
+ # 计算成交额(万元)
460
+ amount = volume * close_price / 10000
461
+
462
+ # 计算涨跌幅和涨跌额
463
+ if i > 0:
464
+ prev_close = stock_data[-1]['收盘价']
465
+ price_change = close_price - prev_close
466
+ pct_change = (price_change / prev_close) * 100
467
+ else:
468
+ price_change = 0
469
+ pct_change = 0
470
+
471
+ # 计算振幅
472
+ amplitude = ((high_price - low_price) / open_price) * 100
473
+
474
+ # 生成换手率(1%-15%之间)
475
+ turnover_rate = np.random.uniform(1.0, 15.0)
476
+
477
+ stock_data.append({
478
+ '日期': date,
479
+ '股票代码': stock_code,
480
+ '开盘价': round(open_price, 2),
481
+ '收盘价': round(close_price, 2),
482
+ '最高价': round(high_price, 2),
483
+ '最低价': round(low_price, 2),
484
+ '成交量': volume,
485
+ '成交额': round(amount, 2),
486
+ '振幅': round(amplitude, 2),
487
+ '涨跌幅': round(pct_change, 2),
488
+ '涨跌额': round(price_change, 2),
489
+ '换手率': round(turnover_rate, 2)
490
+ })
491
+
492
+ df = pd.DataFrame(stock_data)
493
+ df.set_index('日期', inplace=True)
494
+
495
+ print(f"✅ 已创建 {len(df)} 条从 {list_year} 年至今的模拟历史数据")
496
+ print(f"时间范围: {df.index.min().strftime('%Y-%m-%d')} 到 {df.index.max().strftime('%Y-%m-%d')}")
497
+
498
+ # 标记为模拟数据
499
+ df.attrs['data_source'] = '模拟历史数据'
500
+
501
+ return df
502
+
503
+
504
+ def display_all_history_data_info(df, stock_code):
505
+ """显示全历史数据信息"""
506
+ if df is None or df.empty:
507
+ print("没有数据可显示")
508
+ return
509
+
510
+ # 获取数据来源
511
+ data_source = df.attrs.get('data_source', '未知来源')
512
+
513
+ print(f"\n{'=' * 60}")
514
+ print(f"股票 {stock_code} 全部历史数据摘要")
515
+ print(f"{'=' * 60}")
516
+
517
+ print(f"数据时间范围: {df.index.min().strftime('%Y-%m-%d')} 到 {df.index.max().strftime('%Y-%m-%d')}")
518
+ print(f"总交易天数: {len(df):,}")
519
+ print(f"数据来源: {data_source}")
520
+
521
+ # 按年份显示统计
522
+ years = sorted(df.index.year.unique())
523
+ print(f"\n历史年份: {years}")
524
+
525
+ # 显示关键年份统计
526
+ key_years = [years[0]] # 上市年份
527
+ if len(years) > 1:
528
+ key_years.append(years[-1]) # 最新年份
529
+ if len(years) > 5:
530
+ key_years.extend([years[len(years) // 2], years[len(years) // 4], years[3 * len(years) // 4]])
531
+
532
+ for year in sorted(set(key_years)):
533
+ year_data = df[df.index.year == year]
534
+ if len(year_data) > 0:
535
+ print(f"\n{year}年统计:")
536
+ print(f" 交易天数: {len(year_data)}")
537
+ print(f" 平均收盘价: {year_data['收盘价'].mean():.2f} 元")
538
+ print(f" 最高价: {year_data['最高价'].max():.2f} 元")
539
+ print(f" 最低价: {year_data['最低价'].min():.2f} 元")
540
+ if len(year_data) > 1:
541
+ year_return = (year_data['收盘价'].iloc[-1] / year_data['收盘价'].iloc[0] - 1) * 100
542
+ print(f" 年度涨跌幅: {year_return:+.2f}%")
543
+
544
+ # 显示整体统计
545
+ print(f"\n整体统计:")
546
+ total_return = (df['收盘价'].iloc[-1] / df['收盘价'].iloc[0] - 1) * 100
547
+ print(f" 总涨跌幅: {total_return:+.2f}%")
548
+ print(f" 历史最高价: {df['最高价'].max():.2f} 元")
549
+ print(f" 历史最低价: {df['最低价'].min():.2f} 元")
550
+ print(f" 平均日成交量: {df['成交量'].mean():,.0f} 股")
551
+
552
+ # 显示最新交易日数据
553
+ latest_date = df.index.max()
554
+ print(f"\n最新交易日 ({latest_date.strftime('%Y-%m-%d')}) 数据:")
555
+ latest_data = df.loc[latest_date]
556
+ for col, value in latest_data.items():
557
+ if col != '股票代码':
558
+ if col in ['成交量']:
559
+ print(f" {col}: {value:,.0f}")
560
+ elif col in ['成交额']:
561
+ print(f" {col}: {value:,.2f} 万元")
562
+ else:
563
+ print(f" {col}: {value}")
564
+
565
+
566
+ def save_all_history_stock_data(df, stock_code, save_dir="D:/lianghuajiaoyi/Kronos/examples/data"):
567
+ """
568
+ 保存全历史股票数据到指定目录
569
+ """
570
+ if df is not None and not df.empty:
571
+ # 确保保存目录存在
572
+ os.makedirs(save_dir, exist_ok=True)
573
+
574
+ # 保存CSV文件 - 使用全历史命名
575
+ csv_file = os.path.join(save_dir, f"{stock_code}_all_history.csv")
576
+
577
+ # 重置索引以便保存日期列
578
+ df_reset = df.reset_index()
579
+ df_reset.to_csv(csv_file, encoding='utf-8-sig', index=False)
580
+
581
+ print(f"\n📁 全历史股票数据已保存: {csv_file}")
582
+
583
+ # 同时保存一个按年份分割的版本
584
+ years = df_reset['日期'].dt.year.unique()
585
+ for year in years:
586
+ year_data = df_reset[df_reset['日期'].dt.year == year]
587
+ year_file = os.path.join(save_dir, f"{stock_code}_{year}.csv")
588
+ year_data.to_csv(year_file, encoding='utf-8-sig', index=False)
589
+
590
+ print(f"📁 同时保存了 {len(years)} 个年份的单独数据文件")
591
+ return True
592
+ return False
593
+
594
+
595
+ def main_all_history(stock_code="002354"):
596
+ """
597
+ 主函数:获取并保存股票全历史数据
598
+ """
599
+ # 设置保存目录
600
+ save_directory = "D:/lianghuajiaoyi/Kronos/examples/data"
601
+
602
+ print("=" * 60)
603
+ print(f"开始获取股票 {stock_code} 的全部历史数据")
604
+ print("=" * 60)
605
+ print(f"数据将保存到: {save_directory}")
606
+
607
+ # 检查必要库
608
+ try:
609
+ import requests
610
+ import numpy as np
611
+ except ImportError:
612
+ print("正在安装必要库...")
613
+ import subprocess
614
+ subprocess.check_call(["pip", "install", "requests", "numpy", "pandas"])
615
+ import requests
616
+ import numpy as np
617
+
618
+ # 获取全历史数据(多数据源)
619
+ stock_data = get_stock_data_with_retry_all_history(stock_code)
620
+
621
+ if stock_data is not None:
622
+ # 显示数据信息
623
+ display_all_history_data_info(stock_data, stock_code)
624
+
625
+ # 保存全历史数据到指定目录
626
+ save_all_history_stock_data(stock_data, stock_code, save_directory)
627
+
628
+ print(f"\n🎉 股票 {stock_code} 全历史数据处理完成!")
629
+ print(
630
+ f"数据时间跨度: {stock_data.index.min().strftime('%Y-%m-%d')} 到 {stock_data.index.max().strftime('%Y-%m-%d')}")
631
+ print(f"总交易天数: {len(stock_data):,}")
632
+
633
+ # 显示保存的文件
634
+ csv_file = os.path.join(save_directory, f"{stock_code}_all_history.csv")
635
+ if os.path.exists(csv_file):
636
+ file_size = os.path.getsize(csv_file) / 1024 # KB
637
+ print(f"📄 生成的文件: {csv_file} ({file_size:.1f} KB)")
638
+ else:
639
+ print("❌ 未能获取股票全历史数据")
640
+
641
+
642
+ # 使用方法说明
643
+ if __name__ == "__main__":
644
+ """
645
+ 使用方法:
646
+ 修改下面的参数来获取不同股票的全历史数据
647
+ """
648
+
649
+ # ==================== 在这里修改参数 ====================
650
+ TARGET_STOCK_CODE = "300418" # 股票代码
651
+ # =====================================================
652
+
653
+ print("股票全历史数据获取工具")
654
+ print("说明:修改代码中的 TARGET_STOCK_CODE 来获取不同股票的全部历史数据")
655
+ print(f"当前设置: 股票代码={TARGET_STOCK_CODE}")
656
+ print()
657
+
658
+ # 运行主程序
659
+ main_all_history(stock_code=TARGET_STOCK_CODE)
660
+
661
+ print(f"\n💡 提示:要获取其他股票的全历史数据,请修改代码中的 TARGET_STOCK_CODE 变量")
Kronos/examples/prediction_akshare_2024-2025.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import matplotlib.pyplot as plt
3
+ import numpy as np
4
+ import sys
5
+ import os
6
+ from datetime import datetime, timedelta
7
+ import warnings
8
+
9
+ warnings.filterwarnings('ignore')
10
+
11
+ # 添加项目路径以便导入自定义模块
12
+ sys.path.append("../")
13
+ from model import Kronos, KronosTokenizer, KronosPredictor
14
+
15
+ # 设置中文字体
16
+ plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
17
+ plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
18
+
19
+
20
+ def ensure_output_directory(output_dir):
21
+ """确保输出目录存在,如果不存在则创建"""
22
+ if not os.path.exists(output_dir):
23
+ os.makedirs(output_dir)
24
+ print(f"✅ 创建输出目录: {output_dir}")
25
+ return output_dir
26
+
27
+
28
+ def prepare_stock_data(csv_file_path, stock_code):
29
+ """
30
+ 准备股票数据,转换为Kronos模型需要的格式
31
+
32
+ 参数:
33
+ csv_file_path: CSV文件路径
34
+ stock_code: 股票代码,用于显示信息
35
+
36
+ 返回:
37
+ df: 处理后的DataFrame
38
+ """
39
+ print(f"正在加载和预处理股票 {stock_code} 数据...")
40
+
41
+ # 读取CSV文件
42
+ df = pd.read_csv(csv_file_path, encoding='utf-8-sig')
43
+
44
+ # 检查数据列名并重命名为标准格式
45
+ column_mapping = {
46
+ '日期': 'timestamps',
47
+ '开盘价': 'open',
48
+ '最高价': 'high',
49
+ '最低价': 'low',
50
+ '收盘价': 'close',
51
+ '成交量': 'volume',
52
+ '成交额': 'amount'
53
+ }
54
+
55
+ # 只重命名存在的列
56
+ actual_mapping = {k: v for k, v in column_mapping.items() if k in df.columns}
57
+ df = df.rename(columns=actual_mapping)
58
+
59
+ # 确保时间戳列存在并转换为datetime格式
60
+ if 'timestamps' not in df.columns:
61
+ # 如果数据有日期索引,重置索引
62
+ if df.index.name == '日期':
63
+ df = df.reset_index()
64
+ df = df.rename(columns={'日期': 'timestamps'})
65
+
66
+ df['timestamps'] = pd.to_datetime(df['timestamps'])
67
+
68
+ # 按时间排序
69
+ df = df.sort_values('timestamps').reset_index(drop=True)
70
+
71
+ print(f"✅ 数据加载完成,共 {len(df)} 条记录")
72
+ print(f"时间范围: {df['timestamps'].min()} 到 {df['timestamps'].max()}")
73
+ print(f"数据列: {df.columns.tolist()}")
74
+
75
+ return df
76
+
77
+
78
+ def calculate_prediction_parameters(df, target_days=100):
79
+ """
80
+ 根据目标预测天数计算合适的参数
81
+
82
+ 参数:
83
+ df: 股票数据DataFrame
84
+ target_days: 目标预测天数(自然日)
85
+
86
+ 返回:
87
+ lookback: 回看期数
88
+ pred_len: 预测期数
89
+ """
90
+ # 计算平均交易日数量(考虑节假日)
91
+ total_days = (df['timestamps'].max() - df['timestamps'].min()).days
92
+ trading_days = len(df)
93
+ trading_ratio = trading_days / total_days if total_days > 0 else 0.7 # 交易日比例
94
+
95
+ # 计算目标预测的交易日数量
96
+ pred_trading_days = int(target_days * trading_ratio)
97
+
98
+ # 设置回看期数为预测期数的2-3倍,但不超过数据总量的70%
99
+ max_lookback = int(len(df) * 0.7)
100
+ lookback = min(pred_trading_days * 2, max_lookback, len(df) - pred_trading_days)
101
+ pred_len = min(pred_trading_days, len(df) - lookback)
102
+
103
+ print(f"📊 参数计算:")
104
+ print(f" 目标预测天数: {target_days} 天(自然日)")
105
+ print(f" 预计交易日数量: {pred_trading_days} 天")
106
+ print(f" 回看期数 (lookback): {lookback}")
107
+ print(f" 预测期数 (pred_len): {pred_len}")
108
+
109
+ return lookback, pred_len
110
+
111
+
112
+ def generate_future_dates_with_holidays(last_date, pred_len):
113
+ """
114
+ 生成未来的交易日日期,考虑中国节假日
115
+
116
+ 参数:
117
+ last_date: 最后一个历史数据的日期
118
+ pred_len: 预测期数
119
+
120
+ 返回:
121
+ future_dates: 未来的交易日日期列表
122
+ """
123
+ # 中国主要节假日(需要根据实际情况调整)
124
+ holidays_2025 = [
125
+ # 2025年国庆节假期(通常为10月1日-10月8日)
126
+ datetime(2025, 10, 1), datetime(2025, 10, 2), datetime(2025, 10, 3),
127
+ datetime(2025, 10, 4), datetime(2025, 10, 5), datetime(2025, 10, 6),
128
+ datetime(2025, 10, 7), datetime(2025, 10, 8), # 添加10月8日
129
+ # 周末调休等可以根据需要添加
130
+ ]
131
+
132
+ future_dates = []
133
+ current_date = last_date + timedelta(days=1)
134
+
135
+ while len(future_dates) < pred_len:
136
+ # 如果是工作日(周一到周五)且不是节假日
137
+ if current_date.weekday() < 5 and current_date not in holidays_2025:
138
+ future_dates.append(current_date)
139
+ current_date += timedelta(days=1)
140
+
141
+ print(f"📅 生成的未来交易日: 共 {len(future_dates)} 天")
142
+ print(f" 起始日期: {future_dates[0].strftime('%Y-%m-%d')}")
143
+ print(f" 结束日期: {future_dates[-1].strftime('%Y-%m-%d')}")
144
+
145
+ # 显示节假日信息
146
+ holiday_count = sum(1 for date in holidays_2025 if date > last_date)
147
+ print(f" 包含节假日: {holiday_count} 天")
148
+
149
+ return future_dates[:pred_len]
150
+
151
+
152
+ def plot_prediction_with_details(kline_df, pred_df, future_dates, stock_code="002354", stock_name="股票", pred_len=100,
153
+ output_dir="."):
154
+ """
155
+ 绘制详细的预测结果图表 - 优化版,图表更大更清晰
156
+
157
+ 参数:
158
+ kline_df: 历史K线数据
159
+ pred_df: 预测数据
160
+ future_dates: 未来日期列表
161
+ stock_code: 股票代码
162
+ stock_name: 股票名称
163
+ pred_len: 预测期数
164
+ output_dir: 输出目录
165
+ """
166
+ # 确保输出目录存在
167
+ ensure_output_directory(output_dir)
168
+
169
+ # 确保数据长度一致
170
+ min_len = min(len(pred_df), len(future_dates))
171
+ pred_df = pred_df.iloc[:min_len]
172
+ future_dates = future_dates[:min_len]
173
+
174
+ # 设置预测数据的索引为未来日期
175
+ pred_df.index = future_dates
176
+
177
+ # 准备价格数据
178
+ sr_close = kline_df.set_index('timestamps')['close']
179
+ sr_pred_close = pred_df['close']
180
+ sr_close.name = '历史数据'
181
+ sr_pred_close.name = "预测数据"
182
+
183
+ # 准备成交量数据
184
+ sr_volume = kline_df.set_index('timestamps')['volume']
185
+ sr_pred_volume = pred_df['volume']
186
+ sr_volume.name = '历史数据'
187
+ sr_pred_volume.name = "预测数据"
188
+
189
+ # 合并数据
190
+ close_df = pd.concat([sr_close, sr_pred_close], axis=1)
191
+ volume_df = pd.concat([sr_volume, sr_pred_volume], axis=1)
192
+
193
+ # 创建更大的图表
194
+ fig = plt.figure(figsize=(18, 14))
195
+
196
+ # 使用GridSpec创建更灵活的布局
197
+ gs = plt.GridSpec(3, 1, figure=fig, height_ratios=[3, 1, 1])
198
+
199
+ ax1 = fig.add_subplot(gs[0]) # 价格图表
200
+ ax2 = fig.add_subplot(gs[1]) # 成交量图表
201
+ ax3 = fig.add_subplot(gs[2]) # 价格变动图表
202
+
203
+ # 1. 价格图表 - 更大更清晰
204
+ # 只显示最近200个交易日的历史数据,避免图表过于拥挤
205
+ recent_history = close_df['历史数据'].iloc[-min(200, len(close_df['历史数据'])):]
206
+ ax1.plot(recent_history.index, recent_history.values, label='历史价格', color='#1f77b4', linewidth=2.5, alpha=0.9)
207
+ ax1.plot(close_df['预测数据'].index, close_df['预测数据'].values, label='预测价格',
208
+ color='#ff7f0e', linewidth=2.5, linestyle='-', marker='o', markersize=3)
209
+
210
+ # 添加预测起始点的标记
211
+ prediction_start_date = close_df['预测数据'].index[0] if len(close_df['预测数据']) > 0 else close_df.index[-1]
212
+ prediction_start_price = close_df['历史数据'].iloc[-1]
213
+ ax1.axvline(x=prediction_start_date, color='red', linestyle='--', alpha=0.7, linewidth=1.5)
214
+ ax1.annotate('预测起点', xy=(prediction_start_date, prediction_start_price),
215
+ xytext=(10, 10), textcoords='offset points',
216
+ bbox=dict(boxstyle='round,pad=0.3', facecolor='yellow', alpha=0.7),
217
+ arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
218
+
219
+ ax1.set_ylabel('收盘价 (元)', fontsize=14, fontweight='bold')
220
+ ax1.legend(loc='upper left', fontsize=12)
221
+ ax1.grid(True, alpha=0.3)
222
+ ax1.set_title(f'{stock_name}({stock_code}) 股票价格预测 - 未来{pred_len}个交易日',
223
+ fontsize=16, fontweight='bold', pad=20)
224
+
225
+ # 设置x轴日期格式
226
+ ax1.xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter('%Y-%m-%d'))
227
+ plt.setp(ax1.xaxis.get_majorticklabels(), rotation=45)
228
+
229
+ # 设置y轴格式
230
+ ax1.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'{x:.2f}'))
231
+
232
+ # 2. 成交量图表 - 优化显示
233
+ # 只显示预测期的成交量
234
+ pred_volumes = volume_df['预测数据'].dropna()
235
+ if len(pred_volumes) > 0:
236
+ ax2.bar(pred_volumes.index, pred_volumes.values,
237
+ alpha=0.7, color='#ff7f0e', label='预测成交量', width=0.8)
238
+
239
+ ax2.set_ylabel('成交量 (手)', fontsize=14, fontweight='bold')
240
+ ax2.legend(loc='upper left', fontsize=12)
241
+ ax2.grid(True, alpha=0.3)
242
+
243
+ # 设置x轴标签
244
+ if len(pred_volumes) > 0:
245
+ ax2.xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter('%m-%d'))
246
+ plt.setp(ax2.xaxis.get_majorticklabels(), rotation=45)
247
+
248
+ # 3. 价格变动图表 - 优化显示
249
+ if len(close_df['预测数据']) > 0:
250
+ price_change = close_df['预测数据'] - close_df['历史数据'].iloc[-1]
251
+ colors = ['green' if x >= 0 else 'red' for x in price_change]
252
+
253
+ # 每5个交易日显示一个标签,避免过于拥挤
254
+ bars = ax3.bar(range(len(price_change)), price_change, alpha=0.8, color=colors)
255
+
256
+ # 在关键点添加数值标签
257
+ for i, bar in enumerate(bars):
258
+ height = bar.get_height()
259
+ if i % 10 == 0 or i == len(bars) - 1 or abs(height) > price_change.std(): # 每10天或最后一天或显著波动
260
+ ax3.text(bar.get_x() + bar.get_width() / 2., height,
261
+ f'{height:+.2f}', ha='center', va='bottom' if height >= 0 else 'top',
262
+ fontsize=8, fontweight='bold')
263
+
264
+ ax3.axhline(y=0, color='black', linestyle='-', alpha=0.5, linewidth=1)
265
+
266
+ ax3.set_ylabel('价格变动 (��)', fontsize=14, fontweight='bold')
267
+ ax3.set_xlabel('交易日', fontsize=14, fontweight='bold')
268
+ ax3.grid(True, alpha=0.3)
269
+
270
+ # 设置x轴标签
271
+ if len(price_change) > 0:
272
+ # 每10个交易日显示一个标签
273
+ xticks_positions = list(range(0, len(price_change), max(1, len(price_change) // 10)))
274
+ if len(price_change) - 1 not in xticks_positions:
275
+ xticks_positions.append(len(price_change) - 1)
276
+ ax3.set_xticks(xticks_positions)
277
+ ax3.set_xticklabels([f'D{i + 1}' for i in xticks_positions])
278
+
279
+ # 添加详细的统计信息框
280
+ if len(close_df['预测数据']) > 0 and not np.isnan(close_df['历史数据'].iloc[-1]):
281
+ pred_stats = {
282
+ '股票代码': stock_code,
283
+ '股票名称': stock_name,
284
+ '当前价格': f"{close_df['历史数据'].iloc[-1]:.2f} 元",
285
+ '预测结束价格': f"{close_df['预测数据'].iloc[-1]:.2f} 元",
286
+ '预测涨跌幅': f"{(close_df['预测数据'].iloc[-1] / close_df['历史数据'].iloc[-1] - 1) * 100:+.2f}%",
287
+ '预测期间最高价': f"{close_df['预测数据'].max():.2f} 元",
288
+ '预测期间最低价': f"{close_df['预测数据'].min():.2f} 元",
289
+ '预测波动率': f"{close_df['预测数据'].std():.2f} 元",
290
+ '预测起始日期': f"{close_df['预测数据'].index[0].strftime('%Y-%m-%d')}",
291
+ '预测结束日期': f"{close_df['预测数据'].index[-1].strftime('%Y-%m-%d')}",
292
+ '预测交易日数': f"{len(close_df['预测数据'])} 天"
293
+ }
294
+
295
+ stats_text = "\n".join([f"{k}: {v}" for k, v in pred_stats.items()])
296
+ fig.text(0.02, 0.02, stats_text, fontsize=10,
297
+ bbox=dict(boxstyle="round,pad=0.5", facecolor="lightblue", alpha=0.8),
298
+ verticalalignment='bottom')
299
+
300
+ plt.tight_layout()
301
+
302
+ # 保存高分辨率图片到指定目录
303
+ chart_filename = os.path.join(output_dir, f'{stock_code}_prediction_chart.png')
304
+ plt.savefig(chart_filename, dpi=300, bbox_inches='tight', facecolor='white')
305
+ print(f"📊 预测图表已保存: {chart_filename}")
306
+
307
+ plt.show()
308
+
309
+ return close_df, volume_df
310
+
311
+
312
+ def generate_prediction_report(close_df, volume_df, pred_df, future_dates, stock_code="002354", stock_name="股票",
313
+ output_dir="."):
314
+ """
315
+ 生成预测报告
316
+ """
317
+ # 确保输出目录存在
318
+ ensure_output_directory(output_dir)
319
+
320
+ print(f"\n{'=' * 70}")
321
+ print(f"📊 {stock_name}({stock_code}) 股票预测报告")
322
+ print(f"{'=' * 70}")
323
+
324
+ if len(close_df['预测数据']) == 0 or np.isnan(close_df['历史数据'].iloc[-1]):
325
+ print("❌ 没有有效的预测数据可生成报告")
326
+ return
327
+
328
+ # 确保所有数组长度一致
329
+ min_len = min(len(close_df['预测数据']), len(volume_df['预测数据']), len(future_dates))
330
+
331
+ # 基本统计
332
+ historical_close = close_df['历史数据'].iloc[-1]
333
+ predicted_close = close_df['预测数据'].iloc[-1]
334
+ price_change_pct = (predicted_close / historical_close - 1) * 100
335
+
336
+ print(f"🔮 预测概览:")
337
+ print(f" 当前价格: {historical_close:.2f} 元")
338
+ print(f" 预测结束价格: {predicted_close:.2f} 元")
339
+ print(f" 预测涨跌幅: {price_change_pct:+.2f}%")
340
+ print(f" 预测期间: {min_len} 个交易日")
341
+ print(
342
+ f" 预测时间范围: {future_dates[0].strftime('%Y-%m-%d')} 到 {future_dates[min_len - 1].strftime('%Y-%m-%d')}")
343
+
344
+ print(f"\n📈 价格预测统计:")
345
+ print(f" 预测最高价: {close_df['预测数据'].max():.2f} 元")
346
+ print(f" 预测最低价: {close_df['预测数据'].min():.2f} 元")
347
+ print(f" 预测平均价: {close_df['预测数据'].mean():.2f} 元")
348
+ print(f" 价格波动率: {close_df['预测数据'].std():.2f} 元")
349
+
350
+ print(f"\n📊 成交量预测统计:")
351
+ print(f" 预测平均成交量: {volume_df['预测数据'].mean():,.0f} 手")
352
+ print(f" 预测最大成交量: {volume_df['预测数据'].max():,.0f} 手")
353
+ print(f" 预测最小成交量: {volume_df['预测数据'].min():,.0f} 手")
354
+
355
+ # 保存详细预测数据到指定目录 - 确保所有数组长度一致
356
+ prediction_details = pd.DataFrame({
357
+ '日期': future_dates[:min_len],
358
+ '预测收盘价': close_df['预测数据'].values[:min_len],
359
+ '预测成交量': volume_df['预测数据'].values[:min_len],
360
+ '价格变动(元)': (close_df['预测数据'].values[:min_len] - historical_close),
361
+ '价格变动(%)': ((close_df['预测数据'].values[:min_len] / historical_close - 1) * 100)
362
+ })
363
+
364
+ prediction_file = os.path.join(output_dir, f'{stock_code}_detailed_predictions.csv')
365
+ prediction_details.to_csv(prediction_file, index=False, encoding='utf-8-sig')
366
+ print(f"\n💾 详细预测数据已保存: {prediction_file}")
367
+
368
+
369
+ def main(stock_code="002354", stock_name="天娱数科", data_dir="./data", pred_days=100, output_dir="./output"):
370
+ """
371
+ 主函数:执行股票价格预测
372
+
373
+ 参数:
374
+ stock_code: 股票代码
375
+ stock_name: 股票名称
376
+ data_dir: 数据文件目录
377
+ pred_days: 预测天数(自然日)
378
+ output_dir: 输出文件目录
379
+ """
380
+ # 构建数据文件路径
381
+ csv_file_path = os.path.join(data_dir, f"{stock_code}_stock_data.csv")
382
+
383
+ print(f"🎯 开始 {stock_name}({stock_code}) 股票价格预测")
384
+ print("=" * 70)
385
+ print(f"数据文件: {csv_file_path}")
386
+ print(f"预测天数: {pred_days} 天(自然日)")
387
+ print(f"输出目录: {output_dir}")
388
+
389
+ # 检查数据文件是否存在
390
+ if not os.path.exists(csv_file_path):
391
+ print(f"❌ 数据文件不存在: {csv_file_path}")
392
+ print("请先运行数据获取脚本生成股票数据文件")
393
+ return
394
+
395
+ # 确保输出目录存在
396
+ ensure_output_directory(output_dir)
397
+
398
+ try:
399
+ # 1. 加载模型和分词器
400
+ print("\n步骤1: 加载Kronos模型和分词器...")
401
+ tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base")
402
+ model = Kronos.from_pretrained("NeoQuasar/Kronos-base")
403
+ print("✅ 模型加载完成")
404
+
405
+ # 2. 实例化预测器
406
+ print("步骤2: 初始化预测器...")
407
+ predictor = KronosPredictor(model, tokenizer, device="cuda:0", max_context=512)
408
+ print("✅ 预测器初始化完成")
409
+
410
+ # 3. 准备数据
411
+ print("步骤3: 准备股票数据...")
412
+ df = prepare_stock_data(csv_file_path, stock_code)
413
+
414
+ # 4. 计算预测参数
415
+ print("步骤4: 计算预测参数...")
416
+ lookback, pred_len = calculate_prediction_parameters(df, target_days=pred_days)
417
+
418
+ if pred_len <= 0:
419
+ print("❌ 数据量不足,无法进行预测")
420
+ return
421
+
422
+ print(f"✅ 最终参数 - 回看期: {lookback}, 预测期: {pred_len}")
423
+
424
+ # 5. 准备输入数据
425
+ print("步骤5: 准备输入数据...")
426
+ # 使用最新的数据作为输入
427
+ x_df = df.loc[-lookback:, ['open', 'high', 'low', 'close', 'volume', 'amount']].reset_index(drop=True)
428
+ x_timestamp = df.loc[-lookback:, 'timestamps'].reset_index(drop=True)
429
+
430
+ # 生成未来日期(考虑节假日)
431
+ last_historical_date = df['timestamps'].iloc[-1]
432
+ future_dates = generate_future_dates_with_holidays(last_historical_date, pred_len)
433
+
434
+ print(f"输入数据形状: {x_df.shape}")
435
+ print(f"历史数据时间范围: {x_timestamp.iloc[0]} 到 {x_timestamp.iloc[-1]}")
436
+ print(f"预测时间范围: {future_dates[0]} 到 {future_dates[-1]}")
437
+
438
+ # 6. 执行预测
439
+ print("步骤6: 执行价格预测...")
440
+ pred_df = predictor.predict(
441
+ df=x_df,
442
+ x_timestamp=x_timestamp,
443
+ y_timestamp=pd.Series(future_dates), # 使用未来日期作为预测时间戳
444
+ pred_len=pred_len,
445
+ T=1.0,
446
+ top_p=0.9,
447
+ sample_count=1,
448
+ verbose=True
449
+ )
450
+
451
+ print("✅ 预测完成")
452
+
453
+ # 7. 显示预测结果
454
+ print("\n步骤7: 显示预测结果...")
455
+ print("预测数据前5行:")
456
+ # 确保预测数据长度与未来日期一致
457
+ min_len = min(len(pred_df), len(future_dates))
458
+ pred_df = pred_df.iloc[:min_len]
459
+ pred_df.index = future_dates[:min_len]
460
+ print(pred_df.head())
461
+
462
+ # 8. 可视化结果
463
+ print("步骤8: 生成可视化图表...")
464
+ # 使用最后一部分历史数据和预测数据
465
+ kline_df = df.loc[-lookback:].reset_index(drop=True)
466
+ close_df, volume_df = plot_prediction_with_details(kline_df, pred_df, future_dates, stock_code, stock_name,
467
+ pred_len, output_dir)
468
+
469
+ # 9. 生成预测报告
470
+ print("步骤9: 生成预测报告...")
471
+ generate_prediction_report(close_df, volume_df, pred_df, future_dates, stock_code, stock_name, output_dir)
472
+
473
+ print(f"\n🎉 {stock_name}({stock_code}) 股票预测完成!")
474
+ print("生成的文件:")
475
+ print(f" 📊 {os.path.join(output_dir, stock_code + '_prediction_chart.png')} - 预测图表")
476
+ print(f" 📋 {os.path.join(output_dir, stock_code + '_detailed_predictions.csv')} - 详细预测数据")
477
+
478
+ # 显示预测总结
479
+ if len(close_df['预测数据']) > 0 and not np.isnan(close_df['历史数据'].iloc[-1]):
480
+ print(f"\n📈 预测总结:")
481
+ historical_price = close_df['历史数据'].iloc[-1]
482
+ predicted_price = close_df['预测数据'].iloc[-1]
483
+ change_pct = (predicted_price / historical_price - 1) * 100
484
+
485
+ print(f" 当前价格: {historical_price:.2f} 元")
486
+ print(f" 预测价格: {predicted_price:.2f} 元")
487
+ print(f" 预期涨跌: {change_pct:+.2f}%")
488
+ print(
489
+ f" 预测时间: {future_dates[0].strftime('%Y-%m-%d')} 到 {future_dates[min_len - 1].strftime('%Y-%m-%d')}")
490
+
491
+ if change_pct > 10:
492
+ print(f" 🚀 模型预测未来{pred_len}个交易日大幅看涨 (+{change_pct:.1f}%)")
493
+ elif change_pct > 5:
494
+ print(f" 📈 模型预测未来{pred_len}个交易日看涨 (+{change_pct:.1f}%)")
495
+ elif change_pct > 0:
496
+ print(f" ↗️ 模型预测未来{pred_len}个交易日微涨 (+{change_pct:.1f}%)")
497
+ elif change_pct > -5:
498
+ print(f" ↘️ 模型预测未来{pred_len}个交易日微跌 ({change_pct:.1f}%)")
499
+ elif change_pct > -10:
500
+ print(f" 📉 模型预测未来{pred_len}个交易日看跌 ({change_pct:.1f}%)")
501
+ else:
502
+ print(f" 🔻 模型预测未来{pred_len}个交易日大幅看跌 ({change_pct:.1f}%)")
503
+
504
+ except Exception as e:
505
+ print(f"❌ 预测过程中出现错误: {e}")
506
+ import traceback
507
+ traceback.print_exc()
508
+
509
+
510
+ # 使用方法说明
511
+ if __name__ == "__main__":
512
+ """
513
+ 股票预测工具 - 支持多股票预测
514
+
515
+ 使用方法:
516
+ 修改下面的 STOCK_CONFIG 来预测不同的股票
517
+ """
518
+
519
+ # ==================== 在这里修改股票配置 ====================
520
+ STOCK_CONFIG = {
521
+ "stock_code": "300418", # 股票代码
522
+ "stock_name": "昆仑万维", # 股票名称
523
+ "data_dir": "./data", # 数据文件目录
524
+ "pred_days": 100, # 预测100个自然日
525
+ "output_dir": r"D:\lianghuajiaoyi\Kronos\examples\yuce" # 输出文件目录
526
+ }
527
+
528
+ # 其他股票配置示例:
529
+ # STOCK_CONFIG = {"stock_code": "000001", "stock_name": "平安银行", "data_dir": "./data", "pred_days": 100, "output_dir": r"D:\lianghuajiaoyi\Kronos\examples\yuce"}
530
+ # STOCK_CONFIG = {"stock_code": "600036", "stock_name": "招商银行", "data_dir": "./data", "pred_days": 100, "output_dir": r"D:\lianghuajiaoyi\Kronos\examples\yuce"}
531
+ # STOCK_CONFIG = {"stock_code": "300750", "stock_name": "宁德时代", "data_dir": "./data", "pred_days": 100, "output_dir": r"D:\lianghuajiaoyi\Kronos\examples\yuce"}
532
+ # =========================================================
533
+
534
+ print("🤖 智能股票预测工具")
535
+ print("=" * 70)
536
+ print(f"当前预测股票: {STOCK_CONFIG['stock_name']}({STOCK_CONFIG['stock_code']})")
537
+ print(f"数据目录: {STOCK_CONFIG['data_dir']}")
538
+ print(f"预测天数: {STOCK_CONFIG['pred_days']} 天(自然日)")
539
+ print(f"输出目录: {STOCK_CONFIG['output_dir']}")
540
+ print()
541
+
542
+ # 运行主程序
543
+ main(**STOCK_CONFIG)
544
+
545
+ print(f"\n💡 提示:要预测其他股票,请修改代码中的 STOCK_CONFIG 变量")
Kronos/examples/prediction_batch_example.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import matplotlib.pyplot as plt
3
+ import sys
4
+ sys.path.append("../")
5
+ from model import Kronos, KronosTokenizer, KronosPredictor
6
+
7
+
8
+ def plot_prediction(kline_df, pred_df):
9
+ pred_df.index = kline_df.index[-pred_df.shape[0]:]
10
+ sr_close = kline_df['close']
11
+ sr_pred_close = pred_df['close']
12
+ sr_close.name = 'Ground Truth'
13
+ sr_pred_close.name = "Prediction"
14
+
15
+ sr_volume = kline_df['volume']
16
+ sr_pred_volume = pred_df['volume']
17
+ sr_volume.name = 'Ground Truth'
18
+ sr_pred_volume.name = "Prediction"
19
+
20
+ close_df = pd.concat([sr_close, sr_pred_close], axis=1)
21
+ volume_df = pd.concat([sr_volume, sr_pred_volume], axis=1)
22
+
23
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6), sharex=True)
24
+
25
+ ax1.plot(close_df['Ground Truth'], label='Ground Truth', color='blue', linewidth=1.5)
26
+ ax1.plot(close_df['Prediction'], label='Prediction', color='red', linewidth=1.5)
27
+ ax1.set_ylabel('Close Price', fontsize=14)
28
+ ax1.legend(loc='lower left', fontsize=12)
29
+ ax1.grid(True)
30
+
31
+ ax2.plot(volume_df['Ground Truth'], label='Ground Truth', color='blue', linewidth=1.5)
32
+ ax2.plot(volume_df['Prediction'], label='Prediction', color='red', linewidth=1.5)
33
+ ax2.set_ylabel('Volume', fontsize=14)
34
+ ax2.legend(loc='upper left', fontsize=12)
35
+ ax2.grid(True)
36
+
37
+ plt.tight_layout()
38
+ plt.show()
39
+
40
+
41
+ # 1. Load Model and Tokenizer
42
+ tokenizer = KronosTokenizer.from_pretrained('/home/csc/huggingface/Kronos-Tokenizer-base/')
43
+ model = Kronos.from_pretrained("/home/csc/huggingface/Kronos-base/")
44
+
45
+ # 2. Instantiate Predictor
46
+ predictor = KronosPredictor(model, tokenizer, device="cuda:0", max_context=512)
47
+
48
+ # 3. Prepare Data
49
+ df = pd.read_csv("./data/XSHG_5min_600977.csv")
50
+ df['timestamps'] = pd.to_datetime(df['timestamps'])
51
+
52
+ lookback = 400
53
+ pred_len = 120
54
+
55
+ dfs = []
56
+ xtsp = []
57
+ ytsp = []
58
+ for i in range(5):
59
+ idf = df.loc[(i*400):(i*400+lookback-1), ['open', 'high', 'low', 'close', 'volume', 'amount']]
60
+ i_x_timestamp = df.loc[(i*400):(i*400+lookback-1), 'timestamps']
61
+ i_y_timestamp = df.loc[(i*400+lookback):(i*400+lookback+pred_len-1), 'timestamps']
62
+
63
+ dfs.append(idf)
64
+ xtsp.append(i_x_timestamp)
65
+ ytsp.append(i_y_timestamp)
66
+
67
+ pred_df = predictor.predict_batch(
68
+ df_list=dfs,
69
+ x_timestamp_list=xtsp,
70
+ y_timestamp_list=ytsp,
71
+ pred_len=pred_len,
72
+ )
Kronos/examples/prediction_cn_markets_day.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ prediction_cn_markets_day.py
4
+
5
+ Description:
6
+ Predicts future daily K-line (1D) data for A-share markets using Kronos model and akshare.
7
+ The script automatically downloads the latest historical data, cleans it, and runs model inference.
8
+
9
+ Usage:
10
+ python prediction_cn_markets_day.py --symbol 000001
11
+
12
+ Arguments:
13
+ --symbol Stock code (e.g. 002594 for BYD, 000001 for SSE Index)
14
+
15
+ Output:
16
+ - Saves the prediction results to ./outputs/pred_<symbol>_data.csv and ./outputs/pred_<symbol>_chart.png
17
+ - Logs and progress are printed to console
18
+
19
+ Example:
20
+ bash> python prediction_cn_markets_day.py --symbol 000001
21
+ python3 prediction_cn_markets_day.py --symbol 002594
22
+ """
23
+
24
+ import os
25
+ import argparse
26
+ import time
27
+ import pandas as pd
28
+ import akshare as ak
29
+ import matplotlib.pyplot as plt
30
+ import sys
31
+ sys.path.append("../")
32
+ from model import Kronos, KronosTokenizer, KronosPredictor
33
+
34
+ save_dir = "./outputs"
35
+ os.makedirs(save_dir, exist_ok=True)
36
+
37
+ # Setting
38
+ TOKENIZER_PRETRAINED = "NeoQuasar/Kronos-Tokenizer-base"
39
+ MODEL_PRETRAINED = "NeoQuasar/Kronos-base"
40
+ DEVICE = "cpu" # "cuda:0"
41
+ MAX_CONTEXT = 512
42
+ LOOKBACK = 400
43
+ PRED_LEN = 120
44
+ T = 1.0
45
+ TOP_P = 0.9
46
+ SAMPLE_COUNT = 1
47
+
48
+ def load_data(symbol: str) -> pd.DataFrame:
49
+ print(f"📥 Fetching {symbol} daily data from akshare ...")
50
+
51
+ max_retries = 3
52
+ df = None
53
+
54
+ # Retry mechanism
55
+ for attempt in range(1, max_retries + 1):
56
+ try:
57
+ df = ak.stock_zh_a_hist(symbol=symbol, period="daily", adjust="")
58
+ if df is not None and not df.empty:
59
+ break
60
+ except Exception as e:
61
+ print(f"⚠️ Attempt {attempt}/{max_retries} failed: {e}")
62
+ time.sleep(1.5)
63
+
64
+ # If still empty after retries
65
+ if df is None or df.empty:
66
+ print(f"❌ Failed to fetch data for {symbol} after {max_retries} attempts. Exiting.")
67
+ sys.exit(1)
68
+
69
+ df.rename(columns={
70
+ "日期": "date",
71
+ "开盘": "open",
72
+ "收盘": "close",
73
+ "最高": "high",
74
+ "最低": "low",
75
+ "成交量": "volume",
76
+ "成交额": "amount"
77
+ }, inplace=True)
78
+
79
+ df["date"] = pd.to_datetime(df["date"])
80
+ df = df.sort_values("date").reset_index(drop=True)
81
+
82
+ # Convert numeric columns
83
+ numeric_cols = ["open", "high", "low", "close", "volume", "amount"]
84
+ for col in numeric_cols:
85
+ df[col] = (
86
+ df[col]
87
+ .astype(str)
88
+ .str.replace(",", "", regex=False)
89
+ .replace({"--": None, "": None})
90
+ )
91
+ df[col] = pd.to_numeric(df[col], errors="coerce")
92
+
93
+ # Fix invalid open values
94
+ open_bad = (df["open"] == 0) | (df["open"].isna())
95
+ if open_bad.any():
96
+ print(f"⚠️ Fixed {open_bad.sum()} invalid open values.")
97
+ df.loc[open_bad, "open"] = df["close"].shift(1)
98
+ df["open"].fillna(df["close"], inplace=True)
99
+
100
+ # Fix missing amount
101
+ if df["amount"].isna().all() or (df["amount"] == 0).all():
102
+ df["amount"] = df["close"] * df["volume"]
103
+
104
+ print(f"✅ Data loaded: {len(df)} rows, range: {df['date'].min()} ~ {df['date'].max()}")
105
+
106
+ print("Data Head:")
107
+ print(df.head())
108
+
109
+ return df
110
+
111
+
112
+ def prepare_inputs(df):
113
+ x_df = df.iloc[-LOOKBACK:][["open","high","low","close","volume","amount"]]
114
+ x_timestamp = df.iloc[-LOOKBACK:]["date"]
115
+ y_timestamp = pd.bdate_range(start=df["date"].iloc[-1] + pd.Timedelta(days=1), periods=PRED_LEN)
116
+ return x_df, pd.Series(x_timestamp), pd.Series(y_timestamp)
117
+
118
+ def apply_price_limits(pred_df, last_close, limit_rate=0.1):
119
+ print(f"🔒 Applying ±{limit_rate*100:.0f}% price limit ...")
120
+
121
+ # Ensure integer index
122
+ pred_df = pred_df.reset_index(drop=True)
123
+
124
+ # Ensure float64 dtype for safe assignment
125
+ cols = ["open", "high", "low", "close"]
126
+ pred_df[cols] = pred_df[cols].astype("float64")
127
+
128
+ for i in range(len(pred_df)):
129
+ limit_up = last_close * (1 + limit_rate)
130
+ limit_down = last_close * (1 - limit_rate)
131
+
132
+ for col in cols:
133
+ value = pred_df.at[i, col]
134
+ if pd.notna(value):
135
+ clipped = max(min(value, limit_up), limit_down)
136
+ pred_df.at[i, col] = float(clipped)
137
+
138
+ last_close = float(pred_df.at[i, "close"]) # ensure float type
139
+
140
+ return pred_df
141
+
142
+
143
+ def plot_result(df_hist, df_pred, symbol):
144
+ plt.figure(figsize=(12, 6))
145
+ plt.plot(df_hist["date"], df_hist["close"], label="Historical", color="blue")
146
+ plt.plot(df_pred["date"], df_pred["close"], label="Predicted", color="red", linestyle="--")
147
+ plt.title(f"Kronos Prediction for {symbol}")
148
+ plt.xlabel("Date")
149
+ plt.ylabel("Close Price")
150
+ plt.legend()
151
+ plt.grid(True)
152
+ plt.tight_layout()
153
+ plot_path = os.path.join(save_dir, f"pred_{symbol.replace('.', '_')}_chart.png")
154
+ plt.savefig(plot_path)
155
+ plt.close()
156
+ print(f"📊 Chart saved: {plot_path}")
157
+
158
+
159
+ def predict_future(symbol):
160
+ print(f"🚀 Loading Kronos tokenizer:{TOKENIZER_PRETRAINED} model:{MODEL_PRETRAINED} ...")
161
+ tokenizer = KronosTokenizer.from_pretrained(TOKENIZER_PRETRAINED)
162
+ model = Kronos.from_pretrained(MODEL_PRETRAINED)
163
+ predictor = KronosPredictor(model, tokenizer, device=DEVICE, max_context=MAX_CONTEXT)
164
+
165
+ df = load_data(symbol)
166
+ x_df, x_timestamp, y_timestamp = prepare_inputs(df)
167
+
168
+ print("🔮 Generating predictions ...")
169
+
170
+ pred_df = predictor.predict(
171
+ df=x_df,
172
+ x_timestamp=x_timestamp,
173
+ y_timestamp=y_timestamp,
174
+ pred_len=PRED_LEN,
175
+ T=T,
176
+ top_p=TOP_P,
177
+ sample_count=SAMPLE_COUNT,
178
+ )
179
+
180
+ pred_df["date"] = y_timestamp.values
181
+
182
+ # Apply ±10% price limit
183
+ last_close = df["close"].iloc[-1]
184
+ pred_df = apply_price_limits(pred_df, last_close, limit_rate=0.1)
185
+
186
+ # Merge historical and predicted data
187
+ df_out = pd.concat([
188
+ df[["date", "open", "high", "low", "close", "volume", "amount"]],
189
+ pred_df[["date", "open", "high", "low", "close", "volume", "amount"]]
190
+ ]).reset_index(drop=True)
191
+
192
+ # Save CSV
193
+ out_file = os.path.join(save_dir, f"pred_{symbol.replace('.', '_')}_data.csv")
194
+ df_out.to_csv(out_file, index=False)
195
+ print(f"✅ Prediction completed and saved: {out_file}")
196
+
197
+ # Plot
198
+ plot_result(df, pred_df, symbol)
199
+
200
+
201
+ if __name__ == "__main__":
202
+ parser = argparse.ArgumentParser(description="Kronos stock prediction script")
203
+ parser.add_argument("--symbol", type=str, default="000001", help="Stock code")
204
+ args = parser.parse_args()
205
+
206
+ predict_future(
207
+ symbol=args.symbol,
208
+ )
Kronos/examples/prediction_example.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import matplotlib.pyplot as plt
3
+ import sys
4
+ sys.path.append("../")
5
+ from model import Kronos, KronosTokenizer, KronosPredictor
6
+
7
+
8
+ def plot_prediction(kline_df, pred_df):
9
+ pred_df.index = kline_df.index[-pred_df.shape[0]:]
10
+ sr_close = kline_df['close']
11
+ sr_pred_close = pred_df['close']
12
+ sr_close.name = 'Ground Truth'
13
+ sr_pred_close.name = "Prediction"
14
+
15
+ sr_volume = kline_df['volume']
16
+ sr_pred_volume = pred_df['volume']
17
+ sr_volume.name = 'Ground Truth'
18
+ sr_pred_volume.name = "Prediction"
19
+
20
+ close_df = pd.concat([sr_close, sr_pred_close], axis=1)
21
+ volume_df = pd.concat([sr_volume, sr_pred_volume], axis=1)
22
+
23
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6), sharex=True)
24
+
25
+ ax1.plot(close_df['Ground Truth'], label='Ground Truth', color='blue', linewidth=1.5)
26
+ ax1.plot(close_df['Prediction'], label='Prediction', color='red', linewidth=1.5)
27
+ ax1.set_ylabel('Close Price', fontsize=14)
28
+ ax1.legend(loc='lower left', fontsize=12)
29
+ ax1.grid(True)
30
+
31
+ ax2.plot(volume_df['Ground Truth'], label='Ground Truth', color='blue', linewidth=1.5)
32
+ ax2.plot(volume_df['Prediction'], label='Prediction', color='red', linewidth=1.5)
33
+ ax2.set_ylabel('Volume', fontsize=14)
34
+ ax2.legend(loc='upper left', fontsize=12)
35
+ ax2.grid(True)
36
+
37
+ plt.tight_layout()
38
+ plt.show()
39
+
40
+
41
+ # 1. Load Model and Tokenizer
42
+ tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base")
43
+ model = Kronos.from_pretrained("NeoQuasar/Kronos-small")
44
+
45
+ # 2. Instantiate Predictor
46
+ predictor = KronosPredictor(model, tokenizer, max_context=512)
47
+
48
+ # 3. Prepare Data
49
+ df = pd.read_csv("./data/XSHG_5min_600977.csv")
50
+ df['timestamps'] = pd.to_datetime(df['timestamps'])
51
+
52
+ lookback = 400
53
+ pred_len = 120
54
+
55
+ x_df = df.loc[:lookback-1, ['open', 'high', 'low', 'close', 'volume', 'amount']]
56
+ x_timestamp = df.loc[:lookback-1, 'timestamps']
57
+ y_timestamp = df.loc[lookback:lookback+pred_len-1, 'timestamps']
58
+
59
+ # 4. Make Prediction
60
+ pred_df = predictor.predict(
61
+ df=x_df,
62
+ x_timestamp=x_timestamp,
63
+ y_timestamp=y_timestamp,
64
+ pred_len=pred_len,
65
+ T=1.0,
66
+ top_p=0.9,
67
+ sample_count=1,
68
+ verbose=True
69
+ )
70
+
71
+ # 5. Visualize Results
72
+ print("Forecasted Data Head:")
73
+ print(pred_df.head())
74
+
75
+ # Combine historical and forecasted data for plotting
76
+ kline_df = df.loc[:lookback+pred_len-1]
77
+
78
+ # visualize
79
+ plot_prediction(kline_df, pred_df)
80
+
Kronos/examples/prediction_new.py ADDED
@@ -0,0 +1,1333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import matplotlib.pyplot as plt
3
+ import numpy as np
4
+ import sys
5
+ import os
6
+ from datetime import datetime, timedelta
7
+ import warnings
8
+ import requests
9
+ import json
10
+ import time
11
+ import random
12
+ import akshare as ak
13
+ from typing import Dict, List, Tuple, Optional
14
+
15
+ warnings.filterwarnings('ignore')
16
+
17
+ # 添加项目路径以便导入自定义模块
18
+ sys.path.append("../")
19
+ try:
20
+ from model import Kronos, KronosTokenizer, KronosPredictor
21
+ except ImportError:
22
+ print("⚠️ 无法导入Kronos模型,预测功能将不可用")
23
+
24
+ # 设置中文字体
25
+ plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
26
+ plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
27
+
28
+
29
+ # ==================== 基础数据获取函数 ====================
30
+ def ensure_output_directory(output_dir):
31
+ """确保输出目录存在,如果不存在则创建"""
32
+ if not os.path.exists(output_dir):
33
+ os.makedirs(output_dir)
34
+ print(f"✅ 创建输出目录: {output_dir}")
35
+ return output_dir
36
+
37
+
38
+ def fetch_real_stock_data(stock_code, period="daily", adjust="qfq"):
39
+ """
40
+ 使用AKShare获取真实股票数据
41
+ """
42
+ try:
43
+ print(f"📡 正在通过AKShare获取 {stock_code} 的真实股票数据...")
44
+
45
+ # 获取股票数据
46
+ df = ak.stock_zh_a_hist(symbol=stock_code, period=period, adjust=adjust)
47
+
48
+ if df is None or df.empty:
49
+ print(f"❌ 未获取到 {stock_code} 的数据")
50
+ return None
51
+
52
+ # 重命名列以统一格式
53
+ column_mapping = {
54
+ '日期': 'timestamps',
55
+ '开盘': 'open',
56
+ '收盘': 'close',
57
+ '最高': 'high',
58
+ '最低': 'low',
59
+ '成交量': 'volume',
60
+ '成交额': 'amount',
61
+ '振幅': 'amplitude',
62
+ '涨跌幅': 'pct_chg',
63
+ '涨跌额': 'change_amount',
64
+ '换手率': 'turnover'
65
+ }
66
+
67
+ # 只映射存在的列
68
+ actual_mapping = {k: v for k, v in column_mapping.items() if k in df.columns}
69
+ df = df.rename(columns=actual_mapping)
70
+
71
+ # 确保时间戳格式正确
72
+ df['timestamps'] = pd.to_datetime(df['timestamps'])
73
+ df = df.sort_values('timestamps').reset_index(drop=True)
74
+
75
+ # 添加股票代码列
76
+ df['stock_code'] = stock_code
77
+
78
+ print(f"✅ 成功获取 {len(df)} 条真实数据")
79
+ print(f"📈 最新收盘价: {df['close'].iloc[-1]:.2f}元, 涨跌幅: {df['pct_chg'].iloc[-1]:.2f}%")
80
+ print(f"📅 时间范围: {df['timestamps'].min()} 到 {df['timestamps'].max()}")
81
+
82
+ return df
83
+
84
+ except Exception as e:
85
+ print(f"❌ AKShare数据获取失败: {e}")
86
+ return None
87
+
88
+
89
+ def get_stock_data_with_retry_all_history(stock_code="600580", retry_count=2):
90
+ """
91
+ 优化的数据获取函数 - 优先使用真实API数据
92
+ """
93
+ print(f"🔄 尝试获取股票 {stock_code} 的真实历史数据...")
94
+
95
+ # 优先使用AKShare获取真实数据
96
+ df = fetch_real_stock_data(stock_code, "daily", "qfq")
97
+
98
+ if df is not None:
99
+ return df
100
+ else:
101
+ print("⚠️ 真实数据获取失败,使用基于真实价格的模拟数据...")
102
+ return create_realistic_fallback_data(stock_code)
103
+
104
+
105
+ def create_realistic_fallback_data(stock_code="600580"):
106
+ """
107
+ 基于真实价格的备用数据生成函数
108
+ """
109
+ # 基于真实市场价格的参考数据
110
+ real_stock_references = {
111
+ '600580': {'name': '卧龙电驱', 'current_price': 15.20, 'range': (12.0, 20.0)},
112
+ '300207': {'name': '欣旺达', 'current_price': 33.79, 'range': (28.0, 38.0)},
113
+ '300418': {'name': '昆仑万维', 'current_price': 48.59, 'range': (40.0, 55.0)},
114
+ '002354': {'name': '天娱数科', 'current_price': 15.20, 'range': (12.0, 20.0)},
115
+ '000001': {'name': '平安银行', 'current_price': 12.50, 'range': (10.0, 16.0)},
116
+ '600036': {'name': '招商银行', 'current_price': 35.80, 'range': (30.0, 42.0)},
117
+ }
118
+
119
+ stock_info = real_stock_references.get(stock_code, {
120
+ 'name': '未知股票',
121
+ 'current_price': 20.0,
122
+ 'range': (15.0, 25.0)
123
+ })
124
+
125
+ # 生成最近1年的交易日数据
126
+ end_date = datetime.now()
127
+ start_date = end_date - timedelta(days=365)
128
+ dates = pd.bdate_range(start=start_date, end=end_date, freq='B')
129
+
130
+ # 生成基于真实价格的价格序列
131
+ np.random.seed(42)
132
+ n_points = len(dates)
133
+
134
+ # 从当前价格反向生成历史价格
135
+ current_price = stock_info['current_price']
136
+ min_price, max_price = stock_info['range']
137
+
138
+ # 反向生成价格序列
139
+ prices = [current_price]
140
+ for i in range(1, n_points):
141
+ volatility = 0.02
142
+ historical_return = np.random.normal(-0.0002, volatility)
143
+
144
+ prev_price = prices[0] * (1 + historical_return)
145
+ prev_price = max(min_price * 0.9, min(max_price * 1.1, prev_price))
146
+ prices.insert(0, prev_price)
147
+
148
+ # 生成OHLC数据
149
+ stock_data = []
150
+ for i, date in enumerate(dates):
151
+ close_price = prices[i]
152
+
153
+ daily_volatility = abs(np.random.normal(0, 0.015))
154
+ open_price = close_price * (1 + np.random.normal(0, 0.005))
155
+ high_price = max(open_price, close_price) * (1 + daily_volatility)
156
+ low_price = min(open_price, close_price) * (1 - daily_volatility)
157
+
158
+ high_price = max(open_price, close_price, low_price, high_price)
159
+ low_price = min(open_price, close_price, high_price, low_price)
160
+
161
+ volume = int(abs(np.random.normal(1500000, 400000)))
162
+ amount = volume * close_price
163
+
164
+ if i > 0:
165
+ pct_chg = ((close_price - prices[i - 1]) / prices[i - 1]) * 100
166
+ change_amount = close_price - prices[i - 1]
167
+ else:
168
+ pct_chg = 0
169
+ change_amount = 0
170
+
171
+ stock_data.append({
172
+ 'timestamps': date,
173
+ 'stock_code': stock_code,
174
+ 'open': round(open_price, 2),
175
+ 'close': round(close_price, 2),
176
+ 'high': round(high_price, 2),
177
+ 'low': round(low_price, 2),
178
+ 'volume': volume,
179
+ 'amount': round(amount, 2),
180
+ 'amplitude': round(((high_price - low_price) / open_price) * 100, 2),
181
+ 'pct_chg': round(pct_chg, 2),
182
+ 'change_amount': round(change_amount, 2),
183
+ 'turnover': round(np.random.uniform(3.0, 8.0), 2)
184
+ })
185
+
186
+ df = pd.DataFrame(stock_data)
187
+ print(f"✅ 已生成基于真实价格的备用数据 {len(df)} 条")
188
+ return df
189
+
190
+
191
+ def save_all_history_stock_data(df, stock_code, save_dir):
192
+ """
193
+ 保存股票数据到指定目录
194
+ """
195
+ if df is not None and not df.empty:
196
+ os.makedirs(save_dir, exist_ok=True)
197
+ csv_file = os.path.join(save_dir, f"{stock_code}_stock_data.csv")
198
+ df_reset = df.reset_index()
199
+ df_reset.to_csv(csv_file, encoding='utf-8-sig', index=False)
200
+ print(f"📁 股票数据已保存: {csv_file}")
201
+ return True
202
+ return False
203
+
204
+
205
+ def get_stock_data(stock_code, data_dir):
206
+ """
207
+ 获取股票数据,如果数据文件不存在则从API获取真实数据
208
+ """
209
+ csv_file_path = os.path.join(data_dir, f"{stock_code}_stock_data.csv")
210
+
211
+ if os.path.exists(csv_file_path):
212
+ print(f"📁 使用现有数据文件: {csv_file_path}")
213
+ return True, csv_file_path
214
+ else:
215
+ print(f"📡 数据文件不存在,从API获取真实数据...")
216
+ df = get_stock_data_with_retry_all_history(stock_code)
217
+
218
+ if df is not None and not df.empty:
219
+ save_all_history_stock_data(df, stock_code, data_dir)
220
+ return True, csv_file_path
221
+ else:
222
+ print(f"❌ 无法获取股票数据")
223
+ return False, None
224
+
225
+
226
+ def prepare_stock_data(csv_file_path, stock_code, history_years=1):
227
+ """
228
+ 准备股票数据,转换为Kronos模型需要的格式
229
+ """
230
+ print(f"正在加载和预处理股票 {stock_code} 数据...")
231
+
232
+ # 读取CSV文件
233
+ df = pd.read_csv(csv_file_path, encoding='utf-8-sig')
234
+
235
+ # 标准化列名
236
+ column_mapping = {
237
+ '日期': 'timestamps',
238
+ '开盘价': 'open',
239
+ '最高价': 'high',
240
+ '最低价': 'low',
241
+ '收盘价': 'close',
242
+ '成交量': 'volume',
243
+ '成交额': 'amount',
244
+ '开盘': 'open',
245
+ '收盘': 'close',
246
+ '最高': 'high',
247
+ '最低': 'low'
248
+ }
249
+
250
+ actual_mapping = {k: v for k, v in column_mapping.items() if k in df.columns}
251
+ df = df.rename(columns=actual_mapping)
252
+
253
+ # 确保时间戳列存在并转换为datetime格式
254
+ if 'timestamps' not in df.columns:
255
+ if df.index.name == '日期':
256
+ df = df.reset_index()
257
+ df = df.rename(columns={'日期': 'timestamps'})
258
+
259
+ df['timestamps'] = pd.to_datetime(df['timestamps'])
260
+ df = df.sort_values('timestamps').reset_index(drop=True)
261
+
262
+ # 根据历史年限筛选数据
263
+ if history_years > 0:
264
+ cutoff_date = datetime.now() - timedelta(days=history_years * 365)
265
+ original_count = len(df)
266
+ df = df[df['timestamps'] >= cutoff_date]
267
+ print(f"📅 使用最近 {history_years} 年数据: {len(df)} 条记录 (从 {original_count} 条中筛选)")
268
+
269
+ # 数据验证
270
+ print(f"🔍 数据验证 - 最近5个交易日收盘价:")
271
+ recent_prices = df[['timestamps', 'close']].tail()
272
+ for _, row in recent_prices.iterrows():
273
+ print(f" {row['timestamps'].strftime('%Y-%m-%d')}: {row['close']:.2f}元")
274
+
275
+ current_price = df['close'].iloc[-1]
276
+ print(f"✅ 数据加载完成,共 {len(df)} 条记录")
277
+ print(f"时间范围: {df['timestamps'].min()} 到 {df['timestamps'].max()}")
278
+ print(f"价格范围: {df['close'].min():.2f} - {df['close'].max():.2f}")
279
+ print(f"当前价格: {current_price:.2f}元")
280
+
281
+ return df
282
+
283
+
284
+ def calculate_prediction_parameters(df, target_days=60):
285
+ """
286
+ 根据目标预测天数计算合适的���数
287
+ """
288
+ # 计算平均交易日数量
289
+ total_days = (df['timestamps'].max() - df['timestamps'].min()).days
290
+ trading_days = len(df)
291
+ trading_ratio = trading_days / total_days if total_days > 0 else 0.7
292
+
293
+ # 计算目标预测的交易日数量
294
+ pred_trading_days = int(target_days * trading_ratio)
295
+
296
+ # 设置回看期数
297
+ max_lookback = int(len(df) * 0.7)
298
+ lookback = min(pred_trading_days * 3, max_lookback, len(df) - pred_trading_days)
299
+ pred_len = min(pred_trading_days, len(df) - lookback)
300
+
301
+ # 确保参数在合理范围内
302
+ lookback = max(100, min(lookback, 400))
303
+ pred_len = max(20, min(pred_len, 120))
304
+
305
+ print(f"📊 参数计算:")
306
+ print(f" 目标预测天数: {target_days} 天(自然日)")
307
+ print(f" 预计交易日数量: {pred_trading_days} 天")
308
+ print(f" 回看期数 (lookback): {lookback}")
309
+ print(f" 预测期数 (pred_len): {pred_len}")
310
+
311
+ return lookback, pred_len
312
+
313
+
314
+ def generate_future_dates(last_date, pred_len):
315
+ """
316
+ 生成未来的交易日日期
317
+ """
318
+ future_dates = []
319
+ current_date = last_date + timedelta(days=1)
320
+
321
+ while len(future_dates) < pred_len:
322
+ if current_date.weekday() < 5:
323
+ future_dates.append(current_date)
324
+ current_date += timedelta(days=1)
325
+
326
+ print(f"📅 生成的未来交易日: 共 {len(future_dates)} 天")
327
+ print(f" 起始日期: {future_dates[0].strftime('%Y-%m-%d')}")
328
+ print(f" 结束日期: {future_dates[-1].strftime('%Y-%m-%d')}")
329
+
330
+ return future_dates[:pred_len]
331
+
332
+
333
+ def calculate_optimal_interval(min_val, max_val):
334
+ """
335
+ 计算最优的Y轴刻度间隔
336
+ """
337
+ range_val = max_val - min_val
338
+ if range_val <= 0:
339
+ return 1.0
340
+
341
+ if range_val < 1:
342
+ interval = 0.1
343
+ elif range_val < 5:
344
+ interval = 0.5
345
+ elif range_val < 10:
346
+ interval = 1.0
347
+ elif range_val < 20:
348
+ interval = 2.0
349
+ elif range_val < 50:
350
+ interval = 5.0
351
+ elif range_val < 100:
352
+ interval = 10.0
353
+ elif range_val < 200:
354
+ interval = 20.0
355
+ elif range_val < 500:
356
+ interval = 50.0
357
+ else:
358
+ interval = 100.0
359
+
360
+ return interval
361
+
362
+
363
+ def get_stock_price_reference(stock_code, current_price):
364
+ """
365
+ 根据当前价格智能计算参考价格范围
366
+ """
367
+ price_ranges = {
368
+ '600580': (current_price * 0.75, current_price * 1.25),
369
+ '300207': (current_price * 0.75, current_price * 1.25),
370
+ '300418': (current_price * 0.75, current_price * 1.25),
371
+ '002354': (current_price * 0.75, current_price * 1.25),
372
+ '000001': (current_price * 0.75, current_price * 1.25),
373
+ '600036': (current_price * 0.75, current_price * 1.25),
374
+ }
375
+
376
+ if stock_code in price_ranges:
377
+ min_price, max_price = price_ranges[stock_code]
378
+ min_price = max(1.0, min_price)
379
+ return {'min': min_price, 'max': max_price}
380
+ else:
381
+ return {'min': max(1.0, current_price * 0.7), 'max': current_price * 1.3}
382
+
383
+
384
+ # ==================== 增强版市场因素分析器 ====================
385
+ class EnhancedMarketFactorAnalyzer:
386
+ """增强版市场因素分析器 - 整合更多维度的市场因素"""
387
+
388
+ def __init__(self):
389
+ self.market_data = {}
390
+ self.sector_data = {}
391
+ self.macro_factors = {}
392
+ self.policy_factors = {}
393
+
394
+ def analyze_market_trend(self, index_codes=["000001", "399001"]):
395
+ """
396
+ 分析大盘趋势 - 多指数综合分析
397
+ """
398
+ try:
399
+ print(f"📊 综合分析大盘趋势...")
400
+
401
+ market_analysis = {}
402
+
403
+ for index_code in index_codes:
404
+ index_name = "上证指数" if index_code == "000001" else "深证成指"
405
+ print(f" 分析{index_name}({index_code})...")
406
+
407
+ # 获取指数数据
408
+ index_df = ak.stock_zh_index_hist(symbol=index_code, period="daily")
409
+
410
+ if index_df is None or index_df.empty:
411
+ print(f" ❌ 无法获取{index_name}数据")
412
+ continue
413
+
414
+ # 重命名列
415
+ index_df = index_df.rename(columns={
416
+ '日期': 'date', '收盘': 'close', '开盘': 'open',
417
+ '最高': 'high', '最低': 'low', '成交量': 'volume'
418
+ })
419
+ index_df['date'] = pd.to_datetime(index_df['date'])
420
+ index_df = index_df.sort_values('date').reset_index(drop=True)
421
+
422
+ # 计算技术指标
423
+ index_df['ma5'] = index_df['close'].rolling(5).mean()
424
+ index_df['ma20'] = index_df['close'].rolling(20).mean()
425
+ index_df['ma60'] = index_df['close'].rolling(60).mean()
426
+ index_df['vol_ma5'] = index_df['volume'].rolling(5).mean()
427
+
428
+ # 技术分析
429
+ current_data = index_df.iloc[-1]
430
+ prev_data = index_df.iloc[-2]
431
+
432
+ # 均线多头排列判断
433
+ ma_condition = (current_data['ma5'] > current_data['ma20'] > current_data['ma60'])
434
+
435
+ # 价格站在20日均线以上
436
+ price_above_ma20 = current_data['close'] > current_data['ma20']
437
+
438
+ # 成交量配合
439
+ volume_condition = current_data['volume'] > current_data['vol_ma5'] * 0.8
440
+
441
+ # 趋势强度
442
+ trend_strength = self._calculate_trend_strength(index_df)
443
+
444
+ is_main_uptrend = ma_condition and price_above_ma20 and trend_strength > 0.6
445
+
446
+ market_analysis[index_name] = {
447
+ 'is_main_uptrend': is_main_uptrend,
448
+ 'trend_strength': trend_strength,
449
+ 'current_close': current_data['close'],
450
+ 'price_change_pct': ((current_data['close'] - prev_data['close']) / prev_data['close']) * 100,
451
+ 'market_status': '主升浪' if is_main_uptrend else '震荡调整'
452
+ }
453
+
454
+ # 综合判断
455
+ if market_analysis:
456
+ avg_trend_strength = np.mean([data['trend_strength'] for data in market_analysis.values()])
457
+ uptrend_count = sum(1 for data in market_analysis.values() if data['is_main_uptrend'])
458
+ overall_uptrend = uptrend_count >= len(market_analysis) * 0.5
459
+
460
+ final_analysis = {
461
+ 'overall_is_main_uptrend': overall_uptrend,
462
+ 'overall_trend_strength': avg_trend_strength,
463
+ 'detailed_analysis': market_analysis,
464
+ 'market_status': '主升浪' if overall_uptrend else '震荡调整'
465
+ }
466
+
467
+ print(f"✅ 大盘分析完成: {final_analysis['market_status']}, 综合趋势强度: {avg_trend_strength:.2f}")
468
+ return final_analysis
469
+
470
+ return self._get_default_market_analysis()
471
+
472
+ except Exception as e:
473
+ print(f"❌ 大盘分析错误: {e}")
474
+ return self._get_default_market_analysis()
475
+
476
+ def analyze_sector_resonance(self, stock_code):
477
+ """
478
+ 分析板块共振效应 - 增强版行业分析
479
+ """
480
+ try:
481
+ print(f"🔄 分析板块共振效应...")
482
+
483
+ # 获取股票所属行业和概念
484
+ industry = "未知"
485
+ concepts = []
486
+
487
+ try:
488
+ stock_info = ak.stock_individual_info_em(symbol=stock_code)
489
+ if not stock_info.empty and 'value' in stock_info.columns:
490
+ industry_row = stock_info[stock_info['item'] == '行业']
491
+ if not industry_row.empty:
492
+ industry = industry_row['value'].iloc[0]
493
+ except:
494
+ pass
495
+
496
+ # 热门板块和概念映射
497
+ hot_sectors = {
498
+ '机器人': {'momentum': 0.85, 'limit_up_stocks': 18, 'active': True,
499
+ 'description': '人形机器人、工业自动化'},
500
+ '半导体': {'momentum': 0.8, 'limit_up_stocks': 15, 'active': True, 'description': '芯片国产替代'},
501
+ '人工智能': {'momentum': 0.75, 'limit_up_stocks': 12, 'active': True, 'description': 'AI大模型、算力'},
502
+ '低空经济': {'momentum': 0.7, 'limit_up_stocks': 10, 'active': True, 'description': '无人机、eVTOL'},
503
+ '新能源': {'momentum': 0.6, 'limit_up_stocks': 8, 'active': True, 'description': '光伏、储能'},
504
+ '医药': {'momentum': 0.5, 'limit_up_stocks': 5, 'active': False, 'description': '创新药'}
505
+ }
506
+
507
+ # 判断当前股票所属热门板块
508
+ matched_sectors = []
509
+ for sector, data in hot_sectors.items():
510
+ if (sector in industry or
511
+ (stock_code == '600580' and sector in ['机器人', '低空经济']) or # 卧龙电驱特殊处理
512
+ (stock_code == '300207' and sector in ['新能源'])):
513
+ matched_sectors.append({
514
+ 'sector': sector,
515
+ 'momentum': data['momentum'],
516
+ 'limit_up_stocks': data['limit_up_stocks'],
517
+ 'is_active': data['active'],
518
+ 'description': data['description']
519
+ })
520
+
521
+ # 计算综合共振分数
522
+ if matched_sectors:
523
+ resonance_score = np.mean([sector['momentum'] for sector in matched_sectors])
524
+ is_sector_hot = any(sector['is_active'] for sector in matched_sectors)
525
+ main_sector = max(matched_sectors, key=lambda x: x['momentum'])
526
+ else:
527
+ resonance_score = 0.5
528
+ is_sector_hot = False
529
+ main_sector = {'sector': '传统行业', 'momentum': 0.5, 'description': '无热门概念'}
530
+
531
+ analysis = {
532
+ 'industry': industry,
533
+ 'matched_sectors': matched_sectors,
534
+ 'main_sector': main_sector,
535
+ 'is_sector_hot': is_sector_hot,
536
+ 'resonance_score': resonance_score,
537
+ 'sector_count': len(matched_sectors)
538
+ }
539
+
540
+ print(f"✅ 板块分析完成: {industry}, 匹配{len(matched_sectors)}个热门板块, 共振分数: {resonance_score:.2f}")
541
+ return analysis
542
+
543
+ except Exception as e:
544
+ print(f"❌ 板块分析错误: {e}")
545
+ return self._get_default_sector_analysis()
546
+
547
+ def analyze_macro_factors(self):
548
+ """
549
+ 分析宏观因素 - 结合国内外政策
550
+ """
551
+ try:
552
+ print(f"🌍 分析宏观因素...")
553
+
554
+ # 美国降息周期分析 - 基于最新信息
555
+ us_rate_analysis = {
556
+ 'current_rate': 4.25, # 联邦基金利率目标区间4.00%-4.25%:cite[3]
557
+ 'trend': '降息周期',
558
+ 'recent_cut': '2025年9月降息25个基点',
559
+ 'expected_cuts_2025': 2, # 市场预期2025年还有两次降息:cite[7]
560
+ 'expected_cuts_2026': 2,
561
+ 'impact_on_emerging_markets': 'positive',
562
+ 'usd_index_support': 95.0, # 美元指数短期支撑位:cite[7]
563
+ 'analysis': '美联储开启宽松周期,利好全球流动性'
564
+ }
565
+
566
+ # 国内政策因素 - 基于最新政策
567
+ domestic_policy = {
568
+ 'monetary_policy': '稳健偏松',
569
+ 'fiscal_policy': '积极财政',
570
+ 'market_liquidity': '合理充裕',
571
+ 'industrial_policy': '设备更新、以旧换新', # 大规模设备更新政策:cite[5]
572
+ 'employment_policy': '稳就业政策加力', # 国务院稳就业政策:cite[8]
573
+ 'analysis': '政策组合拳发力,经济稳中向好'
574
+ }
575
+
576
+ # 行业政策支持
577
+ industry_policy = {
578
+ 'robot_policy': '机器人产业政策支持',
579
+ 'chip_policy': '国产替代加速推进',
580
+ 'AI_policy': '人工智能发展规划',
581
+ 'low_altitude': '低空经济发展规划'
582
+ }
583
+
584
+ macro_analysis = {
585
+ 'us_rate_cycle': us_rate_analysis,
586
+ 'domestic_policy': domestic_policy,
587
+ 'industry_policy': industry_policy,
588
+ 'global_liquidity_outlook': '改善',
589
+ 'overall_macro_score': 0.75 # 宏观环境整体偏积极
590
+ }
591
+
592
+ print(
593
+ f"✅ 宏观分析完成: 美国{us_rate_analysis['trend']}, 国内政策积极, 宏观评分: {macro_analysis['overall_macro_score']:.2f}")
594
+ return macro_analysis
595
+
596
+ except Exception as e:
597
+ print(f"❌ 宏观分析错误: {e}")
598
+ return self._get_default_macro_analysis()
599
+
600
+ def analyze_company_fundamentals(self, stock_code):
601
+ """
602
+ 分析公司基本面 - 针对特定股票
603
+ """
604
+ try:
605
+ print(f"🏢 分析公司基本面...")
606
+
607
+ # 卧龙电驱特殊分析
608
+ if stock_code == '600580':
609
+ fundamentals = {
610
+ 'company_name': '卧龙电驱',
611
+ 'business_areas': ['工业电机', '机器人关键部件', '航空电机', '新能源汽车驱动'],
612
+ 'recent_developments': [
613
+ '与智元机器人实现双向持股,推进具身智能机器人技术研发:cite[5]',
614
+ '成立浙江龙飞电驱,专注航空电机业务:cite[5]',
615
+ '发布AI外骨骼机器人及灵巧手:cite[9]',
616
+ '布局高爆发关节模组、伺服驱动器等人形机器人关键部件:cite[5]'
617
+ ],
618
+ 'growth_drivers': [
619
+ '设备更新政策推动工业电机需求:cite[5]',
620
+ '机器人产业快速发展',
621
+ '低空经济政策支持',
622
+ '出海战略加速'
623
+ ],
624
+ 'risk_factors': [
625
+ '机器人业务营收占比仅2.71%,占比较低:cite[1]',
626
+ '工业需求景气度波动',
627
+ '原料价格波动风险'
628
+ ],
629
+ 'investment_rating': '积极关注',
630
+ 'fundamental_score': 0.7
631
+ }
632
+ else:
633
+ # 其他股票的基础分析
634
+ fundamentals = {
635
+ 'company_name': '未知',
636
+ 'business_areas': [],
637
+ 'recent_developments': [],
638
+ 'growth_drivers': [],
639
+ 'risk_factors': [],
640
+ 'investment_rating': '中性',
641
+ 'fundamental_score': 0.5
642
+ }
643
+
644
+ print(f"✅ 基本面分析完成: {fundamentals['company_name']}, 评分: {fundamentals['fundamental_score']:.2f}")
645
+ return fundamentals
646
+
647
+ except Exception as e:
648
+ print(f"❌ 基本面分析错误: {e}")
649
+ return self._get_default_fundamental_analysis()
650
+
651
+ def _calculate_trend_strength(self, df):
652
+ """计算趋势强度"""
653
+ if len(df) < 20:
654
+ return 0.5
655
+
656
+ ma_slope = (df['ma5'].iloc[-1] - df['ma5'].iloc[-20]) / df['ma5'].iloc[-20]
657
+ price_slope = (df['close'].iloc[-1] - df['close'].iloc[-20]) / df['close'].iloc[-20]
658
+
659
+ volume_trend = df['volume'].iloc[-5:].mean() / df['volume'].iloc[-10:-5].mean()
660
+
661
+ strength = (ma_slope * 0.4 + price_slope * 0.4 + min(volume_trend - 1, 0.2) * 0.2)
662
+ return max(0, min(1, strength * 10))
663
+
664
+ def _get_default_market_analysis(self):
665
+ return {
666
+ 'overall_is_main_uptrend': False,
667
+ 'overall_trend_strength': 0.5,
668
+ 'market_status': '未知',
669
+ 'detailed_analysis': {}
670
+ }
671
+
672
+ def _get_default_sector_analysis(self):
673
+ return {
674
+ 'industry': '未知',
675
+ 'matched_sectors': [],
676
+ 'main_sector': {'sector': '未知', 'momentum': 0.5, 'description': ''},
677
+ 'is_sector_hot': False,
678
+ 'resonance_score': 0.5,
679
+ 'sector_count': 0
680
+ }
681
+
682
+ def _get_default_macro_analysis(self):
683
+ return {
684
+ 'us_rate_cycle': {'trend': '未知', 'expected_cuts_2025': 0},
685
+ 'domestic_policy': {'monetary_policy': '中性'},
686
+ 'overall_macro_score': 0.5
687
+ }
688
+
689
+ def _get_default_fundamental_analysis(self):
690
+ return {
691
+ 'company_name': '未知',
692
+ 'business_areas': [],
693
+ 'recent_developments': [],
694
+ 'growth_drivers': [],
695
+ 'risk_factors': [],
696
+ 'investment_rating': '中性',
697
+ 'fundamental_score': 0.5
698
+ }
699
+
700
+
701
+ # ==================== 增强预测函数 ====================
702
+ def enhance_prediction_with_market_factors(
703
+ historical_df,
704
+ prediction_df,
705
+ stock_code,
706
+ market_analyzer
707
+ ):
708
+ """
709
+ 使用市场因素增强预测结果 - 多维度综合分析
710
+ """
711
+ print("\n🎯 使用多维度市场因素增强预测...")
712
+
713
+ # 获取各类市场分析
714
+ market_analysis = market_analyzer.analyze_market_trend()
715
+ sector_analysis = market_analyzer.analyze_sector_resonance(stock_code)
716
+ macro_analysis = market_analyzer.analyze_macro_factors()
717
+ fundamental_analysis = market_analyzer.analyze_company_fundamentals(stock_code)
718
+
719
+ # 计算综合调整因子
720
+ adjustment_factor = calculate_enhanced_adjustment_factor(
721
+ market_analysis, sector_analysis, macro_analysis, fundamental_analysis
722
+ )
723
+
724
+ print(f"📈 综合调整因子: {adjustment_factor:.4f}")
725
+
726
+ # 应用调整到预测结果
727
+ enhanced_prediction = prediction_df.copy()
728
+
729
+ # 对价格预测进行调整
730
+ price_columns = ['close', 'open', 'high', 'low']
731
+ for col in price_columns:
732
+ if col in enhanced_prediction.columns:
733
+ # 使用更温和的调整,避免过度乐观或悲观
734
+ adjusted_value = enhanced_prediction[col] * adjustment_factor
735
+ # 限制单次调整幅度在±10%以内
736
+ change_ratio = adjusted_value / enhanced_prediction[col]
737
+ if change_ratio.max() > 1.1:
738
+ adjusted_value = enhanced_prediction[col] * 1.1
739
+ elif change_ratio.min() < 0.9:
740
+ adjusted_value = enhanced_prediction[col] * 0.9
741
+ enhanced_prediction[col] = adjusted_value
742
+
743
+ # 对成交量进行调整
744
+ if 'volume' in enhanced_prediction.columns:
745
+ volume_adjustment = 1 + (adjustment_factor - 1) * 0.3 # 成交量调整更温和
746
+ enhanced_prediction['volume'] = enhanced_prediction['volume'] * volume_adjustment
747
+
748
+ return enhanced_prediction, {
749
+ 'market_analysis': market_analysis,
750
+ 'sector_analysis': sector_analysis,
751
+ 'macro_analysis': macro_analysis,
752
+ 'fundamental_analysis': fundamental_analysis,
753
+ 'adjustment_factor': adjustment_factor
754
+ }
755
+
756
+
757
+ def calculate_enhanced_adjustment_factor(market_analysis, sector_analysis, macro_analysis, fundamental_analysis):
758
+ """
759
+ 计算基于多维度市场因素的调整因子 - 更平衡的方法
760
+ """
761
+ base_factor = 1.0
762
+ factors_log = []
763
+
764
+ # 1. 大盘趋势影响 (权重25%)
765
+ if market_analysis['overall_is_main_uptrend']:
766
+ trend_strength = market_analysis['overall_trend_strength']
767
+ adjustment = 1 + trend_strength * 0.08 # 降低主升浪影响幅度
768
+ base_factor *= adjustment
769
+ factors_log.append(f"大盘主升浪: +{trend_strength * 0.08:.3f}")
770
+ else:
771
+ trend_strength = market_analysis['overall_trend_strength']
772
+ # 震荡市不一定悲观,只是增幅较小
773
+ adjustment = 1 + (trend_strength - 0.5) * 0.04
774
+ base_factor *= adjustment
775
+ factors_log.append(f"大盘震荡: {(trend_strength - 0.5) * 0.04:+.3f}")
776
+
777
+ # 2. 板块共振影响 (权重25%)
778
+ resonance_score = sector_analysis['resonance_score']
779
+ sector_count = sector_analysis['sector_count']
780
+
781
+ if sector_analysis['is_sector_hot']:
782
+ # 热门板块且有多个概念叠加
783
+ sector_adjustment = 1 + resonance_score * 0.06 + min(sector_count * 0.01, 0.03)
784
+ base_factor *= sector_adjustment
785
+ factors_log.append(
786
+ f"热门板块({sector_count}个): +{resonance_score * 0.06 + min(sector_count * 0.01, 0.03):.3f}")
787
+ else:
788
+ # 非热门板块也有基础支撑
789
+ base_factor *= (1 + (resonance_score - 0.5) * 0.02)
790
+ factors_log.append(f"一般板块: {(resonance_score - 0.5) * 0.02:+.3f}")
791
+
792
+ # 3. 宏观因素影响 (权重20%)
793
+ macro_score = macro_analysis['overall_macro_score']
794
+ macro_adjustment = 1 + (macro_score - 0.5) * 0.06
795
+ base_factor *= macro_adjustment
796
+ factors_log.append(f"宏观环境: {(macro_score - 0.5) * 0.06:+.3f}")
797
+
798
+ # 4. 美国降息周期特殊影响 (权重10%)
799
+ us_rate_trend = macro_analysis['us_rate_cycle']['trend']
800
+ if us_rate_trend == '降息周期':
801
+ expected_cuts = macro_analysis['us_rate_cycle']['expected_cuts_2025']
802
+ us_adjustment = 1 + expected_cuts * 0.015 # 降低单次降息影响
803
+ base_factor *= us_adjustment
804
+ factors_log.append(f"美国降息: +{expected_cuts * 0.015:.3f}")
805
+
806
+ # 5. 公司基本面影响 (权重20%)
807
+ fundamental_score = fundamental_analysis['fundamental_score']
808
+ fundamental_adjustment = 1 + (fundamental_score - 0.5) * 0.08
809
+ base_factor *= fundamental_adjustment
810
+ factors_log.append(f"基本面: {(fundamental_score - 0.5) * 0.08:+.3f}")
811
+
812
+ # 输出调整因子详情
813
+ print("🔍 调整因子详情:")
814
+ for log in factors_log:
815
+ print(f" {log}")
816
+
817
+ # 限制调整幅度在更合理的范围内 (0.85 ~ 1.15)
818
+ final_factor = max(0.85, min(1.15, base_factor))
819
+
820
+ if final_factor != base_factor:
821
+ print(f"⚠️ 调整因子从 {base_factor:.3f} 限制到 {final_factor:.3f}")
822
+
823
+ return final_factor
824
+
825
+
826
+ def create_comprehensive_market_report(enhancement_info, output_dir, stock_code):
827
+ """
828
+ 创建综合市场分析报告
829
+ """
830
+ report = {
831
+ 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
832
+ 'stock_code': stock_code,
833
+ 'market_analysis': enhancement_info['market_analysis'],
834
+ 'sector_analysis': enhancement_info['sector_analysis'],
835
+ 'macro_analysis': enhancement_info['macro_analysis'],
836
+ 'fundamental_analysis': enhancement_info['fundamental_analysis'],
837
+ 'adjustment_factor': enhancement_info['adjustment_factor'],
838
+ 'analysis_summary': generate_analysis_summary(enhancement_info)
839
+ }
840
+
841
+ # 保存报告
842
+ report_file = os.path.join(output_dir, f'{stock_code}_comprehensive_analysis_report.json')
843
+ with open(report_file, 'w', encoding='utf-8') as f:
844
+ json.dump(report, f, ensure_ascii=False, indent=2)
845
+
846
+ print(f"📋 综合分析报告已保存: {report_file}")
847
+ return report
848
+
849
+
850
+ def generate_analysis_summary(enhancement_info):
851
+ """
852
+ 生成分析总结
853
+ """
854
+ market = enhancement_info['market_analysis']
855
+ sector = enhancement_info['sector_analysis']
856
+ macro = enhancement_info['macro_analysis']
857
+ fundamental = enhancement_info['fundamental_analysis']
858
+
859
+ summary = {
860
+ 'overall_sentiment': '积极' if enhancement_info['adjustment_factor'] > 1.0 else '谨慎',
861
+ 'key_drivers': [],
862
+ 'main_risks': [],
863
+ 'investment_suggestion': ''
864
+ }
865
+
866
+ # 关键驱动因素
867
+ if market['overall_trend_strength'] > 0.6:
868
+ summary['key_drivers'].append('大盘趋势向好')
869
+
870
+ if sector['is_sector_hot']:
871
+ summary['key_drivers'].append(f"热门板块:{sector['main_sector']['sector']}")
872
+
873
+ if macro['overall_macro_score'] > 0.7:
874
+ summary['key_drivers'].append('宏观环境有利')
875
+
876
+ if fundamental['fundamental_score'] > 0.6:
877
+ summary['key_drivers'].append('基本面稳健')
878
+
879
+ # 主要风险
880
+ if market['overall_trend_strength'] < 0.4:
881
+ summary['main_risks'].append('大盘趋势偏弱')
882
+
883
+ if not sector['is_sector_hot']:
884
+ summary['main_risks'].append('非热门板块')
885
+
886
+ if len(summary['key_drivers']) > len(summary['main_risks']):
887
+ summary['investment_suggestion'] = '可考虑逢低关注'
888
+ else:
889
+ summary['investment_suggestion'] = '建议谨慎操作'
890
+
891
+ return summary
892
+
893
+
894
+ # ==================== 增强可视化函数 ====================
895
+ def plot_comprehensive_prediction(
896
+ historical_df,
897
+ prediction_df,
898
+ future_dates,
899
+ stock_code,
900
+ stock_name,
901
+ output_dir,
902
+ enhancement_info=None
903
+ ):
904
+ """
905
+ 绘制综合预测图表 - 包含更多市场分析信息
906
+ """
907
+ ensure_output_directory(output_dir)
908
+
909
+ # 设置配色
910
+ colors = {
911
+ 'historical': '#1f77b4',
912
+ 'prediction': '#ff7f0e',
913
+ 'enhanced': '#2ca02c',
914
+ 'background': '#f8f9fa',
915
+ 'grid': '#e9ecef',
916
+ 'positive': '#2ecc71',
917
+ 'negative': '#e74c3c',
918
+ 'neutral': '#95a5a6'
919
+ }
920
+
921
+ # 创建综合图表
922
+ fig = plt.figure(figsize=(18, 14))
923
+ gs = plt.GridSpec(4, 3, figure=fig, height_ratios=[2, 1, 1, 1])
924
+
925
+ # 1. 主价格图表
926
+ ax1 = fig.add_subplot(gs[0, :])
927
+ ax1.set_facecolor(colors['background'])
928
+
929
+ # 2. 成交量图表
930
+ ax2 = fig.add_subplot(gs[1, :])
931
+ ax2.set_facecolor(colors['background'])
932
+
933
+ # 3. 市场分析图表
934
+ ax3 = fig.add_subplot(gs[2, 0])
935
+ ax3.set_facecolor(colors['background'])
936
+
937
+ ax4 = fig.add_subplot(gs[2, 1])
938
+ ax4.set_facecolor(colors['background'])
939
+
940
+ ax5 = fig.add_subplot(gs[2, 2])
941
+ ax5.set_facecolor(colors['background'])
942
+
943
+ # 4. 因素分析图表
944
+ ax6 = fig.add_subplot(gs[3, :])
945
+ ax6.set_facecolor(colors['background'])
946
+
947
+ # 设置背景色
948
+ fig.patch.set_facecolor('white')
949
+
950
+ # 1. 价格图表
951
+ historical_prices = historical_df.set_index('timestamps')['close']
952
+ prediction_prices = prediction_df.set_index(pd.DatetimeIndex(future_dates))['close']
953
+
954
+ # 获取当前最新价格
955
+ current_price = historical_prices.iloc[-1]
956
+
957
+ # 智能Y轴范围计算
958
+ all_prices = pd.concat([historical_prices, prediction_prices])
959
+ data_min = all_prices.min()
960
+ data_max = all_prices.max()
961
+
962
+ price_range = data_max - data_min
963
+ y_margin = price_range * 0.15
964
+
965
+ y_min = max(0, data_min - y_margin)
966
+ y_max = data_max + y_margin
967
+
968
+ # 设置Y轴刻度
969
+ y_interval = calculate_optimal_interval(y_min, y_max)
970
+ y_ticks = np.arange(round(y_min / y_interval) * y_interval,
971
+ round(y_max / y_interval) * y_interval + y_interval,
972
+ y_interval)
973
+
974
+ # 绘制历史价格
975
+ ax1.plot(historical_prices.index, historical_prices.values,
976
+ color=colors['historical'], linewidth=2, label='历史价格')
977
+
978
+ # 绘制预测价格
979
+ if len(prediction_prices) > 0:
980
+ # 连接点
981
+ last_hist_date = historical_prices.index[-1]
982
+ last_hist_price = historical_prices.iloc[-1]
983
+ first_pred_date = prediction_prices.index[0]
984
+
985
+ # 绘制连接线
986
+ ax1.plot([last_hist_date, first_pred_date],
987
+ [last_hist_price, prediction_prices.iloc[0]],
988
+ color=colors['prediction'], linewidth=2.5, linestyle='-')
989
+
990
+ # 绘制预测线
991
+ ax1.plot(prediction_prices.index, prediction_prices.values,
992
+ color=colors['prediction'], linewidth=2.5, label='基础预测')
993
+
994
+ # 绘制增强预测线
995
+ if enhancement_info and 'enhanced_prediction' in enhancement_info:
996
+ enhanced_prices = enhancement_info['enhanced_prediction'].set_index(pd.DatetimeIndex(future_dates))['close']
997
+ ax1.plot(enhanced_prices.index, enhanced_prices.values,
998
+ color=colors['enhanced'], linewidth=2.5, linestyle='--', label='增强预测')
999
+
1000
+ # 标记预测起点
1001
+ ax1.axvline(x=last_hist_date, color='red', linestyle='--', alpha=0.7, linewidth=1)
1002
+ ax1.annotate('预测起点', xy=(last_hist_date, last_hist_price),
1003
+ xytext=(10, 10), textcoords='offset points',
1004
+ fontsize=10, fontweight='bold',
1005
+ bbox=dict(boxstyle='round,pad=0.3', facecolor='white', alpha=0.8))
1006
+
1007
+ # 设置Y轴范围和刻度
1008
+ ax1.set_ylim(y_min, y_max)
1009
+ ax1.set_yticks(y_ticks)
1010
+
1011
+ ax1.set_ylabel('收盘价 (元)', fontsize=12, fontweight='bold')
1012
+ ax1.legend(loc='upper left', fontsize=11)
1013
+ ax1.grid(True, color=colors['grid'], alpha=0.7)
1014
+
1015
+ title = f'{stock_name}({stock_code}) - 综合因素价格预测\n当前价: {current_price:.2f}元 | 增强因子: {enhancement_info["adjustment_factor"]:.3f}' if enhancement_info else f'{stock_name}({stock_code}) - 价格预测\n当前价: {current_price:.2f}元'
1016
+ ax1.set_title(title, fontsize=14, fontweight='bold', pad=20)
1017
+
1018
+ # 设置x轴格式
1019
+ ax1.xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter('%Y-%m-%d'))
1020
+ plt.setp(ax1.xaxis.get_majorticklabels(), rotation=45)
1021
+
1022
+ # 2. 成交量图表
1023
+ historical_volume = historical_df.set_index('timestamps')['volume']
1024
+ prediction_volume = prediction_df.set_index(pd.DatetimeIndex(future_dates))['volume']
1025
+
1026
+ # 计算相对成交量(标准化)
1027
+ hist_volume_norm = historical_volume / historical_volume.max()
1028
+ if len(prediction_volume) > 0:
1029
+ pred_volume_norm = prediction_volume / historical_volume.max()
1030
+
1031
+ # 绘制历史成交量
1032
+ ax2.bar(historical_volume.index, hist_volume_norm.values,
1033
+ alpha=0.6, color=colors['historical'], label='历史成交量')
1034
+
1035
+ # 绘制预测成交量
1036
+ if len(prediction_volume) > 0:
1037
+ ax2.bar(prediction_volume.index, pred_volume_norm.values,
1038
+ alpha=0.6, color=colors['prediction'], label='预测成交量')
1039
+
1040
+ ax2.set_ylabel('相对成交量', fontsize=12, fontweight='bold')
1041
+ ax2.legend(loc='upper left', fontsize=11)
1042
+ ax2.grid(True, color=colors['grid'], alpha=0.7)
1043
+ ax2.set_ylim(0, 1.2)
1044
+
1045
+ # 设置x轴格式
1046
+ ax2.xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter('%Y-%m-%d'))
1047
+ plt.setp(ax2.xaxis.get_majorticklabels(), rotation=45)
1048
+
1049
+ # 3. 市场分析子图
1050
+ if enhancement_info:
1051
+ # 因素权重饼图
1052
+ factors = ['大盘趋势', '板块共振', '宏观环境', '美国降息', '基本面']
1053
+ weights = [25, 25, 20, 10, 20]
1054
+ colors_pie = [colors['historical'], colors['prediction'], colors['enhanced'], '#f39c12', '#9b59b6']
1055
+
1056
+ ax3.pie(weights, labels=factors, autopct='%1.0f%%', colors=colors_pie, startangle=90)
1057
+ ax3.set_title('因素权重分配', fontweight='bold', fontsize=11)
1058
+
1059
+ # 因素评分柱状图
1060
+ scores = [
1061
+ enhancement_info['market_analysis']['overall_trend_strength'],
1062
+ enhancement_info['sector_analysis']['resonance_score'],
1063
+ enhancement_info['macro_analysis']['overall_macro_score'],
1064
+ 0.7 if enhancement_info['macro_analysis']['us_rate_cycle']['trend'] == '降息周期' else 0.3,
1065
+ enhancement_info['fundamental_analysis']['fundamental_score']
1066
+ ]
1067
+
1068
+ x_pos = np.arange(len(factors))
1069
+ bars = ax4.bar(x_pos, scores, color=colors_pie, alpha=0.7)
1070
+ ax4.set_xticks(x_pos)
1071
+ ax4.set_xticklabels(factors, rotation=45, fontsize=9)
1072
+ ax4.set_ylim(0, 1)
1073
+ ax4.set_ylabel('评分', fontsize=10)
1074
+ ax4.set_title('各因素当前评分', fontweight='bold', fontsize=11)
1075
+ ax4.grid(True, alpha=0.3)
1076
+
1077
+ # 在柱状图上显示数值
1078
+ for i, bar in enumerate(bars):
1079
+ height = bar.get_height()
1080
+ ax4.text(bar.get_x() + bar.get_width() / 2., height + 0.01,
1081
+ f'{height:.2f}', ha='center', va='bottom', fontsize=8)
1082
+
1083
+ # 市场状态总结
1084
+ market_status = enhancement_info['market_analysis']['market_status']
1085
+ sector_status = "热门" if enhancement_info['sector_analysis']['is_sector_hot'] else "一般"
1086
+ macro_status = "有利" if enhancement_info['macro_analysis']['overall_macro_score'] > 0.6 else "不利"
1087
+
1088
+ summary_text = f"""市场状态总结:
1089
+
1090
+ 大盘趋势: {market_status}
1091
+ 板块热度: {sector_status}
1092
+ 宏观环境: {macro_status}
1093
+ 美国利率: {enhancement_info['macro_analysis']['us_rate_cycle']['trend']}
1094
+ 综合评分: {enhancement_info['adjustment_factor']:.3f}
1095
+
1096
+ 投资建议: {enhancement_info['fundamental_analysis']['investment_rating']}"""
1097
+
1098
+ ax5.text(0.1, 0.9, summary_text, transform=ax5.transAxes, fontsize=10,
1099
+ verticalalignment='top', linespacing=1.5)
1100
+ ax5.set_title('市场状态总结', fontweight='bold', fontsize=11)
1101
+ ax5.set_xticks([])
1102
+ ax5.set_yticks([])
1103
+ ax5.spines['top'].set_visible(False)
1104
+ ax5.spines['right'].set_visible(False)
1105
+ ax5.spines['bottom'].set_visible(False)
1106
+ ax5.spines['left'].set_visible(False)
1107
+
1108
+ # 4. 详细因素分析
1109
+ if 'analysis_summary' in enhancement_info:
1110
+ summary = enhancement_info['analysis_summary']
1111
+ drivers_text = "\n".join([f"• {driver}" for driver in summary['key_drivers']]) if summary[
1112
+ 'key_drivers'] else "• 暂无明显驱动"
1113
+ risks_text = "\n".join([f"• {risk}" for risk in summary['main_risks']]) if summary[
1114
+ 'main_risks'] else "• 风险可控"
1115
+
1116
+ detail_text = f"""关键驱动因素:
1117
+ {drivers_text}
1118
+
1119
+ 主要风险提示:
1120
+ {risks_text}
1121
+
1122
+ 总体情绪: {summary['overall_sentiment']}
1123
+ 建议: {summary['investment_suggestion']}"""
1124
+
1125
+ ax6.text(0.02, 0.95, detail_text, transform=ax6.transAxes, fontsize=9,
1126
+ verticalalignment='top', linespacing=1.3)
1127
+ ax6.set_title('详细因素分析', fontweight='bold', fontsize=11)
1128
+ ax6.set_xticks([])
1129
+ ax6.set_yticks([])
1130
+ ax6.spines['top'].set_visible(False)
1131
+ ax6.spines['right'].set_visible(False)
1132
+ ax6.spines['bottom'].set_visible(False)
1133
+ ax6.spines['left'].set_visible(False)
1134
+
1135
+ plt.tight_layout()
1136
+
1137
+ # 保存图片
1138
+ chart_filename = os.path.join(output_dir, f'{stock_code}_comprehensive_prediction.png')
1139
+ plt.savefig(chart_filename, dpi=300, bbox_inches='tight', facecolor='white')
1140
+ print(f"📊 综合预测图表已保存: {chart_filename}")
1141
+
1142
+ plt.show()
1143
+
1144
+ return historical_prices, prediction_prices
1145
+
1146
+
1147
+ # ==================== 主预测函数 ====================
1148
+ def run_comprehensive_kronos_prediction(stock_code, stock_name, data_dir, pred_days, output_dir, history_years=1):
1149
+ """
1150
+ 运行综合版Kronos模型预测流程
1151
+ """
1152
+ print(f"\n🎯 开始 {stock_name}({stock_code}) 综合版Kronos模型价格预测")
1153
+ print("=" * 60)
1154
+
1155
+ # 初始化增强版市场分析器
1156
+ market_analyzer = EnhancedMarketFactorAnalyzer()
1157
+
1158
+ try:
1159
+ # 1. 获取数据
1160
+ print("\n步骤1: 获取股票数据...")
1161
+ success, csv_file_path = get_stock_data(stock_code, data_dir)
1162
+ if not success:
1163
+ print("❌ 无法获取股票数据,预测终止")
1164
+ return
1165
+
1166
+ # 2. 加载模型和分词器
1167
+ print("\n步骤2: 加载Kronos模型和分词器...")
1168
+ try:
1169
+ tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base")
1170
+ model = Kronos.from_pretrained("NeoQuasar/Kronos-base")
1171
+ print("✅ 模型加载完成 - 使用Kronos-base模型")
1172
+ except Exception as e:
1173
+ print(f"❌ 模型加载失败: {e}")
1174
+ print("⚠️ 预测功能不可用,请检查模型安装")
1175
+ return
1176
+
1177
+ # 3. 实例化预测器
1178
+ print("步骤3: 初始化预测器...")
1179
+ predictor = KronosPredictor(model, tokenizer, device="cuda:0", max_context=512)
1180
+ print("✅ 预测器初始化完成")
1181
+
1182
+ # 4. 准备数据
1183
+ print("步骤4: 准备股票数据...")
1184
+ df = prepare_stock_data(csv_file_path, stock_code, history_years)
1185
+
1186
+ # 5. 计算预测参数
1187
+ print("步骤5: 计算预测参数...")
1188
+ lookback, pred_len = calculate_prediction_parameters(df, target_days=pred_days)
1189
+
1190
+ if pred_len <= 0:
1191
+ print("❌ 数据量不足,无法进行预测")
1192
+ return
1193
+
1194
+ print(f"✅ 最终参数 - 回看期: {lookback}, 预测期: {pred_len}")
1195
+
1196
+ # 6. 准备输入数据
1197
+ print("步骤6: 准备输入数据...")
1198
+ x_df = df.loc[-lookback:, ['open', 'high', 'low', 'close', 'volume', 'amount']].reset_index(drop=True)
1199
+ x_timestamp = df.loc[-lookback:, 'timestamps'].reset_index(drop=True)
1200
+
1201
+ # 生成未来日期
1202
+ last_historical_date = df['timestamps'].iloc[-1]
1203
+ future_dates = generate_future_dates(last_historical_date, pred_len)
1204
+
1205
+ print(f"输入数据形状: {x_df.shape}")
1206
+ print(f"历史数据时间范围: {x_timestamp.iloc[0]} 到 {x_timestamp.iloc[-1]}")
1207
+ print(f"预测时间范围: {future_dates[0]} 到 {future_dates[-1]}")
1208
+
1209
+ # 7. 执行基础预测
1210
+ print("步骤7: 执行基础价格预测...")
1211
+ pred_df = predictor.predict(
1212
+ df=x_df,
1213
+ x_timestamp=x_timestamp,
1214
+ y_timestamp=pd.Series(future_dates),
1215
+ pred_len=pred_len,
1216
+ T=1.0,
1217
+ top_p=0.9,
1218
+ sample_count=1,
1219
+ verbose=True
1220
+ )
1221
+
1222
+ print("✅ 基础预测完成")
1223
+ print("预测数据前5行:")
1224
+ print(pred_df.head())
1225
+
1226
+ # 8. 使用多维度市场因素增强预测
1227
+ print("步骤8: 应用多维度市场因素增强预测...")
1228
+ enhanced_pred_df, enhancement_info = enhance_prediction_with_market_factors(
1229
+ df.loc[-lookback:].reset_index(drop=True),
1230
+ pred_df,
1231
+ stock_code,
1232
+ market_analyzer
1233
+ )
1234
+
1235
+ # 将增强预测结果添加到信息中
1236
+ enhancement_info['enhanced_prediction'] = enhanced_pred_df
1237
+
1238
+ # 9. 创建综合市场分析报告
1239
+ market_report = create_comprehensive_market_report(enhancement_info, output_dir, stock_code)
1240
+
1241
+ # 10. 可视化结果
1242
+ print("步骤9: 生成综合版可视化图表...")
1243
+ historical_df = df.loc[-lookback:].reset_index(drop=True)
1244
+ hist_prices, base_pred_prices = plot_comprehensive_prediction(
1245
+ historical_df, pred_df, future_dates, stock_code, stock_name, output_dir, enhancement_info
1246
+ )
1247
+
1248
+ # 11. 生成综合预测报告
1249
+ print("步骤10: 生成综合预测报告...")
1250
+ if len(enhanced_pred_df) > 0:
1251
+ current_price = hist_prices.iloc[-1]
1252
+ base_predicted_price = base_pred_prices.iloc[-1] if len(base_pred_prices) > 0 else current_price
1253
+ enhanced_predicted_price = enhanced_pred_df.set_index(pd.DatetimeIndex(future_dates))['close'].iloc[-1]
1254
+
1255
+ base_change_pct = (base_predicted_price / current_price - 1) * 100
1256
+ enhanced_change_pct = (enhanced_predicted_price / current_price - 1) * 100
1257
+
1258
+ print(f"\n📈 综合版Kronos模型预测报告")
1259
+ print("=" * 70)
1260
+ print(f"股票: {stock_name}({stock_code})")
1261
+ print(f"当前价格: {current_price:.2f} 元")
1262
+ print(f"基础预测价格: {base_predicted_price:.2f} 元 ({base_change_pct:+.2f}%)")
1263
+ print(f"增强预测价格: {enhanced_predicted_price:.2f} 元 ({enhanced_change_pct:+.2f}%)")
1264
+ print(f"市场因素调整因子: {enhancement_info['adjustment_factor']:.4f}")
1265
+ print(f"大盘状态: {enhancement_info['market_analysis']['market_status']}")
1266
+ print(
1267
+ f"板块共振: {enhancement_info['sector_analysis']['main_sector']['sector']} (分数: {enhancement_info['sector_analysis']['resonance_score']:.2f})")
1268
+ print(f"宏观环境: 美国{enhancement_info['macro_analysis']['us_rate_cycle']['trend']}")
1269
+ print(f"公司评级: {enhancement_info['fundamental_analysis']['investment_rating']}")
1270
+ print(f"预测期间: {pred_len} 个交易日")
1271
+
1272
+ # 输出关键因素
1273
+ print(f"\n🔑 关键影响因素:")
1274
+ for driver in enhancement_info['analysis_summary']['key_drivers']:
1275
+ print(f" ✅ {driver}")
1276
+ for risk in enhancement_info['analysis_summary']['main_risks']:
1277
+ print(f" ⚠️ {risk}")
1278
+ print(f" 💡 投资建议: {enhancement_info['analysis_summary']['investment_suggestion']}")
1279
+
1280
+ # 保存详细预测数据
1281
+ prediction_details = pd.DataFrame({
1282
+ '日期': future_dates,
1283
+ '基础预测收盘价': base_pred_prices.values if len(base_pred_prices) > 0 else [current_price] * len(
1284
+ future_dates),
1285
+ '增强预测收盘价': enhanced_pred_df['close'].values,
1286
+ '预测成交量': enhanced_pred_df['volume'].values
1287
+ })
1288
+
1289
+ prediction_file = os.path.join(output_dir, f'{stock_code}_comprehensive_predictions.csv')
1290
+ prediction_details.to_csv(prediction_file, index=False, encoding='utf-8-sig')
1291
+ print(f"💾 详细预测数据已保存: {prediction_file}")
1292
+
1293
+ print(f"\n🎉 {stock_name}({stock_code}) 综合版Kronos模型预测完成!")
1294
+
1295
+ except Exception as e:
1296
+ print(f"❌ 预测过程中出现错误: {e}")
1297
+ import traceback
1298
+ traceback.print_exc()
1299
+
1300
+
1301
+ # ==================== 主函数 ====================
1302
+ def main():
1303
+ """
1304
+ 主函数:综合版Kronos模型股票预测系统
1305
+ """
1306
+ # ==================== 配置参数 ====================
1307
+ STOCK_CONFIG = {
1308
+ "stock_code": "603288",
1309
+ "stock_name": "海天味业",
1310
+ "data_dir": r"D:\lianghuajiaoyi\Kronos\examples\data",
1311
+ "pred_days": 60,
1312
+ "output_dir": r"D:\lianghuajiaoyi\Kronos\examples\yuce",
1313
+ "history_years": 1
1314
+ }
1315
+
1316
+ print("🤖 综合版Kronos模型股票价格预测系统")
1317
+ print("=" * 50)
1318
+ print("📊 新增功能: 多维度市场因素分析")
1319
+ print("🎯 包含: 大盘趋势 + 板块共振 + 宏观政策 + 公司基本面")
1320
+ print("🚀 使用模型: Kronos-base (更适合3070Ti显卡)")
1321
+ print(f"当前预测股票: {STOCK_CONFIG['stock_name']}({STOCK_CONFIG['stock_code']})")
1322
+ print(f"预测天数: {STOCK_CONFIG['pred_days']} 天")
1323
+ print(f"输出目录: {STOCK_CONFIG['output_dir']}")
1324
+ print()
1325
+
1326
+ # 运行综合版Kronos模型预测流程
1327
+ run_comprehensive_kronos_prediction(**STOCK_CONFIG)
1328
+
1329
+ print(f"\n💡 提示:综合版模型已整合多维度市场环境分析因子")
1330
+
1331
+
1332
+ if __name__ == "__main__":
1333
+ main()
Kronos/examples/prediction_new_GUI.py ADDED
@@ -0,0 +1,1625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import matplotlib.pyplot as plt
3
+ import numpy as np
4
+ import sys
5
+ import os
6
+ from datetime import datetime, timedelta
7
+ import warnings
8
+ import requests
9
+ import json
10
+ import time
11
+ import random
12
+ import akshare as ak
13
+ from typing import Dict, List, Tuple, Optional
14
+ import tkinter as tk
15
+ from tkinter import ttk, messagebox, filedialog
16
+ import threading
17
+ from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
18
+ import matplotlib.dates as mdates
19
+ import matplotlib.ticker as ticker
20
+
21
+ warnings.filterwarnings('ignore')
22
+
23
+ # 添加项目路径以便导入自定义模块
24
+ sys.path.append("../")
25
+ try:
26
+ from model import Kronos, KronosTokenizer, KronosPredictor
27
+ except ImportError:
28
+ print("⚠️ 无法导入Kronos模型,预测功能将不可用")
29
+
30
+ # 设置中文字体
31
+ plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
32
+ plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
33
+
34
+
35
+ class StockPredictorGUI:
36
+ """股票预测图形界面"""
37
+
38
+ def __init__(self, root):
39
+ self.root = root
40
+ self.root.title("Kronos股票预测系统")
41
+ self.root.geometry("800x600")
42
+ self.root.configure(bg='#f0f0f0')
43
+
44
+ # 初始化市场分析器
45
+ self.market_analyzer = EnhancedMarketFactorAnalyzer()
46
+
47
+ # 创建界面
48
+ self.create_widgets()
49
+
50
+ # 默认配置
51
+ self.default_config = {
52
+ "stock_code": "600580",
53
+ "stock_name": "卧龙电驱",
54
+ "data_dir": r"D:\lianghuajiaoyi\Kronos\examples\data",
55
+ "output_dir": r"D:\lianghuajiaoyi\Kronos\examples\yuce",
56
+ "pred_days": 60,
57
+ "history_years": 1
58
+ }
59
+
60
+ def create_widgets(self):
61
+ """创建界面组件"""
62
+ # 主标题
63
+ title_label = tk.Label(
64
+ self.root,
65
+ text="🤖 Kronos股票预测系统",
66
+ font=("Arial", 16, "bold"),
67
+ bg='#f0f0f0',
68
+ fg='#2c3e50'
69
+ )
70
+ title_label.pack(pady=10)
71
+
72
+ # 说明标签
73
+ desc_label = tk.Label(
74
+ self.root,
75
+ text="基于Kronos模型的多维度股票价格预测系统",
76
+ font=("Arial", 10),
77
+ bg='#f0f0f0',
78
+ fg='#7f8c8d'
79
+ )
80
+ desc_label.pack(pady=5)
81
+
82
+ # 创建主框架
83
+ main_frame = tk.Frame(self.root, bg='#f0f0f0')
84
+ main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
85
+
86
+ # 输入框架
87
+ input_frame = tk.LabelFrame(main_frame, text="股票参数设置", font=("Arial", 11, "bold"),
88
+ bg='#f0f0f0', fg='#2c3e50')
89
+ input_frame.pack(fill=tk.X, pady=10)
90
+
91
+ # 股票代码输入
92
+ tk.Label(input_frame, text="股票代码:", bg='#f0f0f0', font=("Arial", 10)).grid(row=0, column=0, sticky=tk.W,
93
+ padx=5, pady=5)
94
+ self.stock_code_var = tk.StringVar(value="600580")
95
+ stock_code_entry = tk.Entry(input_frame, textvariable=self.stock_code_var, font=("Arial", 10), width=15)
96
+ stock_code_entry.grid(row=0, column=1, padx=5, pady=5)
97
+
98
+ # 股票名称输入
99
+ tk.Label(input_frame, text="股票名称:", bg='#f0f0f0', font=("Arial", 10)).grid(row=0, column=2, sticky=tk.W,
100
+ padx=5, pady=5)
101
+ self.stock_name_var = tk.StringVar(value="卧龙电驱")
102
+ stock_name_entry = tk.Entry(input_frame, textvariable=self.stock_name_var, font=("Arial", 10), width=15)
103
+ stock_name_entry.grid(row=0, column=3, padx=5, pady=5)
104
+
105
+ # 预测天数
106
+ tk.Label(input_frame, text="预测天数:", bg='#f0f0f0', font=("Arial", 10)).grid(row=1, column=0, sticky=tk.W,
107
+ padx=5, pady=5)
108
+ self.pred_days_var = tk.StringVar(value="60")
109
+ pred_days_entry = tk.Entry(input_frame, textvariable=self.pred_days_var, font=("Arial", 10), width=15)
110
+ pred_days_entry.grid(row=1, column=1, padx=5, pady=5)
111
+
112
+ # 历史数据年限
113
+ tk.Label(input_frame, text="历史年限:", bg='#f0f0f0', font=("Arial", 10)).grid(row=1, column=2, sticky=tk.W,
114
+ padx=5, pady=5)
115
+ self.history_years_var = tk.StringVar(value="1")
116
+ history_years_entry = tk.Entry(input_frame, textvariable=self.history_years_var, font=("Arial", 10), width=15)
117
+ history_years_entry.grid(row=1, column=3, padx=5, pady=5)
118
+
119
+ # 目录设置框架
120
+ dir_frame = tk.LabelFrame(main_frame, text="目录设置", font=("Arial", 11, "bold"),
121
+ bg='#f0f0f0', fg='#2c3e50')
122
+ dir_frame.pack(fill=tk.X, pady=10)
123
+
124
+ # 数据目录
125
+ tk.Label(dir_frame, text="数据目录:", bg='#f0f0f0', font=("Arial", 10)).grid(row=0, column=0, sticky=tk.W,
126
+ padx=5, pady=5)
127
+ self.data_dir_var = tk.StringVar(value=r"D:\lianghuajiaoyi\Kronos\examples\data")
128
+ data_dir_entry = tk.Entry(dir_frame, textvariable=self.data_dir_var, font=("Arial", 10), width=40)
129
+ data_dir_entry.grid(row=0, column=1, padx=5, pady=5)
130
+ tk.Button(dir_frame, text="浏览", command=self.browse_data_dir, font=("Arial", 9)).grid(row=0, column=2, padx=5,
131
+ pady=5)
132
+
133
+ # 输出目录
134
+ tk.Label(dir_frame, text="输出目录:", bg='#f0f0f0', font=("Arial", 10)).grid(row=1, column=0, sticky=tk.W,
135
+ padx=5, pady=5)
136
+ self.output_dir_var = tk.StringVar(value=r"D:\lianghuajiaoyi\Kronos\examples\yuce")
137
+ output_dir_entry = tk.Entry(dir_frame, textvariable=self.output_dir_var, font=("Arial", 10), width=40)
138
+ output_dir_entry.grid(row=1, column=1, padx=5, pady=5)
139
+ tk.Button(dir_frame, text="浏览", command=self.browse_output_dir, font=("Arial", 9)).grid(row=1, column=2,
140
+ padx=5, pady=5)
141
+
142
+ # 功能按钮框架
143
+ button_frame = tk.Frame(main_frame, bg='#f0f0f0')
144
+ button_frame.pack(pady=20)
145
+
146
+ # 预测按钮
147
+ self.predict_button = tk.Button(
148
+ button_frame,
149
+ text="🚀 开始预测",
150
+ command=self.start_prediction,
151
+ font=("Arial", 12, "bold"),
152
+ bg='#3498db',
153
+ fg='white',
154
+ width=15,
155
+ height=2
156
+ )
157
+ self.predict_button.pack(side=tk.LEFT, padx=10)
158
+
159
+ # 重置按钮
160
+ reset_button = tk.Button(
161
+ button_frame,
162
+ text="🔄 重置",
163
+ command=self.reset_fields,
164
+ font=("Arial", 10),
165
+ bg='#95a5a6',
166
+ fg='white',
167
+ width=10,
168
+ height=2
169
+ )
170
+ reset_button.pack(side=tk.LEFT, padx=10)
171
+
172
+ # 退出按钮
173
+ exit_button = tk.Button(
174
+ button_frame,
175
+ text="❌ 退出",
176
+ command=self.root.quit,
177
+ font=("Arial", 10),
178
+ bg='#e74c3c',
179
+ fg='white',
180
+ width=10,
181
+ height=2
182
+ )
183
+ exit_button.pack(side=tk.LEFT, padx=10)
184
+
185
+ # 进度显示
186
+ self.progress_frame = tk.LabelFrame(main_frame, text="预测进度", font=("Arial", 11, "bold"),
187
+ bg='#f0f0f0', fg='#2c3e50')
188
+ self.progress_frame.pack(fill=tk.X, pady=10)
189
+
190
+ self.progress_var = tk.StringVar(value="等待开始预测...")
191
+ progress_label = tk.Label(self.progress_frame, textvariable=self.progress_var, bg='#f0f0f0',
192
+ font=("Arial", 10), wraplength=700, justify=tk.LEFT)
193
+ progress_label.pack(padx=10, pady=10, fill=tk.X)
194
+
195
+ # 进度条
196
+ self.progress_bar = ttk.Progressbar(self.progress_frame, mode='indeterminate')
197
+ self.progress_bar.pack(fill=tk.X, padx=10, pady=5)
198
+
199
+ # 结果展示区域
200
+ self.result_frame = tk.LabelFrame(main_frame, text="预测结果", font=("Arial", 11, "bold"),
201
+ bg='#f0f0f0', fg='#2c3e50')
202
+ self.result_frame.pack(fill=tk.BOTH, expand=True, pady=10)
203
+
204
+ self.result_text = tk.Text(self.result_frame, height=8, font=("Arial", 9), wrap=tk.WORD)
205
+ scrollbar = tk.Scrollbar(self.result_frame, command=self.result_text.yview)
206
+ self.result_text.configure(yscrollcommand=scrollbar.set)
207
+ self.result_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5)
208
+ scrollbar.pack(side=tk.RIGHT, fill=tk.Y, pady=5)
209
+
210
+ def browse_data_dir(self):
211
+ """浏览数据目录"""
212
+ directory = filedialog.askdirectory()
213
+ if directory:
214
+ self.data_dir_var.set(directory)
215
+
216
+ def browse_output_dir(self):
217
+ """浏览输出目录"""
218
+ directory = filedialog.askdirectory()
219
+ if directory:
220
+ self.output_dir_var.set(directory)
221
+
222
+ def reset_fields(self):
223
+ """重置输入字段"""
224
+ self.stock_code_var.set("600580")
225
+ self.stock_name_var.set("卧龙电驱")
226
+ self.pred_days_var.set("60")
227
+ self.history_years_var.set("1")
228
+ self.data_dir_var.set(r"D:\lianghuajiaoyi\Kronos\examples\data")
229
+ self.output_dir_var.set(r"D:\lianghuajiaoyi\Kronos\examples\yuce")
230
+ self.result_text.delete(1.0, tk.END)
231
+ self.progress_var.set("等待开始预测...")
232
+
233
+ def start_prediction(self):
234
+ """开始预测"""
235
+ # 验证输入
236
+ if not self.validate_inputs():
237
+ return
238
+
239
+ # 禁用预测按钮
240
+ self.predict_button.config(state=tk.DISABLED)
241
+
242
+ # 清空结果区域
243
+ self.result_text.delete(1.0, tk.END)
244
+
245
+ # 开始进度条
246
+ self.progress_bar.start()
247
+
248
+ # 在新线程中运行预测
249
+ prediction_thread = threading.Thread(target=self.run_prediction)
250
+ prediction_thread.daemon = True
251
+ prediction_thread.start()
252
+
253
+ def validate_inputs(self):
254
+ """验证输入参数"""
255
+ try:
256
+ stock_code = self.stock_code_var.get().strip()
257
+ stock_name = self.stock_name_var.get().strip()
258
+ pred_days = int(self.pred_days_var.get())
259
+ history_years = int(self.history_years_var.get())
260
+
261
+ if not stock_code:
262
+ messagebox.showerror("错误", "请输入股票代码")
263
+ return False
264
+
265
+ if not stock_name:
266
+ messagebox.showerror("错误", "请输入股票名称")
267
+ return False
268
+
269
+ if pred_days <= 0 or pred_days > 365:
270
+ messagebox.showerror("错误", "预测天数应在1-365天之间")
271
+ return False
272
+
273
+ if history_years <= 0 or history_years > 10:
274
+ messagebox.showerror("错误", "历史年限应在1-10年之间")
275
+ return False
276
+
277
+ return True
278
+
279
+ except ValueError:
280
+ messagebox.showerror("错误", "请输入有效的数字")
281
+ return False
282
+
283
+ def run_prediction(self):
284
+ """运行预测流程"""
285
+ try:
286
+ # 获取输入参数
287
+ stock_code = self.stock_code_var.get().strip()
288
+ stock_name = self.stock_name_var.get().strip()
289
+ pred_days = int(self.pred_days_var.get())
290
+ history_years = int(self.history_years_var.get())
291
+ data_dir = self.data_dir_var.get()
292
+ output_dir = self.output_dir_var.get()
293
+
294
+ # 更新进度
295
+ self.update_progress("🎯 开始股票预测流程...")
296
+
297
+ # 运行预测
298
+ success, result = run_comprehensive_prediction_gui(
299
+ stock_code, stock_name, data_dir, pred_days, output_dir, history_years,
300
+ progress_callback=self.update_progress,
301
+ result_callback=self.update_result
302
+ )
303
+
304
+ if success:
305
+ self.update_progress("✅ 预测完成!")
306
+ messagebox.showinfo("完成", f"{stock_name}({stock_code})预测完成!\n图表已保存到输出目录。")
307
+ else:
308
+ self.update_progress("❌ 预测失败")
309
+ messagebox.showerror("错误", f"预测失败: {result}")
310
+
311
+ except Exception as e:
312
+ self.update_progress(f"❌ 预测过程出现错误: {str(e)}")
313
+ messagebox.showerror("错误", f"预测过程出现错误: {str(e)}")
314
+ finally:
315
+ # 重新启用预测按钮
316
+ self.root.after(0, lambda: self.predict_button.config(state=tk.NORMAL))
317
+ # 停止进度条
318
+ self.root.after(0, self.progress_bar.stop)
319
+
320
+ def update_progress(self, message):
321
+ """更新进度信息"""
322
+ self.root.after(0, lambda: self.progress_var.set(message))
323
+ print(message) # 同时在控制台输出
324
+
325
+ def update_result(self, message):
326
+ """更新结果信息"""
327
+ self.root.after(0, lambda: self.result_text.insert(tk.END, message + "\n"))
328
+ self.root.after(0, lambda: self.result_text.see(tk.END))
329
+
330
+
331
+ # ==================== 基础数据获取函数 ====================
332
+ def ensure_output_directory(output_dir):
333
+ """确保输出目录存在,如果不存在则创建"""
334
+ if not os.path.exists(output_dir):
335
+ os.makedirs(output_dir)
336
+ print(f"✅ 创建输出目录: {output_dir}")
337
+ return output_dir
338
+
339
+
340
+ def fetch_real_stock_data(stock_code, period="daily", adjust="qfq"):
341
+ """
342
+ 使用AKShare获取真实股票数据
343
+ """
344
+ try:
345
+ print(f"📡 正在通过AKShare获取 {stock_code} 的真实股票数据...")
346
+
347
+ # 获取股票数据
348
+ df = ak.stock_zh_a_hist(symbol=stock_code, period=period, adjust=adjust)
349
+
350
+ if df is None or df.empty:
351
+ print(f"❌ 未获取到 {stock_code} 的数据")
352
+ return None
353
+
354
+ # 重命名列以统一格式
355
+ column_mapping = {
356
+ '日期': 'timestamps',
357
+ '开盘': 'open',
358
+ '收盘': 'close',
359
+ '最高': 'high',
360
+ '最低': 'low',
361
+ '成交量': 'volume',
362
+ '成交额': 'amount',
363
+ '振幅': 'amplitude',
364
+ '涨跌幅': 'pct_chg',
365
+ '涨跌额': 'change_amount',
366
+ '换手率': 'turnover'
367
+ }
368
+
369
+ # 只映射存在的列
370
+ actual_mapping = {k: v for k, v in column_mapping.items() if k in df.columns}
371
+ df = df.rename(columns=actual_mapping)
372
+
373
+ # 确保时间戳格式正确
374
+ df['timestamps'] = pd.to_datetime(df['timestamps'])
375
+ df = df.sort_values('timestamps').reset_index(drop=True)
376
+
377
+ # 添加股票代码列
378
+ df['stock_code'] = stock_code
379
+
380
+ print(f"✅ 成功获取 {len(df)} 条真实数据")
381
+ print(f"📈 最新收盘价: {df['close'].iloc[-1]:.2f}元, 涨跌幅: {df['pct_chg'].iloc[-1]:.2f}%")
382
+ print(f"📅 时间范围: {df['timestamps'].min()} 到 {df['timestamps'].max()}")
383
+
384
+ return df
385
+
386
+ except Exception as e:
387
+ print(f"❌ AKShare数据获取失败: {e}")
388
+ return None
389
+
390
+
391
+ def get_stock_data_with_retry_all_history(stock_code="600580", retry_count=2):
392
+ """
393
+ 优化的数据获取函数 - 优先使用真实API数据
394
+ """
395
+ print(f"🔄 尝试获取股票 {stock_code} 的真实历史数据...")
396
+
397
+ # 优先使用AKShare获取真实数据
398
+ df = fetch_real_stock_data(stock_code, "daily", "qfq")
399
+
400
+ if df is not None:
401
+ return df
402
+ else:
403
+ print("⚠️ 真实数据获取失败,使用基于真实价格的模拟数据...")
404
+ return create_realistic_fallback_data(stock_code)
405
+
406
+
407
+ def create_realistic_fallback_data(stock_code="600580"):
408
+ """
409
+ 基于真实价格的备用数据生成函数
410
+ """
411
+ # 基于真实市场价格的参考数据
412
+ real_stock_references = {
413
+ '600580': {'name': '卧龙电驱', 'current_price': 15.20, 'range': (12.0, 20.0)},
414
+ '300207': {'name': '欣旺达', 'current_price': 33.79, 'range': (28.0, 38.0)},
415
+ '300418': {'name': '昆仑万维', 'current_price': 48.59, 'range': (40.0, 55.0)},
416
+ '002354': {'name': '天娱数科', 'current_price': 15.20, 'range': (12.0, 20.0)},
417
+ '000001': {'name': '平安银行', 'current_price': 12.50, 'range': (10.0, 16.0)},
418
+ '600036': {'name': '招商银行', 'current_price': 35.80, 'range': (30.0, 42.0)},
419
+ }
420
+
421
+ stock_info = real_stock_references.get(stock_code, {
422
+ 'name': '未知股票',
423
+ 'current_price': 20.0,
424
+ 'range': (15.0, 25.0)
425
+ })
426
+
427
+ # 生成最近1年的交易日数据
428
+ end_date = datetime.now()
429
+ start_date = end_date - timedelta(days=365)
430
+ dates = pd.bdate_range(start=start_date, end=end_date, freq='B')
431
+
432
+ # 生成基于真实价格的价格序列
433
+ np.random.seed(42)
434
+ n_points = len(dates)
435
+
436
+ # 从当前价格反向生成历史价格
437
+ current_price = stock_info['current_price']
438
+ min_price, max_price = stock_info['range']
439
+
440
+ # 反向生成价格序列
441
+ prices = [current_price]
442
+ for i in range(1, n_points):
443
+ volatility = 0.02
444
+ historical_return = np.random.normal(-0.0002, volatility)
445
+
446
+ prev_price = prices[0] * (1 + historical_return)
447
+ prev_price = max(min_price * 0.9, min(max_price * 1.1, prev_price))
448
+ prices.insert(0, prev_price)
449
+
450
+ # 生成OHLC数据
451
+ stock_data = []
452
+ for i, date in enumerate(dates):
453
+ close_price = prices[i]
454
+
455
+ daily_volatility = abs(np.random.normal(0, 0.015))
456
+ open_price = close_price * (1 + np.random.normal(0, 0.005))
457
+ high_price = max(open_price, close_price) * (1 + daily_volatility)
458
+ low_price = min(open_price, close_price) * (1 - daily_volatility)
459
+
460
+ high_price = max(open_price, close_price, low_price, high_price)
461
+ low_price = min(open_price, close_price, high_price, low_price)
462
+
463
+ volume = int(abs(np.random.normal(1500000, 400000)))
464
+ amount = volume * close_price
465
+
466
+ if i > 0:
467
+ pct_chg = ((close_price - prices[i - 1]) / prices[i - 1]) * 100
468
+ change_amount = close_price - prices[i - 1]
469
+ else:
470
+ pct_chg = 0
471
+ change_amount = 0
472
+
473
+ stock_data.append({
474
+ 'timestamps': date,
475
+ 'stock_code': stock_code,
476
+ 'open': round(open_price, 2),
477
+ 'close': round(close_price, 2),
478
+ 'high': round(high_price, 2),
479
+ 'low': round(low_price, 2),
480
+ 'volume': volume,
481
+ 'amount': round(amount, 2),
482
+ 'amplitude': round(((high_price - low_price) / open_price) * 100, 2),
483
+ 'pct_chg': round(pct_chg, 2),
484
+ 'change_amount': round(change_amount, 2),
485
+ 'turnover': round(np.random.uniform(3.0, 8.0), 2)
486
+ })
487
+
488
+ df = pd.DataFrame(stock_data)
489
+ print(f"✅ 已生成基于真实价格的备用数据 {len(df)} 条")
490
+ return df
491
+
492
+
493
+ def save_all_history_stock_data(df, stock_code, save_dir):
494
+ """
495
+ 保存股票数据到指定目录
496
+ """
497
+ if df is not None and not df.empty:
498
+ os.makedirs(save_dir, exist_ok=True)
499
+ csv_file = os.path.join(save_dir, f"{stock_code}_stock_data.csv")
500
+ df_reset = df.reset_index()
501
+ df_reset.to_csv(csv_file, encoding='utf-8-sig', index=False)
502
+ print(f"📁 股票数据已保存: {csv_file}")
503
+ return True
504
+ return False
505
+
506
+
507
+ def get_stock_data(stock_code, data_dir):
508
+ """
509
+ 获取股票数据,如果数据文件不存在则从API获取真实数据
510
+ """
511
+ csv_file_path = os.path.join(data_dir, f"{stock_code}_stock_data.csv")
512
+
513
+ if os.path.exists(csv_file_path):
514
+ print(f"📁 使用现有数据文件: {csv_file_path}")
515
+ return True, csv_file_path
516
+ else:
517
+ print(f"📡 数据文件不存在,从API获取真实数据...")
518
+ df = get_stock_data_with_retry_all_history(stock_code)
519
+
520
+ if df is not None and not df.empty:
521
+ save_all_history_stock_data(df, stock_code, data_dir)
522
+ return True, csv_file_path
523
+ else:
524
+ print(f"❌ 无法获取股票数据")
525
+ return False, None
526
+
527
+
528
+ def prepare_stock_data(csv_file_path, stock_code, history_years=1):
529
+ """
530
+ 准备股票数据,转换为Kronos模型需要的格式
531
+ """
532
+ print(f"正在加载和预处理股票 {stock_code} 数据...")
533
+
534
+ # 读取CSV文件
535
+ df = pd.read_csv(csv_file_path, encoding='utf-8-sig')
536
+
537
+ # 标准化列名
538
+ column_mapping = {
539
+ '日期': 'timestamps',
540
+ '开盘价': 'open',
541
+ '最高价': 'high',
542
+ '最低价': 'low',
543
+ '收盘价': 'close',
544
+ '成交量': 'volume',
545
+ '成交额': 'amount',
546
+ '开盘': 'open',
547
+ '收盘': 'close',
548
+ '最高': 'high',
549
+ '最低': 'low'
550
+ }
551
+
552
+ actual_mapping = {k: v for k, v in column_mapping.items() if k in df.columns}
553
+ df = df.rename(columns=actual_mapping)
554
+
555
+ # 确保时间戳列存在并转换为datetime格式
556
+ if 'timestamps' not in df.columns:
557
+ if df.index.name == '日期':
558
+ df = df.reset_index()
559
+ df = df.rename(columns={'日期': 'timestamps'})
560
+
561
+ df['timestamps'] = pd.to_datetime(df['timestamps'])
562
+ df = df.sort_values('timestamps').reset_index(drop=True)
563
+
564
+ # 根据历史年限筛选数据
565
+ if history_years > 0:
566
+ cutoff_date = datetime.now() - timedelta(days=history_years * 365)
567
+ original_count = len(df)
568
+ df = df[df['timestamps'] >= cutoff_date]
569
+ print(f"📅 使用最近 {history_years} 年数据: {len(df)} 条记录 (从 {original_count} 条中筛选)")
570
+
571
+ # 数据验证
572
+ print(f"🔍 数据验证 - 最近5个交易日收盘价:")
573
+ recent_prices = df[['timestamps', 'close']].tail()
574
+ for _, row in recent_prices.iterrows():
575
+ print(f" {row['timestamps'].strftime('%Y-%m-%d')}: {row['close']:.2f}元")
576
+
577
+ current_price = df['close'].iloc[-1]
578
+ print(f"✅ 数据加载完成,共 {len(df)} 条记录")
579
+ print(f"时间范围: {df['timestamps'].min()} 到 {df['timestamps'].max()}")
580
+ print(f"价格范围: {df['close'].min():.2f} - {df['close'].max():.2f}")
581
+ print(f"当前价格: {current_price:.2f}元")
582
+
583
+ return df
584
+
585
+
586
+ def calculate_prediction_parameters(df, target_days=60):
587
+ """
588
+ 根据目标预测天数计算合适的参数
589
+ """
590
+ # 计算平均交易日数量
591
+ total_days = (df['timestamps'].max() - df['timestamps'].min()).days
592
+ trading_days = len(df)
593
+ trading_ratio = trading_days / total_days if total_days > 0 else 0.7
594
+
595
+ # 计算目标预测的交易日数量
596
+ pred_trading_days = int(target_days * trading_ratio)
597
+
598
+ # 设置回看期数
599
+ max_lookback = int(len(df) * 0.7)
600
+ lookback = min(pred_trading_days * 3, max_lookback, len(df) - pred_trading_days)
601
+ pred_len = min(pred_trading_days, len(df) - lookback)
602
+
603
+ # 确保参数在合理范围内
604
+ lookback = max(100, min(lookback, 400))
605
+ pred_len = max(20, min(pred_len, 120))
606
+
607
+ print(f"📊 参数计算:")
608
+ print(f" 目标预测天数: {target_days} 天(自然日)")
609
+ print(f" 预计交易日数量: {pred_trading_days} 天")
610
+ print(f" 回看期数 (lookback): {lookback}")
611
+ print(f" 预测期数 (pred_len): {pred_len}")
612
+
613
+ return lookback, pred_len
614
+
615
+
616
+ def generate_trading_dates_only(last_date, pred_len):
617
+ """
618
+ 🎯 修复版:只生成交易日,排除周末和法定节假日
619
+ """
620
+ # 2025年法定节假日安排(修正版)
621
+ holidays_2025 = [
622
+ '2025-01-01', # 元旦
623
+ '2025-01-27', '2025-01-28', '2025-01-29', '2025-01-30', '2025-01-31', '2025-02-01', '2025-02-02', # 春节
624
+ '2025-04-04', '2025-04-05', '2025-04-06', # 清明
625
+ '2025-05-01', '2025-05-02', '2025-05-03', # 劳动节
626
+ '2025-06-08', '2025-06-09', '2025-06-10', # 端午
627
+ '2025-10-01', '2025-10-02', '2025-10-03', '2025-10-04', '2025-10-05', '2025-10-06', '2025-10-07', # 国庆节
628
+ ]
629
+
630
+ holidays = [datetime.strptime(date, '%Y-%m-%d').date() for date in holidays_2025]
631
+
632
+ trading_dates = []
633
+ current_date = last_date + timedelta(days=1)
634
+
635
+ while len(trading_dates) < pred_len:
636
+ # 排除周末和节假日
637
+ if current_date.weekday() < 5 and current_date.date() not in holidays:
638
+ trading_dates.append(current_date)
639
+ current_date += timedelta(days=1)
640
+
641
+ print(f"📅 生成的纯交易日: 共 {len(trading_dates)} 天")
642
+ if trading_dates:
643
+ print(f" 起始: {trading_dates[0].strftime('%Y-%m-%d')}")
644
+ print(f" 结束: {trading_dates[-1].strftime('%Y-%m-%d')}")
645
+
646
+ return trading_dates
647
+
648
+
649
+ def calculate_optimal_interval(min_val, max_val):
650
+ """
651
+ 计算最优的Y轴刻度间隔
652
+ """
653
+ range_val = max_val - min_val
654
+ if range_val <= 0:
655
+ return 1.0
656
+
657
+ if range_val < 1:
658
+ interval = 0.1
659
+ elif range_val < 5:
660
+ interval = 0.5
661
+ elif range_val < 10:
662
+ interval = 1.0
663
+ elif range_val < 20:
664
+ interval = 2.0
665
+ elif range_val < 50:
666
+ interval = 5.0
667
+ elif range_val < 100:
668
+ interval = 10.0
669
+ elif range_val < 200:
670
+ interval = 20.0
671
+ elif range_val < 500:
672
+ interval = 50.0
673
+ else:
674
+ interval = 100.0
675
+
676
+ return interval
677
+
678
+
679
+ # ==================== 增强版市场因素分析器 ====================
680
+ class EnhancedMarketFactorAnalyzer:
681
+ """增强版市场因素分析器 - 整合更多维度的市场因素"""
682
+
683
+ def __init__(self):
684
+ self.market_data = {}
685
+ self.sector_data = {}
686
+ self.macro_factors = {}
687
+ self.policy_factors = {}
688
+
689
+ def analyze_market_trend(self, index_codes=["000001", "399001"]):
690
+ """
691
+ 分析大盘趋势 - 多指数综合分析
692
+ """
693
+ try:
694
+ print(f"📊 综合分析大盘趋势...")
695
+
696
+ market_analysis = {}
697
+
698
+ for index_code in index_codes:
699
+ index_name = "上证指数" if index_code == "000001" else "深证成指"
700
+ print(f" 分析{index_name}({index_code})...")
701
+
702
+ # 获取指数数据
703
+ index_df = ak.stock_zh_index_hist(symbol=index_code, period="daily")
704
+
705
+ if index_df is None or index_df.empty:
706
+ print(f" ❌ 无法获取{index_name}数据")
707
+ continue
708
+
709
+ # 重命名列
710
+ index_df = index_df.rename(columns={
711
+ '日期': 'date', '收盘': 'close', '开盘': 'open',
712
+ '最高': 'high', '最低': 'low', '成交量': 'volume'
713
+ })
714
+ index_df['date'] = pd.to_datetime(index_df['date'])
715
+ index_df = index_df.sort_values('date').reset_index(drop=True)
716
+
717
+ # 计算技术指标
718
+ index_df['ma5'] = index_df['close'].rolling(5).mean()
719
+ index_df['ma20'] = index_df['close'].rolling(20).mean()
720
+ index_df['ma60'] = index_df['close'].rolling(60).mean()
721
+ index_df['vol_ma5'] = index_df['volume'].rolling(5).mean()
722
+
723
+ # 技术分析
724
+ current_data = index_df.iloc[-1]
725
+ prev_data = index_df.iloc[-2]
726
+
727
+ # 均线多头排列判断
728
+ ma_condition = (current_data['ma5'] > current_data['ma20'] > current_data['ma60'])
729
+
730
+ # 价格站在20日均线以上
731
+ price_above_ma20 = current_data['close'] > current_data['ma20']
732
+
733
+ # 成交量配合
734
+ volume_condition = current_data['volume'] > current_data['vol_ma5'] * 0.8
735
+
736
+ # 趋势强度
737
+ trend_strength = self._calculate_trend_strength(index_df)
738
+
739
+ is_main_uptrend = ma_condition and price_above_ma20 and trend_strength > 0.6
740
+
741
+ market_analysis[index_name] = {
742
+ 'is_main_uptrend': is_main_uptrend,
743
+ 'trend_strength': trend_strength,
744
+ 'current_close': current_data['close'],
745
+ 'price_change_pct': ((current_data['close'] - prev_data['close']) / prev_data['close']) * 100,
746
+ 'market_status': '主升浪' if is_main_uptrend else '震荡调整'
747
+ }
748
+
749
+ # 综合判断
750
+ if market_analysis:
751
+ avg_trend_strength = np.mean([data['trend_strength'] for data in market_analysis.values()])
752
+ uptrend_count = sum(1 for data in market_analysis.values() if data['is_main_uptrend'])
753
+ overall_uptrend = uptrend_count >= len(market_analysis) * 0.5
754
+
755
+ final_analysis = {
756
+ 'overall_is_main_uptrend': overall_uptrend,
757
+ 'overall_trend_strength': avg_trend_strength,
758
+ 'detailed_analysis': market_analysis,
759
+ 'market_status': '主升浪' if overall_uptrend else '震荡调整'
760
+ }
761
+
762
+ print(f"✅ 大盘分析完成: {final_analysis['market_status']}, 综合趋势强度: {avg_trend_strength:.2f}")
763
+ return final_analysis
764
+
765
+ return self._get_default_market_analysis()
766
+
767
+ except Exception as e:
768
+ print(f"❌ 大盘分析错误: {e}")
769
+ return self._get_default_market_analysis()
770
+
771
+ def analyze_sector_resonance(self, stock_code):
772
+ """
773
+ 分析板块共振效应 - 增强版行业分析
774
+ """
775
+ try:
776
+ print(f"🔄 分析板块共振效应...")
777
+
778
+ # 获取股票所属行业和概念
779
+ industry = "未知"
780
+ concepts = []
781
+
782
+ try:
783
+ stock_info = ak.stock_individual_info_em(symbol=stock_code)
784
+ if not stock_info.empty and 'value' in stock_info.columns:
785
+ industry_row = stock_info[stock_info['item'] == '行业']
786
+ if not industry_row.empty:
787
+ industry = industry_row['value'].iloc[0]
788
+ except:
789
+ pass
790
+
791
+ # 热门板块和概念映射
792
+ hot_sectors = {
793
+ '机器人': {'momentum': 0.85, 'limit_up_stocks': 18, 'active': True,
794
+ 'description': '人形机器人、工业自动化'},
795
+ '半导体': {'momentum': 0.8, 'limit_up_stocks': 15, 'active': True, 'description': '芯片国产替代'},
796
+ '人工智能': {'momentum': 0.75, 'limit_up_stocks': 12, 'active': True, 'description': 'AI大模型、算力'},
797
+ '低空经济': {'momentum': 0.7, 'limit_up_stocks': 10, 'active': True, 'description': '无人机、eVTOL'},
798
+ '新能源': {'momentum': 0.6, 'limit_up_stocks': 8, 'active': True, 'description': '光伏、储能'},
799
+ '医药': {'momentum': 0.5, 'limit_up_stocks': 5, 'active': False, 'description': '创新药'}
800
+ }
801
+
802
+ # 判断当前股票所属热门板块
803
+ matched_sectors = []
804
+ for sector, data in hot_sectors.items():
805
+ if (sector in industry or
806
+ (stock_code == '600580' and sector in ['机器人', '低空经济']) or # 卧龙电驱特殊处理
807
+ (stock_code == '300207' and sector in ['新能源'])):
808
+ matched_sectors.append({
809
+ 'sector': sector,
810
+ 'momentum': data['momentum'],
811
+ 'limit_up_stocks': data['limit_up_stocks'],
812
+ 'is_active': data['active'],
813
+ 'description': data['description']
814
+ })
815
+
816
+ # 计算综合共振分数
817
+ if matched_sectors:
818
+ resonance_score = np.mean([sector['momentum'] for sector in matched_sectors])
819
+ is_sector_hot = any(sector['is_active'] for sector in matched_sectors)
820
+ main_sector = max(matched_sectors, key=lambda x: x['momentum'])
821
+ else:
822
+ resonance_score = 0.5
823
+ is_sector_hot = False
824
+ main_sector = {'sector': '传统行业', 'momentum': 0.5, 'description': '无热门概念'}
825
+
826
+ analysis = {
827
+ 'industry': industry,
828
+ 'matched_sectors': matched_sectors,
829
+ 'main_sector': main_sector,
830
+ 'is_sector_hot': is_sector_hot,
831
+ 'resonance_score': resonance_score,
832
+ 'sector_count': len(matched_sectors)
833
+ }
834
+
835
+ print(f"✅ 板块分析完成: {industry}, 匹配{len(matched_sectors)}个热门板块, 共振分数: {resonance_score:.2f}")
836
+ return analysis
837
+
838
+ except Exception as e:
839
+ print(f"❌ 板块分析错误: {e}")
840
+ return self._get_default_sector_analysis()
841
+
842
+ def analyze_macro_factors(self):
843
+ """
844
+ 分析宏观因素 - 结合国内外政策
845
+ """
846
+ try:
847
+ print(f"🌍 分析宏观因素...")
848
+
849
+ # 美国降息周期分析 - 基于最新信息
850
+ us_rate_analysis = {
851
+ 'current_rate': 4.25, # 联邦基金利率目标区间4.00%-4.25%
852
+ 'trend': '降息周期',
853
+ 'recent_cut': '2025年9月降息25个基点',
854
+ 'expected_cuts_2025': 2, # 市场预期2025年还有两次降息
855
+ 'expected_cuts_2026': 2,
856
+ 'impact_on_emerging_markets': 'positive',
857
+ 'usd_index_support': 95.0, # 美元指数短期支撑位
858
+ 'analysis': '美联储开启宽松周期,利好全球流动性'
859
+ }
860
+
861
+ # 国内政策因素 - 基于最新政策
862
+ domestic_policy = {
863
+ 'monetary_policy': '稳健偏松',
864
+ 'fiscal_policy': '积极财政',
865
+ 'market_liquidity': '合理充裕',
866
+ 'industrial_policy': '设备更新、以旧换新', # 大规模设备更新政策
867
+ 'employment_policy': '稳就业政策加力', # 国务院稳就业政策
868
+ 'analysis': '政策组合拳发力,经济稳中向好'
869
+ }
870
+
871
+ # 行业政策支持
872
+ industry_policy = {
873
+ 'robot_policy': '机器人产业政策支持',
874
+ 'chip_policy': '国产替代加速推进',
875
+ 'AI_policy': '人工智能发展规划',
876
+ 'low_altitude': '低空经济发展规划'
877
+ }
878
+
879
+ macro_analysis = {
880
+ 'us_rate_cycle': us_rate_analysis,
881
+ 'domestic_policy': domestic_policy,
882
+ 'industry_policy': industry_policy,
883
+ 'global_liquidity_outlook': '改善',
884
+ 'overall_macro_score': 0.75 # 宏观环境整体偏积极
885
+ }
886
+
887
+ print(
888
+ f"✅ 宏观分析完成: 美国{us_rate_analysis['trend']}, 国内政策积极, 宏观评分: {macro_analysis['overall_macro_score']:.2f}")
889
+ return macro_analysis
890
+
891
+ except Exception as e:
892
+ print(f"❌ 宏观分析错误: {e}")
893
+ return self._get_default_macro_analysis()
894
+
895
+ def analyze_company_fundamentals(self, stock_code):
896
+ """
897
+ 分析公司基本面 - 针对特定股票
898
+ """
899
+ try:
900
+ print(f"🏢 分析公司基本面...")
901
+
902
+ # 卧龙电驱特殊分析
903
+ if stock_code == '600580':
904
+ fundamentals = {
905
+ 'company_name': '卧龙电驱',
906
+ 'business_areas': ['工业电机', '机器人关键部件', '航空电机', '新能源汽车驱动'],
907
+ 'recent_developments': [
908
+ '与智元机器人实现双向持股,推进具身智能机器人技术研发',
909
+ '成立浙江龙飞电驱,专注航空电机业务',
910
+ '发布AI外骨骼机器人及灵巧手',
911
+ '布局高爆发关节模组、伺服驱动器等人形机器人关键部件'
912
+ ],
913
+ 'growth_drivers': [
914
+ '设备更新政策推动工业电机需求',
915
+ '机器人产业快速发展',
916
+ '低空经济政策支持',
917
+ '出海战略加速'
918
+ ],
919
+ 'risk_factors': [
920
+ '机器人业务营收占比仅2.71%,占比较低',
921
+ '工业需求景气度波动',
922
+ '原料价格波动风险'
923
+ ],
924
+ 'investment_rating': '积极关注',
925
+ 'fundamental_score': 0.7
926
+ }
927
+ else:
928
+ # 其他股票的基础分析
929
+ fundamentals = {
930
+ 'company_name': '未知',
931
+ 'business_areas': [],
932
+ 'recent_developments': [],
933
+ 'growth_drivers': [],
934
+ 'risk_factors': [],
935
+ 'investment_rating': '中性',
936
+ 'fundamental_score': 0.5
937
+ }
938
+
939
+ print(f"✅ 基本面分析完成: {fundamentals['company_name']}, 评分: {fundamentals['fundamental_score']:.2f}")
940
+ return fundamentals
941
+
942
+ except Exception as e:
943
+ print(f"❌ 基本面分析错误: {e}")
944
+ return self._get_default_fundamental_analysis()
945
+
946
+ def _calculate_trend_strength(self, df):
947
+ """计算趋势强度"""
948
+ if len(df) < 20:
949
+ return 0.5
950
+
951
+ ma_slope = (df['ma5'].iloc[-1] - df['ma5'].iloc[-20]) / df['ma5'].iloc[-20]
952
+ price_slope = (df['close'].iloc[-1] - df['close'].iloc[-20]) / df['close'].iloc[-20]
953
+
954
+ volume_trend = df['volume'].iloc[-5:].mean() / df['volume'].iloc[-10:-5].mean()
955
+
956
+ strength = (ma_slope * 0.4 + price_slope * 0.4 + min(volume_trend - 1, 0.2) * 0.2)
957
+ return max(0, min(1, strength * 10))
958
+
959
+ def _get_default_market_analysis(self):
960
+ return {
961
+ 'overall_is_main_uptrend': False,
962
+ 'overall_trend_strength': 0.5,
963
+ 'market_status': '未知',
964
+ 'detailed_analysis': {}
965
+ }
966
+
967
+ def _get_default_sector_analysis(self):
968
+ return {
969
+ 'industry': '未知',
970
+ 'matched_sectors': [],
971
+ 'main_sector': {'sector': '未知', 'momentum': 0.5, 'description': ''},
972
+ 'is_sector_hot': False,
973
+ 'resonance_score': 0.5,
974
+ 'sector_count': 0
975
+ }
976
+
977
+ def _get_default_macro_analysis(self):
978
+ return {
979
+ 'us_rate_cycle': {'trend': '未知', 'expected_cuts_2025': 0},
980
+ 'domestic_policy': {'monetary_policy': '中性'},
981
+ 'overall_macro_score': 0.5
982
+ }
983
+
984
+ def _get_default_fundamental_analysis(self):
985
+ return {
986
+ 'company_name': '未知',
987
+ 'business_areas': [],
988
+ 'recent_developments': [],
989
+ 'growth_drivers': [],
990
+ 'risk_factors': [],
991
+ 'investment_rating': '中性',
992
+ 'fundamental_score': 0.5
993
+ }
994
+
995
+
996
+ # ==================== 优化的预测平滑函数 ====================
997
+ def smooth_prediction_results(prediction_df, historical_df, smooth_factor=0.3):
998
+ """
999
+ 🎯 优化预测结果的平滑处理,避免剧烈波动
1000
+ """
1001
+ print("🔄 应用预测结果平滑处理...")
1002
+
1003
+ smoothed_df = prediction_df.copy()
1004
+
1005
+ # 获取历史数据的趋势
1006
+ recent_trend = calculate_recent_trend(historical_df)
1007
+
1008
+ # 对价格序列进行平滑
1009
+ price_columns = ['close', 'open', 'high', 'low']
1010
+ for col in price_columns:
1011
+ if col in smoothed_df.columns:
1012
+ original_values = smoothed_df[col].values
1013
+
1014
+ # 应用移动平均平滑
1015
+ window_size = max(3, min(7, len(original_values) // 5))
1016
+ smoothed_values = pd.Series(original_values).rolling(
1017
+ window=window_size, center=True, min_periods=1
1018
+ ).mean()
1019
+
1020
+ # 结合历史趋势进行微调
1021
+ trend_adjusted = smoothed_values * (1 + recent_trend * smooth_factor)
1022
+
1023
+ smoothed_df[col] = trend_adjusted.values
1024
+
1025
+ # 对成交量进行合理调整
1026
+ if 'volume' in smoothed_df.columns:
1027
+ hist_volume_mean = historical_df['volume'].tail(20).mean()
1028
+ current_volume = smoothed_df['volume'].values
1029
+
1030
+ # 保持成交量在合理范围内
1031
+ volume_factor = 0.8 + 0.4 * np.random.random(len(current_volume))
1032
+ adjusted_volume = current_volume * volume_factor
1033
+
1034
+ # 确保成交量不会异常波动
1035
+ volume_std = historical_df['volume'].tail(50).std()
1036
+ volume_min = hist_volume_mean * 0.3
1037
+ volume_max = hist_volume_mean * 3.0
1038
+
1039
+ smoothed_df['volume'] = np.clip(adjusted_volume, volume_min, volume_max)
1040
+
1041
+ print("✅ 预测结果平滑完成")
1042
+ return smoothed_df
1043
+
1044
+
1045
+ def calculate_recent_trend(historical_df, lookback_days=20):
1046
+ """
1047
+ 计算近期价格趋势
1048
+ """
1049
+ if len(historical_df) < lookback_days:
1050
+ lookback_days = len(historical_df)
1051
+
1052
+ recent_prices = historical_df['close'].tail(lookback_days).values
1053
+ if len(recent_prices) < 2:
1054
+ return 0
1055
+
1056
+ # 计算线性回归斜率作为趋势
1057
+ x = np.arange(len(recent_prices))
1058
+ slope = np.polyfit(x, recent_prices, 1)[0]
1059
+
1060
+ # 归一化为趋势强度 (-1 到 1)
1061
+ price_range = np.ptp(recent_prices)
1062
+ if price_range > 0:
1063
+ trend_strength = slope / price_range * len(recent_prices)
1064
+ else:
1065
+ trend_strength = 0
1066
+
1067
+ return np.clip(trend_strength, -0.1, 0.1) # 限制趋势强度
1068
+
1069
+
1070
+ def apply_post_holiday_adjustment(prediction_df, future_dates, holiday_periods):
1071
+ """
1072
+ 🎯 修复版:应用节后调整,避免国庆后异常下跌
1073
+ """
1074
+ print("🔄 应用节后日历效应调整...")
1075
+
1076
+ adjusted_df = prediction_df.copy()
1077
+
1078
+ for holiday in holiday_periods:
1079
+ holiday_start = pd.Timestamp(holiday['start'])
1080
+ holiday_end = pd.Timestamp(holiday['end'])
1081
+ adjustment_days = holiday['adjustment_days']
1082
+ effect_strength = holiday['effect_strength']
1083
+
1084
+ # 计算调整期结束日期
1085
+ adjustment_end = holiday_end + timedelta(days=adjustment_days)
1086
+
1087
+ # 找到在节后调整期内的日期索引
1088
+ post_holiday_indices = []
1089
+ for i, date in enumerate(future_dates):
1090
+ if holiday_end <= date < adjustment_end:
1091
+ post_holiday_indices.append(i)
1092
+
1093
+ # 应用节后效应调整
1094
+ if post_holiday_indices:
1095
+ for col in ['close', 'open', 'high', 'low']:
1096
+ if col in adjusted_df.columns:
1097
+ for idx in post_holiday_indices:
1098
+ adjusted_df.iloc[idx][col] = adjusted_df.iloc[idx][col] * (1 + effect_strength)
1099
+
1100
+ print("✅ 节后调整完成")
1101
+ return adjusted_df
1102
+
1103
+
1104
+ # ==================== 价格合理性检查函数 ====================
1105
+ def validate_prediction_results(historical_df, prediction_df, max_price_change=0.3):
1106
+ """
1107
+ 🎯 验证预测结果的合理性,避免异常价格波动
1108
+ """
1109
+ print("🔍 验证预测结果合理性...")
1110
+
1111
+ validated_df = prediction_df.copy()
1112
+ current_price = historical_df['close'].iloc[-1]
1113
+
1114
+ # 检查价格列的合理性
1115
+ price_columns = ['close', 'open', 'high', 'low']
1116
+
1117
+ for col in price_columns:
1118
+ if col in validated_df.columns:
1119
+ # 计算最大允许的价格变化范围
1120
+ max_allowed_change = current_price * max_price_change
1121
+
1122
+ # 检查每个预测价格
1123
+ for i in range(len(validated_df)):
1124
+ predicted_price = validated_df[col].iloc[i]
1125
+
1126
+ # 如果预测价格超出合理范围,进行修正
1127
+ if abs(predicted_price - current_price) > max_allowed_change:
1128
+ # 基于历史波动率进行修正
1129
+ correction_factor = 0.8 + 0.4 * np.random.random()
1130
+ corrected_price = current_price * (1 + (predicted_price / current_price - 1) * correction_factor)
1131
+ validated_df.iloc[i][col] = corrected_price
1132
+
1133
+ print(f"⚠️ 修正异常{col}价格: {predicted_price:.2f} -> {corrected_price:.2f}")
1134
+
1135
+ print("✅ 预测结果验证完成")
1136
+ return validated_df
1137
+
1138
+
1139
+ # ==================== GUI版本预测函数 ====================
1140
+ def run_comprehensive_prediction_gui(stock_code, stock_name, data_dir, pred_days, output_dir, history_years=1,
1141
+ progress_callback=None, result_callback=None):
1142
+ """
1143
+ GUI版本的预测函数
1144
+ """
1145
+
1146
+ def update_progress(message):
1147
+ if progress_callback:
1148
+ progress_callback(message)
1149
+ print(message)
1150
+
1151
+ def update_result(message):
1152
+ if result_callback:
1153
+ result_callback(message)
1154
+ print(message)
1155
+
1156
+ try:
1157
+ # 初始化市场分析器
1158
+ market_analyzer = EnhancedMarketFactorAnalyzer()
1159
+
1160
+ update_progress(f"🎯 开始 {stock_name}({stock_code}) 预测流程")
1161
+ update_progress("=" * 50)
1162
+
1163
+ # 1. 获取数据
1164
+ update_progress("\n步骤1: 获取股票数据...")
1165
+ success, csv_file_path = get_stock_data(stock_code, data_dir)
1166
+ if not success:
1167
+ update_result("❌ 无法获取股票数据,预测终止")
1168
+ return False, "无法获取股票数据"
1169
+
1170
+ # 2. 加载模型和分词器
1171
+ update_progress("\n步骤2: 加载Kronos模型和分词器...")
1172
+ try:
1173
+ tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base")
1174
+ model = Kronos.from_pretrained("NeoQuasar/Kronos-base")
1175
+ update_progress("✅ 模型加载完成 - 使用Kronos-base模型")
1176
+ except Exception as e:
1177
+ error_msg = f"❌ 模型加载失败: {e}"
1178
+ update_result(error_msg)
1179
+ update_progress("⚠️ 预测功能不可用,请检查模型安装")
1180
+ return False, error_msg
1181
+
1182
+ # 3. 实例化预测器
1183
+ update_progress("步骤3: 初始化预测器...")
1184
+ predictor = KronosPredictor(model, tokenizer, device="cuda:0", max_context=512)
1185
+ update_progress("✅ 预测器初始化完成")
1186
+
1187
+ # 4. 准备数据
1188
+ update_progress("步骤4: 准备股票数据...")
1189
+ df = prepare_stock_data(csv_file_path, stock_code, history_years)
1190
+
1191
+ # 5. 计算预测参数
1192
+ update_progress("步骤5: 计算预测参数...")
1193
+ lookback, pred_len = calculate_prediction_parameters(df, target_days=pred_days)
1194
+
1195
+ if pred_len <= 0:
1196
+ update_result("❌ 数据量不足,无法进行预测")
1197
+ return False, "数据量不足"
1198
+
1199
+ update_progress(f"✅ 最终参数 - 回看期: {lookback}, 预测期: {pred_len}")
1200
+
1201
+ # 6. 准备输入数据
1202
+ update_progress("步骤6: 准备输入数据...")
1203
+ x_df = df.loc[-lookback:, ['open', 'high', 'low', 'close', 'volume', 'amount']].reset_index(drop=True)
1204
+ x_timestamp = df.loc[-lookback:, 'timestamps'].reset_index(drop=True)
1205
+
1206
+ # 生成未来日期 - 🎯 修复:只生成交易日
1207
+ last_historical_date = df['timestamps'].iloc[-1]
1208
+ future_dates = generate_trading_dates_only(last_historical_date, pred_len)
1209
+
1210
+ if len(future_dates) < pred_len:
1211
+ update_progress(f"⚠️ 警告:只生成了 {len(future_dates)} 个交易日,少于请求的 {pred_len} 天")
1212
+ pred_len = len(future_dates)
1213
+
1214
+ update_progress(f"输入数据形状: {x_df.shape}")
1215
+ update_progress(f"历史数据时间范围: {x_timestamp.iloc[0]} 到 {x_timestamp.iloc[-1]}")
1216
+ if future_dates:
1217
+ update_progress(f"预测时间范围: {future_dates[0]} 到 {future_dates[-1]}")
1218
+
1219
+ # 7. 执行基础预测
1220
+ update_progress("步骤7: 执行基础价格预测...")
1221
+ pred_df = predictor.predict(
1222
+ df=x_df,
1223
+ x_timestamp=x_timestamp,
1224
+ y_timestamp=pd.Series(future_dates),
1225
+ pred_len=pred_len,
1226
+ T=1.0,
1227
+ top_p=0.9,
1228
+ sample_count=1,
1229
+ verbose=True
1230
+ )
1231
+
1232
+ update_progress("✅ 基础预测完成")
1233
+
1234
+ # 🎯 新增:对基础预测进行合理性检查
1235
+ update_progress("步骤7.2: 验证预测结果合理性...")
1236
+ historical_df_for_validation = df.loc[-lookback:].reset_index(drop=True)
1237
+ validated_pred_df = validate_prediction_results(historical_df_for_validation, pred_df)
1238
+
1239
+ # 🎯 新增:对基础预测进行平滑处理
1240
+ update_progress("步骤7.5: 对预测结果进行平滑优化...")
1241
+ smoothed_pred_df = smooth_prediction_results(validated_pred_df, historical_df_for_validation)
1242
+
1243
+ # 🎯 修复:应用节后调整(特别是国庆节后)
1244
+ holiday_periods = [
1245
+ {
1246
+ 'start': '2025-10-01',
1247
+ 'end': '2025-10-09', # 国庆后第一个交易日(10月9日周四)
1248
+ 'adjustment_days': 5,
1249
+ 'effect_strength': 0.03 # 节后通常有正面效应
1250
+ }
1251
+ ]
1252
+
1253
+ adjusted_pred_df = apply_post_holiday_adjustment(smoothed_pred_df, future_dates, holiday_periods)
1254
+
1255
+ # 8. 使用多维度市场因素增强预测
1256
+ update_progress("步骤8: 应用多维度市场因素增强预测...")
1257
+ enhanced_pred_df, enhancement_info = enhance_prediction_with_market_factors(
1258
+ df.loc[-lookback:].reset_index(drop=True),
1259
+ adjusted_pred_df, # 使用平滑调整后的预测结果
1260
+ stock_code,
1261
+ market_analyzer
1262
+ )
1263
+
1264
+ # 将增强预测结果添加到信息中
1265
+ enhancement_info['enhanced_prediction'] = enhanced_pred_df
1266
+
1267
+ # 9. 创建综合市场分析报告
1268
+ update_progress("步骤9: 创建市场分析报告...")
1269
+ market_report = create_comprehensive_market_report(enhancement_info, output_dir, stock_code)
1270
+
1271
+ # 10. 生成预测图表
1272
+ update_progress("步骤10: 生成预测图表...")
1273
+ historical_df = df.loc[-lookback:].reset_index(drop=True)
1274
+ chart_path = plot_optimized_prediction_gui(
1275
+ historical_df, adjusted_pred_df, enhanced_pred_df, future_dates,
1276
+ stock_code, stock_name, output_dir, enhancement_info
1277
+ )
1278
+
1279
+ # 11. 生成预测报告
1280
+ update_progress("步骤11: 生成预测报告...")
1281
+ if len(enhanced_pred_df) > 0:
1282
+ current_price = historical_df['close'].iloc[-1]
1283
+ base_predicted_price = adjusted_pred_df['close'].iloc[-1] if len(adjusted_pred_df) > 0 else current_price
1284
+ enhanced_predicted_price = enhanced_pred_df['close'].iloc[-1]
1285
+
1286
+ base_change_pct = (base_predicted_price / current_price - 1) * 100
1287
+ enhanced_change_pct = (enhanced_predicted_price / current_price - 1) * 100
1288
+
1289
+ # 输出预测结果
1290
+ update_result(f"\n📈 {stock_name}({stock_code}) 预测报告")
1291
+ update_result("=" * 50)
1292
+ update_result(f"当前价格: {current_price:.2f} 元")
1293
+ update_result(f"平滑预测价格: {base_predicted_price:.2f} 元 ({base_change_pct:+.2f}%)")
1294
+ update_result(f"增强预测价格: {enhanced_predicted_price:.2f} 元 ({enhanced_change_pct:+.2f}%)")
1295
+ update_result(f"市场因素调整因子: {enhancement_info['adjustment_factor']:.4f}")
1296
+ update_result(f"大盘状态: {enhancement_info['market_analysis']['market_status']}")
1297
+ update_result(f"板块共振: {enhancement_info['sector_analysis']['main_sector']['sector']}")
1298
+ update_result(f"宏观环境: 美国{enhancement_info['macro_analysis']['us_rate_cycle']['trend']}")
1299
+ update_result(f"公司评级: {enhancement_info['fundamental_analysis']['investment_rating']}")
1300
+
1301
+ # 保存详细预测数据
1302
+ prediction_details = pd.DataFrame({
1303
+ '日期': future_dates,
1304
+ '平滑预测收盘价': adjusted_pred_df['close'].values if len(
1305
+ adjusted_pred_df) > 0 else [current_price] * len(future_dates),
1306
+ '增强预测收盘价': enhanced_pred_df['close'].values,
1307
+ '预测成交量': enhanced_pred_df['volume'].values
1308
+ })
1309
+
1310
+ prediction_file = os.path.join(output_dir, f'{stock_code}_comprehensive_predictions.csv')
1311
+ prediction_details.to_csv(prediction_file, index=False, encoding='utf-8-sig')
1312
+ update_progress(f"💾 详细预测数据已保存: {prediction_file}")
1313
+
1314
+ update_progress(f"\n🎉 {stock_name}({stock_code}) 预测完成!")
1315
+ update_progress(f"📊 预测图表: {chart_path}")
1316
+
1317
+ return True, "预测完成"
1318
+
1319
+ except Exception as e:
1320
+ error_msg = f"❌ 预测过程中出现错误: {e}"
1321
+ update_result(error_msg)
1322
+ import traceback
1323
+ traceback.print_exc()
1324
+ return False, error_msg
1325
+
1326
+
1327
+ def enhance_prediction_with_market_factors(historical_df, prediction_df, stock_code, market_analyzer):
1328
+ """
1329
+ 使用市场因素增强预测结果
1330
+ """
1331
+ print("\n🎯 使用市场因素增强预测...")
1332
+
1333
+ # 获取各类市场分析
1334
+ market_analysis = market_analyzer.analyze_market_trend()
1335
+ sector_analysis = market_analyzer.analyze_sector_resonance(stock_code)
1336
+ macro_analysis = market_analyzer.analyze_macro_factors()
1337
+ fundamental_analysis = market_analyzer.analyze_company_fundamentals(stock_code)
1338
+
1339
+ # 计算综合调整因子
1340
+ adjustment_factor = calculate_enhanced_adjustment_factor(
1341
+ market_analysis, sector_analysis, macro_analysis, fundamental_analysis
1342
+ )
1343
+
1344
+ print(f"📈 综合调整因子: {adjustment_factor:.4f}")
1345
+
1346
+ # 应用调整到预测结果
1347
+ enhanced_prediction = prediction_df.copy()
1348
+
1349
+ # 对价格预测进行调整
1350
+ price_columns = ['close', 'open', 'high', 'low']
1351
+ for col in price_columns:
1352
+ if col in enhanced_prediction.columns:
1353
+ enhanced_prediction[col] = enhanced_prediction[col] * adjustment_factor
1354
+
1355
+ # 对成交量进行调整
1356
+ if 'volume' in enhanced_prediction.columns:
1357
+ volume_adjustment = 1 + (adjustment_factor - 1) * 0.3
1358
+ enhanced_prediction['volume'] = enhanced_prediction['volume'] * volume_adjustment
1359
+
1360
+ return enhanced_prediction, {
1361
+ 'market_analysis': market_analysis,
1362
+ 'sector_analysis': sector_analysis,
1363
+ 'macro_analysis': macro_analysis,
1364
+ 'fundamental_analysis': fundamental_analysis,
1365
+ 'adjustment_factor': adjustment_factor
1366
+ }
1367
+
1368
+
1369
+ def calculate_enhanced_adjustment_factor(market_analysis, sector_analysis, macro_analysis, fundamental_analysis):
1370
+ """
1371
+ 计算基于多维度市场因素的调整因子
1372
+ """
1373
+ base_factor = 1.0
1374
+
1375
+ # 1. 大盘趋势影响 (权���25%)
1376
+ if market_analysis['overall_is_main_uptrend']:
1377
+ trend_strength = market_analysis['overall_trend_strength']
1378
+ base_factor *= (1 + trend_strength * 0.08)
1379
+ else:
1380
+ trend_strength = market_analysis['overall_trend_strength']
1381
+ base_factor *= (1 + (trend_strength - 0.5) * 0.04)
1382
+
1383
+ # 2. 板块共振影响 (权重25%)
1384
+ resonance_score = sector_analysis['resonance_score']
1385
+ sector_count = sector_analysis['sector_count']
1386
+
1387
+ if sector_analysis['is_sector_hot']:
1388
+ base_factor *= (1 + resonance_score * 0.06 + min(sector_count * 0.01, 0.03))
1389
+ else:
1390
+ base_factor *= (1 + (resonance_score - 0.5) * 0.02)
1391
+
1392
+ # 3. 宏观因素影响 (权重20%)
1393
+ macro_score = macro_analysis['overall_macro_score']
1394
+ base_factor *= (1 + (macro_score - 0.5) * 0.06)
1395
+
1396
+ # 4. 美国降息周期特殊影响 (权重10%)
1397
+ us_rate_trend = macro_analysis['us_rate_cycle']['trend']
1398
+ if us_rate_trend == '降息周期':
1399
+ expected_cuts = macro_analysis['us_rate_cycle']['expected_cuts_2025']
1400
+ base_factor *= (1 + expected_cuts * 0.015)
1401
+
1402
+ # 5. 公司基本面影响 (权重20%)
1403
+ fundamental_score = fundamental_analysis['fundamental_score']
1404
+ base_factor *= (1 + (fundamental_score - 0.5) * 0.08)
1405
+
1406
+ # 🎯 限制调整幅度在更合理范围内 (0.9 ~ 1.1),避免过度调整
1407
+ return max(0.9, min(1.1, base_factor))
1408
+
1409
+
1410
+ def create_comprehensive_market_report(enhancement_info, output_dir, stock_code):
1411
+ """
1412
+ 创建综合市场分析报告
1413
+ """
1414
+ report = {
1415
+ 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
1416
+ 'stock_code': stock_code,
1417
+ 'market_analysis': enhancement_info['market_analysis'],
1418
+ 'sector_analysis': enhancement_info['sector_analysis'],
1419
+ 'macro_analysis': enhancement_info['macro_analysis'],
1420
+ 'fundamental_analysis': enhancement_info['fundamental_analysis'],
1421
+ 'adjustment_factor': enhancement_info['adjustment_factor']
1422
+ }
1423
+
1424
+ # 保存报告
1425
+ report_file = os.path.join(output_dir, f'{stock_code}_comprehensive_analysis_report.json')
1426
+ with open(report_file, 'w', encoding='utf-8') as f:
1427
+ json.dump(report, f, ensure_ascii=False, indent=2)
1428
+
1429
+ print(f"📋 综合分析报告已保存: {report_file}")
1430
+ return report
1431
+
1432
+
1433
+ def plot_optimized_prediction_gui(historical_df, base_pred_df, enhanced_pred_df, future_trading_dates,
1434
+ stock_code, stock_name, output_dir, enhancement_info=None):
1435
+ """
1436
+ 🎯 优化版:清晰显示每个交易日的预测图表
1437
+ """
1438
+ ensure_output_directory(output_dir)
1439
+
1440
+ # 设置配色
1441
+ colors = {
1442
+ 'historical': '#1f77b4',
1443
+ 'prediction': '#ff7f0e',
1444
+ 'enhanced': '#2ca02c',
1445
+ 'background': '#f8f9fa',
1446
+ 'grid': '#e9ecef'
1447
+ }
1448
+
1449
+ # 创建图表
1450
+ fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(16, 12))
1451
+ fig.suptitle(f'{stock_name}({stock_code}) - 优化版交易日预测图表', fontsize=16, fontweight='bold')
1452
+
1453
+ # 设置背景色
1454
+ fig.patch.set_facecolor('white')
1455
+ for ax in [ax1, ax2, ax3, ax4]:
1456
+ ax.set_facecolor(colors['background'])
1457
+
1458
+ # 🎯 优化1: 使用实际日期作为x轴,但只显示交易日
1459
+ all_dates = list(historical_df['timestamps']) + future_trading_dates
1460
+
1461
+ # 1. 主价格图表
1462
+ current_price = historical_df['close'].iloc[-1]
1463
+
1464
+ # 绘制历史价格
1465
+ ax1.plot(historical_df['timestamps'], historical_df['close'],
1466
+ color=colors['historical'], linewidth=2.5, label='历史价格')
1467
+
1468
+ # 绘制预测价格
1469
+ if len(future_trading_dates) > 0:
1470
+ # 绘制基础预测
1471
+ ax1.plot(future_trading_dates, base_pred_df['close'],
1472
+ color=colors['prediction'], linewidth=2, label='平滑预测', linestyle='--')
1473
+
1474
+ # 绘制增强预测
1475
+ ax1.plot(future_trading_dates, enhanced_pred_df['close'],
1476
+ color=colors['enhanced'], linewidth=2.5, label='增强预测')
1477
+
1478
+ # 🎯 修复:使用更安全的关键日期标记
1479
+ mark_key_dates_safe(ax1, future_trading_dates, enhanced_pred_df)
1480
+
1481
+ ax1.set_ylabel('收盘价 (元)', fontsize=12, fontweight='bold')
1482
+ ax1.legend(loc='upper left', fontsize=10)
1483
+ ax1.grid(True, color=colors['grid'], alpha=0.7)
1484
+ ax1.set_title(f'价格走势预测 - 当前价: {current_price:.2f}元', fontweight='bold', fontsize=13)
1485
+
1486
+ # 🎯 优化2: 使用每周标记,避免过于密集
1487
+ ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
1488
+ ax1.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=mdates.MO, interval=2)) # 每两周一个标记
1489
+ plt.setp(ax1.xaxis.get_majorticklabels(), rotation=45, fontsize=9)
1490
+
1491
+ # 2. 成交量图表
1492
+ ax2.bar(historical_df['timestamps'], historical_df['volume'],
1493
+ alpha=0.6, color=colors['historical'], label='历史成交量')
1494
+
1495
+ if len(future_trading_dates) > 0:
1496
+ ax2.bar(future_trading_dates, enhanced_pred_df['volume'],
1497
+ alpha=0.6, color=colors['enhanced'], label='预测成交量')
1498
+
1499
+ ax2.set_ylabel('成交量', fontsize=12, fontweight='bold')
1500
+ ax2.legend(loc='upper left', fontsize=10)
1501
+ ax2.grid(True, color=colors['grid'], alpha=0.7)
1502
+ ax2.set_title('成交量预测', fontweight='bold', fontsize=13)
1503
+ ax2.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
1504
+ ax2.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=mdates.MO, interval=2))
1505
+ plt.setp(ax2.xaxis.get_majorticklabels(), rotation=45, fontsize=9)
1506
+
1507
+ # 3. 价格变化率图表
1508
+ ax3.plot(historical_df['timestamps'], historical_df['close'].pct_change() * 100,
1509
+ color=colors['historical'], linewidth=1.5, label='历史涨跌幅', alpha=0.7)
1510
+
1511
+ if len(future_trading_dates) > 0:
1512
+ pred_returns = enhanced_pred_df['close'].pct_change() * 100
1513
+ ax3.plot(future_trading_dates, pred_returns,
1514
+ color=colors['enhanced'], linewidth=2, label='预测涨跌幅')
1515
+
1516
+ # 添加零线参考
1517
+ ax3.axhline(y=0, color='red', linestyle='-', alpha=0.3, linewidth=1)
1518
+
1519
+ ax3.set_ylabel('日涨跌幅 (%)', fontsize=12, fontweight='bold')
1520
+ ax3.legend(loc='upper left', fontsize=10)
1521
+ ax3.grid(True, color=colors['grid'], alpha=0.7)
1522
+ ax3.set_title('价格变化率分析', fontweight='bold', fontsize=13)
1523
+ ax3.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
1524
+ ax3.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=mdates.MO, interval=2))
1525
+ plt.setp(ax3.xaxis.get_majorticklabels(), rotation=45, fontsize=9)
1526
+
1527
+ # 4. 市场因素分析
1528
+ if enhancement_info:
1529
+ factors = ['大盘趋势', '板块共振', '宏观环境', '美国降息', '基本面']
1530
+ scores = [
1531
+ enhancement_info['market_analysis']['overall_trend_strength'],
1532
+ enhancement_info['sector_analysis']['resonance_score'],
1533
+ enhancement_info['macro_analysis']['overall_macro_score'],
1534
+ 0.7 if enhancement_info['macro_analysis']['us_rate_cycle']['trend'] == '降息周期' else 0.3,
1535
+ enhancement_info['fundamental_analysis']['fundamental_score']
1536
+ ]
1537
+
1538
+ colors_bars = [colors['historical'], colors['prediction'], colors['enhanced'], '#f39c12', '#9b59b6']
1539
+
1540
+ bars = ax4.bar(factors, scores, color=colors_bars, alpha=0.8, edgecolor='black', linewidth=1)
1541
+ ax4.set_ylim(0, 1)
1542
+ ax4.set_ylabel('评分', fontsize=12, fontweight='bold')
1543
+ ax4.set_title('市场因素评分分析', fontweight='bold', fontsize=13)
1544
+ ax4.grid(True, alpha=0.3, axis='y')
1545
+
1546
+ # 在柱状图上显示具体数值
1547
+ for i, (bar, score) in enumerate(zip(bars, scores)):
1548
+ height = bar.get_height()
1549
+ ax4.text(bar.get_x() + bar.get_width() / 2., height + 0.02,
1550
+ f'{score:.2f}', ha='center', va='bottom', fontsize=10, fontweight='bold')
1551
+
1552
+ # 添加平均线
1553
+ avg_score = np.mean(scores)
1554
+ ax4.axhline(y=avg_score, color='red', linestyle='--', alpha=0.7,
1555
+ label=f'平均分: {avg_score:.2f}')
1556
+ ax4.legend(loc='upper right', fontsize=9)
1557
+
1558
+ plt.tight_layout()
1559
+
1560
+ # 保存图片
1561
+ chart_filename = os.path.join(output_dir, f'{stock_code}_optimized_prediction.png')
1562
+ plt.savefig(chart_filename, dpi=300, bbox_inches='tight', facecolor='white')
1563
+ plt.close()
1564
+
1565
+ print(f"📊 优化版预测图表已保存: {chart_filename}")
1566
+ return chart_filename
1567
+
1568
+
1569
+ def mark_key_dates_safe(ax, future_dates, pred_df):
1570
+ """
1571
+ 🎯 安全版:标记关键日期和价格点,避免类型错误
1572
+ """
1573
+ if len(future_dates) == 0 or len(pred_df) == 0:
1574
+ return
1575
+
1576
+ try:
1577
+ # 重置索引确保使用整数索引
1578
+ pred_df_reset = pred_df.reset_index(drop=True)
1579
+
1580
+ # 获取最高点和最低点的整数索引
1581
+ if hasattr(pred_df_reset['close'], 'idxmax'):
1582
+ max_idx = pred_df_reset['close'].idxmax()
1583
+ min_idx = pred_df_reset['close'].idxmin()
1584
+ else:
1585
+ # 备用方法
1586
+ max_idx = np.argmax(pred_df_reset['close'].values)
1587
+ min_idx = np.argmin(pred_df_reset['close'].values)
1588
+
1589
+ # 确保索引在有效范围内
1590
+ max_idx = min(int(max_idx), len(future_dates) - 1)
1591
+ min_idx = min(int(min_idx), len(future_dates) - 1)
1592
+
1593
+ # 标记最高点
1594
+ if 0 <= max_idx < len(future_dates):
1595
+ max_price = pred_df_reset['close'].iloc[max_idx]
1596
+ ax.plot(future_dates[max_idx], max_price,
1597
+ 'v', color='red', markersize=8, label=f'最高点: {max_price:.2f}')
1598
+
1599
+ # 标记最低点
1600
+ if 0 <= min_idx < len(future_dates):
1601
+ min_price = pred_df_reset['close'].iloc[min_idx]
1602
+ ax.plot(future_dates[min_idx], min_price,
1603
+ '^', color='green', markersize=8, label=f'最低点: {min_price:.2f}')
1604
+
1605
+ # 标记预测结束点
1606
+ if len(future_dates) > 0:
1607
+ final_price = pred_df_reset['close'].iloc[-1]
1608
+ ax.plot(future_dates[-1], final_price,
1609
+ 's', color='blue', markersize=6, label=f'最终预测: {final_price:.2f}')
1610
+
1611
+ except Exception as e:
1612
+ print(f"⚠️ 标记关键日期时出现错误: {e}")
1613
+ # 如果出错,跳过标记但不影响整体流程
1614
+
1615
+
1616
+ # ==================== 主函数 ====================
1617
+ def main():
1618
+ """主函数:启动GUI界面"""
1619
+ root = tk.Tk()
1620
+ app = StockPredictorGUI(root)
1621
+ root.mainloop()
1622
+
1623
+
1624
+ if __name__ == "__main__":
1625
+ main()
Kronos/examples/prediction_wo_vol_example.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import matplotlib.pyplot as plt
3
+ import sys
4
+ sys.path.append("../")
5
+ from model import Kronos, KronosTokenizer, KronosPredictor
6
+
7
+
8
+ def plot_prediction(kline_df, pred_df):
9
+ pred_df.index = kline_df.index[-pred_df.shape[0]:]
10
+ sr_close = kline_df['close']
11
+ sr_pred_close = pred_df['close']
12
+ sr_close.name = 'Ground Truth'
13
+ sr_pred_close.name = "Prediction"
14
+
15
+ close_df = pd.concat([sr_close, sr_pred_close], axis=1)
16
+
17
+ fig, ax = plt.subplots(1, 1, figsize=(8, 4))
18
+
19
+ ax.plot(close_df['Ground Truth'], label='Ground Truth', color='blue', linewidth=1.5)
20
+ ax.plot(close_df['Prediction'], label='Prediction', color='red', linewidth=1.5)
21
+ ax.set_ylabel('Close Price', fontsize=14)
22
+ ax.legend(loc='lower left', fontsize=12)
23
+ ax.grid(True)
24
+
25
+ plt.tight_layout()
26
+ plt.show()
27
+
28
+
29
+ # 1. Load Model and Tokenizer
30
+ tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base")
31
+ model = Kronos.from_pretrained("NeoQuasar/Kronos-small")
32
+
33
+ # 2. Instantiate Predictor
34
+ predictor = KronosPredictor(model, tokenizer, device="cuda:0", max_context=512)
35
+
36
+ # 3. Prepare Data
37
+ df = pd.read_csv("./data/XSHG_5min_600977.csv")
38
+ df['timestamps'] = pd.to_datetime(df['timestamps'])
39
+
40
+ lookback = 400
41
+ pred_len = 120
42
+
43
+ x_df = df.loc[:lookback-1, ['open', 'high', 'low', 'close']]
44
+ x_timestamp = df.loc[:lookback-1, 'timestamps']
45
+ y_timestamp = df.loc[lookback:lookback+pred_len-1, 'timestamps']
46
+
47
+ # 4. Make Prediction
48
+ pred_df = predictor.predict(
49
+ df=x_df,
50
+ x_timestamp=x_timestamp,
51
+ y_timestamp=y_timestamp,
52
+ pred_len=pred_len,
53
+ T=1.0,
54
+ top_p=0.9,
55
+ sample_count=1,
56
+ verbose=True
57
+ )
58
+
59
+ # 5. Visualize Results
60
+ print("Forecasted Data Head:")
61
+ print(pred_df.head())
62
+
63
+ # Combine historical and forecasted data for plotting
64
+ kline_df = df.loc[:lookback+pred_len-1]
65
+
66
+ # visualize
67
+ plot_prediction(kline_df, pred_df)
68
+
Kronos/examples/run_backtest_kronos.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # run_backtest.py
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import os
6
+ from datetime import datetime, timedelta
7
+ import warnings
8
+
9
+ warnings.filterwarnings('ignore')
10
+
11
+ # 设置中文字体
12
+ plt.rcParams['font.sans-serif'] = ['SimHei']
13
+ plt.rcParams['axes.unicode_minus'] = False
14
+
15
+
16
+ class KronosBacktester:
17
+ """
18
+ Kronos模型回测类
19
+ """
20
+
21
+ def __init__(self, data_dir, model_dir, initial_capital=100000):
22
+ """
23
+ 初始化回测器
24
+
25
+ 参数:
26
+ data_dir: 数据目录
27
+ model_dir: 模型预测结果目录
28
+ initial_capital: 初始资金
29
+ """
30
+ self.data_dir = data_dir
31
+ self.model_dir = model_dir
32
+ self.initial_capital = initial_capital
33
+ self.results = {}
34
+
35
+ def load_historical_data(self, stock_code):
36
+ """
37
+ 加载历史数据
38
+ """
39
+ csv_file = os.path.join(self.data_dir, f"{stock_code}_stock_data.csv")
40
+ if not os.path.exists(csv_file):
41
+ raise FileNotFoundError(f"数据文件不存在: {csv_file}")
42
+
43
+ df = pd.read_csv(csv_file, encoding='utf-8-sig')
44
+
45
+ # 检查列名并标准化
46
+ column_mapping = {
47
+ '日期': 'date',
48
+ '开盘价': 'open',
49
+ '最高价': 'high',
50
+ '最低价': 'low',
51
+ '收盘价': 'close',
52
+ '成交量': 'volume',
53
+ '成交额': 'amount'
54
+ }
55
+
56
+ # 重命名列
57
+ for old_col, new_col in column_mapping.items():
58
+ if old_col in df.columns:
59
+ df = df.rename(columns={old_col: new_col})
60
+
61
+ df['date'] = pd.to_datetime(df['date'])
62
+ df.set_index('date', inplace=True)
63
+ df = df.sort_index()
64
+
65
+ print(f"✅ 加载历史数据: {len(df)} 条记录")
66
+ print(f"时间范围: {df.index.min()} 到 {df.index.max()}")
67
+
68
+ return df
69
+
70
+ def load_predictions(self, stock_code):
71
+ """
72
+ 加载模型预测结果
73
+ """
74
+ # 尝试不同的预测文件命名
75
+ pred_files = [
76
+ os.path.join(self.model_dir, f"{stock_code}_kronos_predictions.csv"),
77
+ os.path.join(self.model_dir, f"{stock_code}_detailed_predictions.csv"),
78
+ os.path.join(self.model_dir, f"{stock_code}_predictions.csv")
79
+ ]
80
+
81
+ pred_df = None
82
+ for pred_file in pred_files:
83
+ if os.path.exists(pred_file):
84
+ pred_df = pd.read_csv(pred_file, encoding='utf-8-sig')
85
+ print(f"✅ 找到预测文件: {pred_file}")
86
+ break
87
+
88
+ if pred_df is None:
89
+ raise FileNotFoundError(f"未找到预测文件,请检查目录: {self.model_dir}")
90
+
91
+ # 标准化列名
92
+ column_mapping = {
93
+ '日期': 'date',
94
+ '预测收盘价': 'predicted_close',
95
+ '收盘价': 'predicted_close',
96
+ '预测成交量': 'predicted_volume',
97
+ '成交量': 'predicted_volume'
98
+ }
99
+
100
+ for old_col, new_col in column_mapping.items():
101
+ if old_col in pred_df.columns:
102
+ pred_df = pred_df.rename(columns={old_col: new_col})
103
+
104
+ pred_df['date'] = pd.to_datetime(pred_df['date'])
105
+ pred_df.set_index('date', inplace=True)
106
+ pred_df = pred_df.sort_index()
107
+
108
+ print(f"✅ 加载预测数据: {len(pred_df)} 条记录")
109
+ print(f"预测时间范围: {pred_df.index.min()} 到 {pred_df.index.max()}")
110
+
111
+ return pred_df
112
+
113
+ def align_data(self, hist_df, pred_df):
114
+ """
115
+ 对齐历史数据和预测数据的时间范围
116
+ """
117
+ # 找到历史数据的最后日期
118
+ last_hist_date = hist_df.index.max()
119
+
120
+ # 筛选预测数据,从历史数据结束后开始
121
+ pred_df_aligned = pred_df[pred_df.index > last_hist_date]
122
+
123
+ if len(pred_df_aligned) == 0:
124
+ # 如果没有未来的预测数据,使用所有预测数据
125
+ pred_df_aligned = pred_df.copy()
126
+ print("⚠️ 警告:预测数据没有未来的日期,使用所有预测数据")
127
+
128
+ print(f"✅ 数据对齐: 历史数据结束于 {last_hist_date}, 预测数据从 {pred_df_aligned.index.min()} 开始")
129
+
130
+ return pred_df_aligned
131
+
132
+ def calculate_trading_signals(self, hist_df, pred_df, threshold=0.02):
133
+ """
134
+ 计算交易信号
135
+ """
136
+ # 对齐数据
137
+ pred_df = self.align_data(hist_df, pred_df)
138
+
139
+ # 合并历史数据和预测数据
140
+ combined = pd.concat([
141
+ hist_df[['close']].rename(columns={'close': 'actual'}),
142
+ pred_df[['predicted_close']].rename(columns={'predicted_close': 'predicted'})
143
+ ], axis=1)
144
+
145
+ # 计算预测收益率
146
+ combined['pred_return'] = combined['predicted'].pct_change()
147
+
148
+ # 生成交易信号
149
+ combined['signal'] = 0
150
+ combined['signal'] = np.where(combined['pred_return'] > threshold, 1, # 买入信号
151
+ np.where(combined['pred_return'] < -threshold, -1, 0)) # 卖出信号
152
+
153
+ # 过滤信号:避免频繁交易
154
+ combined['position'] = combined['signal'].replace(to_replace=0, method='ffill').fillna(0)
155
+
156
+ return combined
157
+
158
+ def run_backtest(self, combined_df):
159
+ """
160
+ 运行回测
161
+ """
162
+ # 初始化资金和持仓
163
+ capital = self.initial_capital
164
+ position = 0
165
+ trades = []
166
+
167
+ # 回测记录
168
+ backtest_results = pd.DataFrame(index=combined_df.index)
169
+ backtest_results['capital'] = capital
170
+ backtest_results['position'] = 0
171
+ backtest_results['returns'] = 0.0
172
+ backtest_results['price'] = combined_df['actual'].combine_first(combined_df['predicted'])
173
+
174
+ for i, (date, row) in enumerate(combined_df.iterrows()):
175
+ current_price = row['actual'] if not pd.isna(row['actual']) else row['predicted']
176
+ signal = row['position']
177
+
178
+ # 跳过无效价格
179
+ if pd.isna(current_price):
180
+ continue
181
+
182
+ # 执行交易
183
+ if i > 0: # 从第二天开始
184
+ prev_position = backtest_results['position'].iloc[i - 1] if i > 0 else 0
185
+
186
+ # 平仓信号
187
+ if prev_position != 0 and signal == 0:
188
+ # 平仓
189
+ capital = position * current_price
190
+ position = 0
191
+ trades.append({
192
+ 'date': date,
193
+ 'action': 'SELL',
194
+ 'price': current_price,
195
+ 'shares': prev_position,
196
+ 'capital': capital
197
+ })
198
+
199
+ # 开仓信号
200
+ elif prev_position == 0 and signal != 0:
201
+ # 计算可买股数(假设全仓交易)
202
+ shares = int(capital / current_price)
203
+ if shares > 0:
204
+ position = shares * signal
205
+ capital -= shares * current_price
206
+ trades.append({
207
+ 'date': date,
208
+ 'action': 'BUY',
209
+ 'price': current_price,
210
+ 'shares': shares * signal,
211
+ 'capital': capital
212
+ })
213
+
214
+ # 更新持仓市值
215
+ portfolio_value = capital + position * current_price
216
+
217
+ # 记录结果
218
+ backtest_results.loc[date, 'capital'] = portfolio_value
219
+ backtest_results.loc[date, 'position'] = position
220
+ backtest_results.loc[date, 'price'] = current_price
221
+
222
+ # 计算日收益率
223
+ if i > 0:
224
+ prev_value = backtest_results['capital'].iloc[i - 1]
225
+ if prev_value > 0:
226
+ backtest_results.loc[date, 'returns'] = (portfolio_value - prev_value) / prev_value
227
+
228
+ return backtest_results, trades
229
+
230
+ def calculate_metrics(self, backtest_results, trades):
231
+ """
232
+ 计算回测指标
233
+ """
234
+ returns = backtest_results['returns'].replace([np.inf, -np.inf], np.nan).dropna()
235
+
236
+ if len(returns) == 0:
237
+ return {
238
+ '总收益率': 0,
239
+ '年化收益率': 0,
240
+ '波动率': 0,
241
+ '夏普比率': 0,
242
+ '最大回撤': 0,
243
+ '胜率': 0,
244
+ '平均交易收益': 0,
245
+ '交易次数': 0,
246
+ '最终资金': self.initial_capital
247
+ }
248
+
249
+ total_return = (backtest_results['capital'].iloc[-1] - self.initial_capital) / self.initial_capital
250
+ annual_return = (1 + total_return) ** (252 / len(returns)) - 1
251
+
252
+ # 波动率
253
+ volatility = returns.std() * np.sqrt(252)
254
+
255
+ # 夏普比率(假设无风险利率为3%)
256
+ risk_free_rate = 0.03
257
+ sharpe_ratio = (annual_return - risk_free_rate) / volatility if volatility > 0 else 0
258
+
259
+ # 最大回撤
260
+ cumulative_returns = (1 + returns).cumprod()
261
+ peak = cumulative_returns.expanding().max()
262
+ drawdown = (cumulative_returns - peak) / peak
263
+ max_drawdown = drawdown.min()
264
+
265
+ # 交易统计
266
+ trade_returns = []
267
+ buy_trades = [t for t in trades if t['action'] == 'BUY']
268
+ sell_trades = [t for t in trades if t['action'] == 'SELL']
269
+
270
+ for i in range(min(len(buy_trades), len(sell_trades))):
271
+ buy = buy_trades[i]
272
+ sell = sell_trades[i]
273
+ trade_return = (sell['price'] - buy['price']) / buy['price']
274
+ trade_returns.append(trade_return)
275
+
276
+ win_rate = len([r for r in trade_returns if r > 0]) / len(trade_returns) if trade_returns else 0
277
+ avg_trade_return = np.mean(trade_returns) if trade_returns else 0
278
+
279
+ metrics = {
280
+ '总收益率': total_return,
281
+ '年化收益率': annual_return,
282
+ '波动率': volatility,
283
+ '夏普比率': sharpe_ratio,
284
+ '最大回撤': max_drawdown,
285
+ '胜率': win_rate,
286
+ '平均交易收益': avg_trade_return,
287
+ '交易次数': len(trades),
288
+ '最终资金': backtest_results['capital'].iloc[-1]
289
+ }
290
+
291
+ return metrics
292
+
293
+ def plot_backtest_results(self, backtest_results, metrics, stock_code, output_dir):
294
+ """
295
+ 绘制回测结果图表
296
+ """
297
+ fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(15, 12))
298
+
299
+ # 1. 资金曲线
300
+ ax1.plot(backtest_results.index, backtest_results['capital'],
301
+ linewidth=2, label='策略资金曲线', color='#1f77b4')
302
+ ax1.axhline(y=self.initial_capital, color='red', linestyle='--',
303
+ label=f'初始资金 ({self.initial_capital:,.0f}元)')
304
+ ax1.set_ylabel('资金 (元)', fontsize=12)
305
+ ax1.legend()
306
+ ax1.grid(True, alpha=0.3)
307
+ ax1.set_title(f'{stock_code} Kronos模型回测结果', fontsize=14, fontweight='bold')
308
+
309
+ # 2. 收益率曲线
310
+ cumulative_returns = (1 + backtest_results['returns'].fillna(0)).cumprod()
311
+ ax2.plot(backtest_results.index, cumulative_returns,
312
+ linewidth=2, label='策略累计收益', color='#2ca02c')
313
+
314
+ # 基准收益(买入持有)
315
+ price_returns = backtest_results['price'].pct_change().fillna(0)
316
+ benchmark_returns = (1 + price_returns).cumprod()
317
+ ax2.plot(backtest_results.index, benchmark_returns,
318
+ linewidth=2, label='基准收益(买入持有)', color='#ff7f0e', alpha=0.7)
319
+
320
+ ax2.set_ylabel('累计收益', fontsize=12)
321
+ ax2.legend()
322
+ ax2.grid(True, alpha=0.3)
323
+
324
+ # 3. 回撤曲线
325
+ peak = cumulative_returns.expanding().max()
326
+ drawdown = (cumulative_returns - peak) / peak
327
+ ax3.fill_between(backtest_results.index, drawdown, 0,
328
+ alpha=0.3, color='red', label='回撤')
329
+ ax3.set_ylabel('回撤', fontsize=12)
330
+ ax3.set_xlabel('日期', fontsize=12)
331
+ ax3.legend()
332
+ ax3.grid(True, alpha=0.3)
333
+
334
+ # 添加指标文本
335
+ metrics_text = (
336
+ f"总收益率: {metrics['总收益率']:.2%}\n"
337
+ f"年化收益率: {metrics['年化收益率']:.2%}\n"
338
+ f"夏普比率: {metrics['夏普比率']:.2f}\n"
339
+ f"最大回撤: {metrics['最大回撤']:.2%}\n"
340
+ f"胜率: {metrics['胜率']:.2%}\n"
341
+ f"交易次数: {metrics['交易次数']}\n"
342
+ f"最终资金: {metrics['最终资金']:,.0f}元"
343
+ )
344
+
345
+ ax1.text(0.02, 0.98, metrics_text, transform=ax1.transAxes, fontsize=10,
346
+ verticalalignment='top', bbox=dict(boxstyle="round,pad=0.3",
347
+ facecolor="lightyellow", alpha=0.8))
348
+
349
+ plt.tight_layout()
350
+
351
+ # 保存图表
352
+ os.makedirs(output_dir, exist_ok=True)
353
+ chart_file = os.path.join(output_dir, f'{stock_code}_backtest_results.png')
354
+ plt.savefig(chart_file, dpi=300, bbox_inches='tight')
355
+ print(f"📊 回测图表已保存: {chart_file}")
356
+
357
+ plt.show()
358
+
359
+ def run_complete_backtest(self, stock_code, output_dir, threshold=0.02):
360
+ """
361
+ 运行完整的回测流程
362
+ """
363
+ print(f"🎯 开始 {stock_code} 回测分析")
364
+ print("=" * 50)
365
+
366
+ try:
367
+ # 1. 加载数据
368
+ print("步骤1: 加载历史数据和预测数据...")
369
+ hist_df = self.load_historical_data(stock_code)
370
+ pred_df = self.load_predictions(stock_code)
371
+
372
+ # 2. 计算交易信号
373
+ print("步骤2: 计算交易信号...")
374
+ combined_df = self.calculate_trading_signals(hist_df, pred_df, threshold)
375
+
376
+ # 3. 运行回测
377
+ print("步骤3: 运行回测...")
378
+ backtest_results, trades = self.run_backtest(combined_df)
379
+
380
+ # 4. 计算指标
381
+ print("步骤4: 计算回测指标...")
382
+ metrics = self.calculate_metrics(backtest_results, trades)
383
+
384
+ # 5. 绘制结果
385
+ print("步骤5: 生成回测图表...")
386
+ self.plot_backtest_results(backtest_results, metrics, stock_code, output_dir)
387
+
388
+ # 6. 打印详细报告
389
+ print("\n" + "=" * 70)
390
+ print(f"📊 {stock_code} 回测报告")
391
+ print("=" * 70)
392
+ for key, value in metrics.items():
393
+ if isinstance(value, float):
394
+ if '率' in key or '收益' in key or '回撤' in key:
395
+ print(f" {key}: {value:.2%}")
396
+ else:
397
+ print(f" {key}: {value:.2f}")
398
+ else:
399
+ print(f" {key}: {value}")
400
+
401
+ print(f"\n交易记录 (共{len(trades)}次交易):")
402
+ for i, trade in enumerate(trades[-10:], 1): # 显示最后10次交易
403
+ print(f" 交易{i}: {trade['date'].strftime('%Y-%m-%d')} "
404
+ f"{trade['action']} {abs(trade['shares'])}股 @ {trade['price']:.2f}元")
405
+
406
+ return metrics, backtest_results, trades
407
+
408
+ except Exception as e:
409
+ print(f"❌ 回测过程中出现错误: {e}")
410
+ import traceback
411
+ traceback.print_exc()
412
+ return None, None, None
413
+
414
+
415
+ def main():
416
+ """
417
+ 主函数:运行Kronos模型回测
418
+ """
419
+ # 配置参数
420
+ BACKTEST_CONFIG = {
421
+ "stock_code": "000831", # 要回测的股票代码
422
+ "data_dir": r"D:\lianghuajiaoyi\Kronos\examples\data", # 历史数据目录
423
+ "model_dir": r"D:\lianghuajiaoyi\Kronos\examples\yuce", # 模型预测结果目录
424
+ "output_dir": r"D:\lianghuajiaoyi\Kronos\examples\backtest", # 回测结果输出目录
425
+ "initial_capital": 100000, # 初始资金
426
+ "threshold": 0.02 # 交易阈值(2%)
427
+ }
428
+
429
+ print("🤖 Kronos模型回测系统")
430
+ print("=" * 50)
431
+ print(f"回测股票: {BACKTEST_CONFIG['stock_code']}")
432
+ print(f"初始资金: {BACKTEST_CONFIG['initial_capital']:,.0f}元")
433
+ print(f"交易阈值: {BACKTEST_CONFIG['threshold']:.1%}")
434
+ print()
435
+
436
+ # 创建回测器并运行
437
+ backtester = KronosBacktester(
438
+ data_dir=BACKTEST_CONFIG["data_dir"],
439
+ model_dir=BACKTEST_CONFIG["model_dir"],
440
+ initial_capital=BACKTEST_CONFIG["initial_capital"]
441
+ )
442
+
443
+ metrics, results, trades = backtester.run_complete_backtest(
444
+ stock_code=BACKTEST_CONFIG["stock_code"],
445
+ output_dir=BACKTEST_CONFIG["output_dir"],
446
+ threshold=BACKTEST_CONFIG["threshold"]
447
+ )
448
+
449
+ if metrics:
450
+ print(f"\n✅ {BACKTEST_CONFIG['stock_code']} 回测完成!")
451
+ print(f"📁 结果保存在: {BACKTEST_CONFIG['output_dir']}")
452
+
453
+
454
+ if __name__ == "__main__":
455
+ main()
Kronos/examples/yuce/000021_comprehensive_analysis_report.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timestamp": "2025-10-10 16:09:38",
3
+ "stock_code": "000021",
4
+ "market_analysis": {
5
+ "overall_is_main_uptrend": false,
6
+ "overall_trend_strength": 0.5,
7
+ "market_status": "未知",
8
+ "detailed_analysis": {}
9
+ },
10
+ "sector_analysis": {
11
+ "industry": "消费电子",
12
+ "matched_sectors": [],
13
+ "main_sector": {
14
+ "sector": "传统行业",
15
+ "momentum": 0.5,
16
+ "description": "无热门概念"
17
+ },
18
+ "is_sector_hot": false,
19
+ "resonance_score": 0.5,
20
+ "sector_count": 0
21
+ },
22
+ "macro_analysis": {
23
+ "us_rate_cycle": {
24
+ "current_rate": 4.25,
25
+ "trend": "降息周期",
26
+ "recent_cut": "2025年9月降息25个基点",
27
+ "expected_cuts_2025": 2,
28
+ "expected_cuts_2026": 2,
29
+ "impact_on_emerging_markets": "positive",
30
+ "usd_index_support": 95.0,
31
+ "analysis": "美联储开启宽松周期,利好全球流动性"
32
+ },
33
+ "domestic_policy": {
34
+ "monetary_policy": "稳健偏松",
35
+ "fiscal_policy": "积极财政",
36
+ "market_liquidity": "合理充裕",
37
+ "industrial_policy": "设备更新、以旧换新",
38
+ "employment_policy": "稳就业政策加力",
39
+ "analysis": "政策组合拳发力,经济稳中向好"
40
+ },
41
+ "industry_policy": {
42
+ "robot_policy": "机器人产业政策支持",
43
+ "chip_policy": "国产替代加速推进",
44
+ "AI_policy": "人工智能发展规划",
45
+ "low_altitude": "低空经济发展规划"
46
+ },
47
+ "global_liquidity_outlook": "改善",
48
+ "overall_macro_score": 0.75
49
+ },
50
+ "fundamental_analysis": {
51
+ "company_name": "未知",
52
+ "business_areas": [],
53
+ "recent_developments": [],
54
+ "growth_drivers": [],
55
+ "risk_factors": [],
56
+ "investment_rating": "中性",
57
+ "fundamental_score": 0.5
58
+ },
59
+ "adjustment_factor": 1.04545
60
+ }
Kronos/examples/yuce/000021_optimized_prediction.png ADDED

Git LFS Details

  • SHA256: 531a03e19120d9a69fb8e4380341f1c2a9cc6b7b98ddd543989ed7fbe71106c5
  • Pointer size: 131 Bytes
  • Size of remote file: 877 kB
Kronos/examples/yuce/002354_comprehensive_analysis_report.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timestamp": "2025-10-01 01:55:50",
3
+ "stock_code": "002354",
4
+ "market_analysis": {
5
+ "overall_is_main_uptrend": false,
6
+ "overall_trend_strength": 0.5,
7
+ "market_status": "未知",
8
+ "detailed_analysis": {}
9
+ },
10
+ "sector_analysis": {
11
+ "industry": "互联网服务",
12
+ "matched_sectors": [],
13
+ "main_sector": {
14
+ "sector": "传统行业",
15
+ "momentum": 0.5,
16
+ "description": "无热门概念"
17
+ },
18
+ "is_sector_hot": false,
19
+ "resonance_score": 0.5,
20
+ "sector_count": 0
21
+ },
22
+ "macro_analysis": {
23
+ "us_rate_cycle": {
24
+ "current_rate": 4.25,
25
+ "trend": "降息周期",
26
+ "recent_cut": "2025年9月降息25个基点",
27
+ "expected_cuts_2025": 2,
28
+ "expected_cuts_2026": 2,
29
+ "impact_on_emerging_markets": "positive",
30
+ "usd_index_support": 95.0,
31
+ "analysis": "美联储开启宽松周期,利好全球流动性"
32
+ },
33
+ "domestic_policy": {
34
+ "monetary_policy": "稳健偏松",
35
+ "fiscal_policy": "积极财政",
36
+ "market_liquidity": "合理充裕",
37
+ "industrial_policy": "设备更新、以旧换新",
38
+ "employment_policy": "稳就业政策加力",
39
+ "analysis": "政策组合拳发力,经济稳中向好"
40
+ },
41
+ "industry_policy": {
42
+ "robot_policy": "机器人产业政策支持",
43
+ "chip_policy": "国产替代加速推进",
44
+ "AI_policy": "人工智能发展规划",
45
+ "low_altitude": "低空经济发展规划"
46
+ },
47
+ "global_liquidity_outlook": "改善",
48
+ "overall_macro_score": 0.75
49
+ },
50
+ "fundamental_analysis": {
51
+ "company_name": "未知",
52
+ "business_areas": [],
53
+ "recent_developments": [],
54
+ "growth_drivers": [],
55
+ "risk_factors": [],
56
+ "investment_rating": "中性",
57
+ "fundamental_score": 0.5
58
+ },
59
+ "adjustment_factor": 1.04545
60
+ }
Kronos/examples/yuce/002354_optimized_prediction.png ADDED

Git LFS Details

  • SHA256: 8d85805a3001d717a1ffbd6ca8afa492e62760b2ca3061cfbbff850bea3b3f89
  • Pointer size: 131 Bytes
  • Size of remote file: 963 kB
Kronos/examples/yuce/300207_comprehensive_analysis_report.json ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timestamp": "2025-10-01 01:54:37",
3
+ "stock_code": "300207",
4
+ "market_analysis": {
5
+ "overall_is_main_uptrend": false,
6
+ "overall_trend_strength": 0.5,
7
+ "market_status": "未知",
8
+ "detailed_analysis": {}
9
+ },
10
+ "sector_analysis": {
11
+ "industry": "电池",
12
+ "matched_sectors": [
13
+ {
14
+ "sector": "新能源",
15
+ "momentum": 0.6,
16
+ "limit_up_stocks": 8,
17
+ "is_active": true,
18
+ "description": "光伏、储能"
19
+ }
20
+ ],
21
+ "main_sector": {
22
+ "sector": "新能源",
23
+ "momentum": 0.6,
24
+ "limit_up_stocks": 8,
25
+ "is_active": true,
26
+ "description": "光伏、储能"
27
+ },
28
+ "is_sector_hot": true,
29
+ "resonance_score": 0.6,
30
+ "sector_count": 1
31
+ },
32
+ "macro_analysis": {
33
+ "us_rate_cycle": {
34
+ "current_rate": 4.25,
35
+ "trend": "降息周期",
36
+ "recent_cut": "2025年9月降息25个基点",
37
+ "expected_cuts_2025": 2,
38
+ "expected_cuts_2026": 2,
39
+ "impact_on_emerging_markets": "positive",
40
+ "usd_index_support": 95.0,
41
+ "analysis": "美联储开启宽松周期,利好全球流动性"
42
+ },
43
+ "domestic_policy": {
44
+ "monetary_policy": "稳健偏松",
45
+ "fiscal_policy": "积极财政",
46
+ "market_liquidity": "合理充裕",
47
+ "industrial_policy": "设备更新、以旧换新",
48
+ "employment_policy": "稳就业政策加力",
49
+ "analysis": "政策组合拳发力,经济稳中向好"
50
+ },
51
+ "industry_policy": {
52
+ "robot_policy": "机器人产业政策支持",
53
+ "chip_policy": "国产替代加速推进",
54
+ "AI_policy": "人工智能发展规划",
55
+ "low_altitude": "低空经济发展规划"
56
+ },
57
+ "global_liquidity_outlook": "改善",
58
+ "overall_macro_score": 0.75
59
+ },
60
+ "fundamental_analysis": {
61
+ "company_name": "未知",
62
+ "business_areas": [],
63
+ "recent_developments": [],
64
+ "growth_drivers": [],
65
+ "risk_factors": [],
66
+ "investment_rating": "中性",
67
+ "fundamental_score": 0.5
68
+ },
69
+ "adjustment_factor": 1.0935407000000001
70
+ }
Kronos/examples/yuce/300207_optimized_prediction.png ADDED

Git LFS Details

  • SHA256: d932e80b049511934ac261b8868146a522acb8da3d2f0387931c42f79adb43e6
  • Pointer size: 131 Bytes
  • Size of remote file: 795 kB
Kronos/examples/yuce/600580_comprehensive_analysis_report.json ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timestamp": "2025-10-01 01:53:45",
3
+ "stock_code": "600580",
4
+ "market_analysis": {
5
+ "overall_is_main_uptrend": false,
6
+ "overall_trend_strength": 0.5,
7
+ "market_status": "未知",
8
+ "detailed_analysis": {}
9
+ },
10
+ "sector_analysis": {
11
+ "industry": "电机",
12
+ "matched_sectors": [
13
+ {
14
+ "sector": "机器人",
15
+ "momentum": 0.85,
16
+ "limit_up_stocks": 18,
17
+ "is_active": true,
18
+ "description": "人形机器人、工业自动化"
19
+ },
20
+ {
21
+ "sector": "低空经济",
22
+ "momentum": 0.7,
23
+ "limit_up_stocks": 10,
24
+ "is_active": true,
25
+ "description": "无人机、eVTOL"
26
+ }
27
+ ],
28
+ "main_sector": {
29
+ "sector": "机器人",
30
+ "momentum": 0.85,
31
+ "limit_up_stocks": 18,
32
+ "is_active": true,
33
+ "description": "人形机器人、工业自动化"
34
+ },
35
+ "is_sector_hot": true,
36
+ "resonance_score": 0.7749999999999999,
37
+ "sector_count": 2
38
+ },
39
+ "macro_analysis": {
40
+ "us_rate_cycle": {
41
+ "current_rate": 4.25,
42
+ "trend": "降息周期",
43
+ "recent_cut": "2025年9月降息25个基点",
44
+ "expected_cuts_2025": 2,
45
+ "expected_cuts_2026": 2,
46
+ "impact_on_emerging_markets": "positive",
47
+ "usd_index_support": 95.0,
48
+ "analysis": "美联储开启宽松周期,利好全球流动性"
49
+ },
50
+ "domestic_policy": {
51
+ "monetary_policy": "稳健偏松",
52
+ "fiscal_policy": "积极财政",
53
+ "market_liquidity": "合理充裕",
54
+ "industrial_policy": "设备更新、以旧换新",
55
+ "employment_policy": "稳就业政策加力",
56
+ "analysis": "政策组合拳发力,经济稳中向好"
57
+ },
58
+ "industry_policy": {
59
+ "robot_policy": "机器人产业政策支持",
60
+ "chip_policy": "国产替代加速推进",
61
+ "AI_policy": "人工智能发展规划",
62
+ "low_altitude": "低空经济发展规划"
63
+ },
64
+ "global_liquidity_outlook": "改善",
65
+ "overall_macro_score": 0.75
66
+ },
67
+ "fundamental_analysis": {
68
+ "company_name": "卧龙电驱",
69
+ "business_areas": [
70
+ "工业电机",
71
+ "机器人关键部件",
72
+ "航空电机",
73
+ "新能源汽车驱动"
74
+ ],
75
+ "recent_developments": [
76
+ "与智元机器人实现双向持股,推进具身智能机器人技术研发",
77
+ "成立浙江龙飞电驱,专注航空电机业务",
78
+ "发布AI外骨骼机器人及灵巧手",
79
+ "布局高爆发关节模组、伺服驱动器等人形机器人关键部件"
80
+ ],
81
+ "growth_drivers": [
82
+ "设备更新政策推动工业电机需求",
83
+ "机器人产业快速发展",
84
+ "低空经济政策支持",
85
+ "出海战略加速"
86
+ ],
87
+ "risk_factors": [
88
+ "机器人业务营收占比仅2.71%,占比较低",
89
+ "工业需求景气度波动",
90
+ "原料价格波动风险"
91
+ ],
92
+ "investment_rating": "积极关注",
93
+ "fundamental_score": 0.7
94
+ },
95
+ "adjustment_factor": 1.1
96
+ }
Kronos/examples/yuce/600580_optimized_prediction.png ADDED

Git LFS Details

  • SHA256: eeedf79aa21322dd64febdd4b3911519bdd871673ade2710cea08e185942fab8
  • Pointer size: 131 Bytes
  • Size of remote file: 911 kB
Kronos/examples/yuce/historical_backtest.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # historical_backtest.py
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import os
6
+ from datetime import datetime, timedelta
7
+ import warnings
8
+
9
+ warnings.filterwarnings('ignore')
10
+
11
+ # 设置中文字体
12
+ plt.rcParams['font.sans-serif'] = ['SimHei']
13
+ plt.rcParams['axes.unicode_minus'] = False
14
+
15
+
16
+ class HistoricalBacktester:
17
+ """
18
+ 历史回测类:用历史数据验证模型预测效果
19
+ """
20
+
21
+ def __init__(self, data_dir, initial_capital=100000):
22
+ self.data_dir = data_dir
23
+ self.initial_capital = initial_capital
24
+
25
+ def load_historical_data(self, stock_code):
26
+ """加载历史数据"""
27
+ csv_file = os.path.join(self.data_dir, f"{stock_code}_stock_data.csv")
28
+ if not os.path.exists(csv_file):
29
+ raise FileNotFoundError(f"数据文件不存在: {csv_file}")
30
+
31
+ df = pd.read_csv(csv_file, encoding='utf-8-sig')
32
+
33
+ # 标准化列名
34
+ column_mapping = {
35
+ '日期': 'date',
36
+ '开盘价': 'open',
37
+ '最高价': 'high',
38
+ '最低价': 'low',
39
+ '收盘价': 'close',
40
+ '成交量': 'volume',
41
+ '成交额': 'amount'
42
+ }
43
+
44
+ for old_col, new_col in column_mapping.items():
45
+ if old_col in df.columns:
46
+ df = df.rename(columns={old_col: new_col})
47
+
48
+ df['date'] = pd.to_datetime(df['date'])
49
+ df.set_index('date', inplace=True)
50
+ df = df.sort_index()
51
+
52
+ print(f"✅ 加载历史数据: {len(df)} 条记录")
53
+ print(f"时间范围: {df.index.min()} 到 {df.index.max()}")
54
+
55
+ return df
56
+
57
+ def simulate_model_prediction(self, df, lookback_days=60, pred_days=30):
58
+ """
59
+ 模拟模型预测:使用历史数据进行"预测",然后与实际结果对比
60
+ """
61
+ results = []
62
+
63
+ # 从数据中选取多个时间点进行"预测"
64
+ test_points = range(lookback_days, len(df) - pred_days, pred_days)
65
+
66
+ for start_idx in test_points:
67
+ # 模拟预测:使用前lookback_days天数据"预测"后pred_days天
68
+ historical_data = df.iloc[start_idx - lookback_days:start_idx]
69
+ actual_future = df.iloc[start_idx:start_idx + pred_days]
70
+
71
+ # 简单的预测策略(这里应该替换为您的实际模型预测)
72
+ # 这里使用移动平均作为示例预测
73
+ pred_close = self.simple_prediction(historical_data, pred_days)
74
+
75
+ # 记录结果
76
+ for i in range(min(len(pred_close), len(actual_future))):
77
+ results.append({
78
+ 'date': actual_future.index[i],
79
+ 'actual_close': actual_future['close'].iloc[i],
80
+ 'predicted_close': pred_close[i],
81
+ 'lookback_start': historical_data.index[0],
82
+ 'prediction_date': historical_data.index[-1]
83
+ })
84
+
85
+ return pd.DataFrame(results)
86
+
87
+ def simple_prediction(self, historical_data, pred_days):
88
+ """简单的预测方法(示例)"""
89
+ # 使用移动平均 + 随机波动作为预测
90
+ last_price = historical_data['close'].iloc[-1]
91
+ avg_volatility = historical_data['close'].pct_change().std()
92
+
93
+ predictions = []
94
+ current_price = last_price
95
+
96
+ for _ in range(pred_days):
97
+ # 模拟价格变化(正态分布)
98
+ change = np.random.normal(0, avg_volatility)
99
+ current_price = current_price * (1 + change)
100
+ predictions.append(current_price)
101
+
102
+ return predictions
103
+
104
+ def calculate_prediction_accuracy(self, results_df):
105
+ """计算预测准确率"""
106
+ results_df['error'] = results_df['predicted_close'] - results_df['actual_close']
107
+ results_df['error_pct'] = results_df['error'] / results_df['actual_close']
108
+ results_df['abs_error_pct'] = abs(results_df['error_pct'])
109
+
110
+ accuracy_metrics = {
111
+ '平均绝对误差率': results_df['abs_error_pct'].mean(),
112
+ '预测准确率': (results_df['abs_error_pct'] < 0.05).mean(), # 误差小于5%算准确
113
+ '方向准确率': (np.sign(results_df['predicted_close'].diff()) ==
114
+ np.sign(results_df['actual_close'].diff())).mean(),
115
+ '相关系数': results_df['predicted_close'].corr(results_df['actual_close'])
116
+ }
117
+
118
+ return accuracy_metrics
119
+
120
+ def run_trading_strategy(self, results_df, threshold=0.03):
121
+ """基于预测结果运行交易策略"""
122
+ capital = self.initial_capital
123
+ position = 0
124
+ trades = []
125
+ portfolio_values = []
126
+
127
+ # 按日期排序
128
+ results_df = results_df.sort_index()
129
+
130
+ for date, row in results_df.iterrows():
131
+ current_price = row['actual_close']
132
+ predicted_price = row['predicted_close']
133
+ predicted_return = (predicted_price - current_price) / current_price
134
+
135
+ # 交易逻辑
136
+ if position == 0 and predicted_return > threshold:
137
+ # 买入信号
138
+ shares = int(capital / current_price)
139
+ if shares > 0:
140
+ position = shares
141
+ capital -= shares * current_price
142
+ trades.append({
143
+ 'date': date,
144
+ 'action': 'BUY',
145
+ 'price': current_price,
146
+ 'shares': shares,
147
+ 'reason': f'预测上涨{predicted_return:.2%}'
148
+ })
149
+
150
+ elif position > 0 and predicted_return < -threshold:
151
+ # 卖出信号
152
+ capital += position * current_price
153
+ trades.append({
154
+ 'date': date,
155
+ 'action': 'SELL',
156
+ 'price': current_price,
157
+ 'shares': position,
158
+ 'reason': f'预测下跌{predicted_return:.2%}'
159
+ })
160
+ position = 0
161
+
162
+ # 计算当前资产总值
163
+ portfolio_value = capital + position * current_price
164
+ portfolio_values.append({
165
+ 'date': date,
166
+ 'portfolio_value': portfolio_value,
167
+ 'position': position,
168
+ 'price': current_price
169
+ })
170
+
171
+ return pd.DataFrame(portfolio_values), trades
172
+
173
+ def calculate_performance(self, portfolio_df, trades):
174
+ """计算策略表现"""
175
+ portfolio_df = portfolio_df.set_index('date')
176
+ returns = portfolio_df['portfolio_value'].pct_change().dropna()
177
+
178
+ total_return = (portfolio_df['portfolio_value'].iloc[-1] - self.initial_capital) / self.initial_capital
179
+
180
+ if len(returns) > 0:
181
+ annual_return = (1 + total_return) ** (252 / len(returns)) - 1
182
+ volatility = returns.std() * np.sqrt(252)
183
+ sharpe_ratio = (annual_return - 0.03) / volatility if volatility > 0 else 0
184
+
185
+ # 最大回撤
186
+ cumulative = (1 + returns).cumprod()
187
+ peak = cumulative.expanding().max()
188
+ drawdown = (cumulative - peak) / peak
189
+ max_drawdown = drawdown.min()
190
+ else:
191
+ annual_return = 0
192
+ volatility = 0
193
+ sharpe_ratio = 0
194
+ max_drawdown = 0
195
+
196
+ # 买入持有策略对比
197
+ buy_hold_return = (portfolio_df['price'].iloc[-1] - portfolio_df['price'].iloc[0]) / portfolio_df['price'].iloc[
198
+ 0]
199
+
200
+ performance = {
201
+ '策略总收益': total_return,
202
+ '策略年化收益': annual_return,
203
+ '买入持有收益': buy_hold_return,
204
+ '波动率': volatility,
205
+ '夏普比率': sharpe_ratio,
206
+ '最大回撤': max_drawdown,
207
+ '交易次数': len(trades),
208
+ '最终资金': portfolio_df['portfolio_value'].iloc[-1],
209
+ '超额收益': total_return - buy_hold_return
210
+ }
211
+
212
+ return performance
213
+
214
+ def plot_comparison(self, results_df, portfolio_df, stock_code, output_dir):
215
+ """绘制预测对比图表"""
216
+ fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(15, 12))
217
+
218
+ # 1. 价格预测对比
219
+ ax1.plot(results_df.index, results_df['actual_close'],
220
+ label='实际价格', color='blue', linewidth=2)
221
+ ax1.plot(results_df.index, results_df['predicted_close'],
222
+ label='预测价格', color='red', linestyle='--', alpha=0.7)
223
+ ax1.set_ylabel('价格 (元)')
224
+ ax1.legend()
225
+ ax1.set_title(f'{stock_code} - 价格预测 vs 实际走势', fontsize=14, fontweight='bold')
226
+ ax1.grid(True, alpha=0.3)
227
+
228
+ # 2. 预测误差
229
+ ax2.bar(results_df.index, results_df['error_pct'] * 100,
230
+ alpha=0.6, color='orange')
231
+ ax2.axhline(y=0, color='black', linestyle='-', linewidth=1)
232
+ ax2.set_ylabel('预测误差 (%)')
233
+ ax2.set_title('预测误差分析')
234
+ ax2.grid(True, alpha=0.3)
235
+
236
+ # 3. 策略表现
237
+ ax3.plot(portfolio_df['date'], portfolio_df['portfolio_value'],
238
+ label='策略资金曲线', color='green', linewidth=2)
239
+ ax3.axhline(y=self.initial_capital, color='red', linestyle='--',
240
+ label=f'初始资金 ({self.initial_capital:,.0f}元)')
241
+
242
+ # 买入持有对比
243
+ initial_shares = self.initial_capital / portfolio_df['price'].iloc[0]
244
+ buy_hold_values = portfolio_df['price'] * initial_shares
245
+ ax3.plot(portfolio_df['date'], buy_hold_values,
246
+ label='买入持有策略', color='blue', linestyle=':', alpha=0.7)
247
+
248
+ ax3.set_ylabel('资金 (元)')
249
+ ax3.set_xlabel('日期')
250
+ ax3.legend()
251
+ ax3.set_title('策略表现对比')
252
+ ax3.grid(True, alpha=0.3)
253
+
254
+ plt.tight_layout()
255
+
256
+ # 保存图表
257
+ os.makedirs(output_dir, exist_ok=True)
258
+ chart_file = os.path.join(output_dir, f'{stock_code}_historical_backtest.png')
259
+ plt.savefig(chart_file, dpi=300, bbox_inches='tight')
260
+ print(f"📊 历史回测图表已保存: {chart_file}")
261
+
262
+ plt.show()
263
+
264
+ def run_complete_backtest(self, stock_code, output_dir, lookback_days=60, pred_days=30, threshold=0.03):
265
+ """运行完整的历史回测"""
266
+ print(f"🎯 开始 {stock_code} 历史回测分析")
267
+ print("=" * 60)
268
+
269
+ try:
270
+ # 1. 加载历史数据
271
+ print("步骤1: 加载历史数据...")
272
+ df = self.load_historical_data(stock_code)
273
+
274
+ # 2. 模拟模型预测
275
+ print("步骤2: 模拟模型预测...")
276
+ results_df = self.simulate_model_prediction(df, lookback_days, pred_days)
277
+
278
+ # 3. 计算预测准确率
279
+ print("步骤3: 计算预测准确率...")
280
+ accuracy_metrics = self.calculate_prediction_accuracy(results_df)
281
+
282
+ # 4. 运行交易策略
283
+ print("步骤4: 运行交易策略...")
284
+ portfolio_df, trades = self.run_trading_strategy(results_df, threshold)
285
+
286
+ # 5. 计算策略表现
287
+ print("步骤5: 计算策略表现...")
288
+ performance = self.calculate_performance(portfolio_df, trades)
289
+
290
+ # 6. 绘制结果
291
+ print("步骤6: 生成回测图表...")
292
+ self.plot_comparison(results_df, portfolio_df, stock_code, output_dir)
293
+
294
+ # 7. 打印报告
295
+ print("\n" + "=" * 70)
296
+ print(f"📊 {stock_code} 历史回测报告")
297
+ print("=" * 70)
298
+
299
+ print("\n🔍 预测准确率分析:")
300
+ for metric, value in accuracy_metrics.items():
301
+ if isinstance(value, float):
302
+ print(f" {metric}: {value:.2%}")
303
+ else:
304
+ print(f" {metric}: {value:.4f}")
305
+
306
+ print("\n💰 策略表现分析:")
307
+ for metric, value in performance.items():
308
+ if isinstance(value, float):
309
+ if '收益' in metric or '回撤' in metric:
310
+ print(f" {metric}: {value:.2%}")
311
+ else:
312
+ print(f" {metric}: {value:.4f}")
313
+ else:
314
+ print(f" {metric}: {value}")
315
+
316
+ print(f"\n📈 交易统计:")
317
+ print(f" 总交易次数: {len(trades)}")
318
+ print(f" 买入次数: {len([t for t in trades if t['action'] == 'BUY'])}")
319
+ print(f" 卖出次数: {len([t for t in trades if t['action'] == 'SELL'])}")
320
+
321
+ if len(trades) > 0:
322
+ print(f"\n最近5次交易:")
323
+ for trade in trades[-5:]:
324
+ print(f" {trade['date'].strftime('%Y-%m-%d')} {trade['action']} "
325
+ f"{trade['shares']}股 @ {trade['price']:.2f}元 - {trade['reason']}")
326
+
327
+ return accuracy_metrics, performance, results_df
328
+
329
+ except Exception as e:
330
+ print(f"❌ 回测过程中出现错误: {e}")
331
+ import traceback
332
+ traceback.print_exc()
333
+ return None, None, None
334
+
335
+
336
+ def main():
337
+ """主函数"""
338
+ # 配置参数
339
+ BACKTEST_CONFIG = {
340
+ "stock_code": "300418",
341
+ "data_dir": r"D:\lianghuajiaoyi\Kronos\examples\data",
342
+ "output_dir": r"D:\lianghuajiaoyi\Kronos\examples\historical_backtest",
343
+ "initial_capital": 100000,
344
+ "lookback_days": 60, # 使用60天历史数据
345
+ "pred_days": 30, # 预测30天
346
+ "threshold": 0.03 # 3%的交易阈值
347
+ }
348
+
349
+ print("🤖 Kronos模型历史回测系统")
350
+ print("=" * 50)
351
+ print(f"回测股票: {BACKTEST_CONFIG['stock_code']}")
352
+ print(f"回看天数: {BACKTEST_CONFIG['lookback_days']}天")
353
+ print(f"预测天数: {BACKTEST_CONFIG['pred_days']}天")
354
+ print(f"初始资金: {BACKTEST_CONFIG['initial_capital']:,.0f}元")
355
+ print()
356
+
357
+ # 创建回测器并运行
358
+ backtester = HistoricalBacktester(
359
+ data_dir=BACKTEST_CONFIG["data_dir"],
360
+ initial_capital=BACKTEST_CONFIG["initial_capital"]
361
+ )
362
+
363
+ accuracy, performance, results = backtester.run_complete_backtest(
364
+ stock_code=BACKTEST_CONFIG["stock_code"],
365
+ output_dir=BACKTEST_CONFIG["output_dir"],
366
+ lookback_days=BACKTEST_CONFIG["lookback_days"],
367
+ pred_days=BACKTEST_CONFIG["pred_days"],
368
+ threshold=BACKTEST_CONFIG["threshold"]
369
+ )
370
+
371
+ if accuracy and performance:
372
+ print(f"\n✅ {BACKTEST_CONFIG['stock_code']} 历史回测完成!")
373
+
374
+ # 简单结论
375
+ if performance['超额收益'] > 0:
376
+ print("🎉 结论: 模型策略跑赢了买入持有策略!")
377
+ else:
378
+ print("⚠️ 结论: 模型策略未能跑赢买入持有策略。")
379
+
380
+ print(f"📁 详细结果保存在: {BACKTEST_CONFIG['output_dir']}")
381
+
382
+
383
+ if __name__ == "__main__":
384
+ main()
Kronos/examples/yuce/market_analysis_report.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timestamp": "2025-09-30 22:45:36",
3
+ "market_analysis": {
4
+ "is_main_uptrend": false,
5
+ "trend_strength": 0.5,
6
+ "market_status": "未知",
7
+ "support_level": null,
8
+ "resistance_level": null
9
+ },
10
+ "sector_analysis": {
11
+ "industry": "电机",
12
+ "sector_momentum": 0.5,
13
+ "sector_limit_up_count": 0,
14
+ "is_sector_hot": false,
15
+ "resonance_score": 0.35
16
+ },
17
+ "macro_analysis": {
18
+ "us_rate_cycle": {
19
+ "current_rate": 4.25,
20
+ "trend": "降息周期",
21
+ "expected_cuts_2025": 2,
22
+ "expected_cuts_2026": 2,
23
+ "impact_on_emerging_markets": "positive",
24
+ "usd_index_support": 95.0
25
+ },
26
+ "domestic_policy": {
27
+ "monetary_policy": "宽松",
28
+ "fiscal_policy": "积极",
29
+ "market_liquidity": "充足",
30
+ "holiday_effect": {
31
+ "effect": "节前震荡,节后上涨概率大",
32
+ "historical_win_rate": 0.8,
33
+ "expected_return": 0.0227,
34
+ "period": "节后5个交易日"
35
+ }
36
+ },
37
+ "global_liquidity_outlook": "改善",
38
+ "overall_macro_score": 0.7
39
+ },
40
+ "adjustment_factor": 1.00776
41
+ }
Kronos/figures/backtest_result_example.png ADDED

Git LFS Details

  • SHA256: 628b062af9f02940110304f96518254f4ddc28ed46dd7c04ba20452588adb1f0
  • Pointer size: 131 Bytes
  • Size of remote file: 182 kB
Kronos/figures/logo.png ADDED

Git LFS Details

  • SHA256: b4a3bb66fed73a24f74b74f15f0798d5edf1b9729ee826a0cad8e5088dedda61
  • Pointer size: 131 Bytes
  • Size of remote file: 872 kB
Kronos/figures/overview.png ADDED

Git LFS Details

  • SHA256: f5b4556a39883fdd82b35515a686899a4c94495f70ab8f3fc7a7ac1e3104cc50
  • Pointer size: 132 Bytes
  • Size of remote file: 1.25 MB
Kronos/figures/prediction_example.png ADDED

Git LFS Details

  • SHA256: 24ddc86256158658582687fc7cef4761f1dbb130ab8161e04957c8d178d323f9
  • Pointer size: 131 Bytes
  • Size of remote file: 194 kB
Kronos/finetune/__pycache__/config.cpython-39.pyc ADDED
Binary file (2.98 kB). View file
 
Kronos/finetune/__pycache__/qlib_test.cpython-39.pyc ADDED
Binary file (11.8 kB). View file
 
Kronos/finetune/backtest_external_signal.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Run Qlib backtest using an external signal CSV.
3
+
4
+ CSV format expected:
5
+ trade_date, code, pred, signal_date
6
+ """
7
+ import sys
8
+ import pickle
9
+ import pandas as pd
10
+ sys.path.append("../")
11
+ from config import Config
12
+ from qlib_test import QlibBacktest
13
+
14
+
15
+ SIGNAL_CSV = "/home/hanyueju/MinModel/outputs/joint_signals_val_s2s_oo.csv"
16
+ SIGNAL_NAME = "s2s_oo" # name shown in the plot legend
17
+
18
+
19
+ def load_signal(csv_path: str) -> pd.DataFrame:
20
+ df = pd.read_csv(csv_path, parse_dates=["trade_date"])
21
+ df = df[["trade_date", "code", "pred"]].dropna()
22
+ df["code"] = df["code"].str.upper()
23
+
24
+ pivot = df.pivot_table(index="trade_date", columns="code", values="pred")
25
+ pivot.index = pd.to_datetime(pivot.index)
26
+ pivot.index.name = "datetime"
27
+ pivot.columns.name = "instrument"
28
+ return pivot
29
+
30
+
31
+ if __name__ == "__main__":
32
+ print(f"Loading signal from {SIGNAL_CSV} ...")
33
+ signal_df = load_signal(SIGNAL_CSV)
34
+ print(f"Signal shape: {signal_df.shape}")
35
+ print(signal_df.head(3))
36
+
37
+ signals = {SIGNAL_NAME: signal_df}
38
+
39
+ config = Config()
40
+ backtester = QlibBacktest(config)
41
+ backtester.run_and_plot_results(signals)
Kronos/finetune/build_test_data.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Build test_data.pkl from 5min adjusted CSV files.
3
+ Only loads the test time range to save memory/disk.
4
+ """
5
+ import os
6
+ import pickle
7
+ import pandas as pd
8
+ from tqdm import tqdm
9
+
10
+ # ── Config ────────────────────────────────────────────────────────────────────
11
+ DATA_DIR = "/home/hanyueju/MinModel/data/one_stock_one_csv_adjusted"
12
+ OUTPUT_DIR = "./data/processed_datasets"
13
+ OUTPUT_FILE = os.path.join(OUTPUT_DIR, "test_data.pkl")
14
+
15
+ # Match config.py test_time_range.
16
+ # Start a bit earlier to cover the lookback_window (240 bars) before backtest begins.
17
+ TEST_START = "2024-12-20"
18
+ TEST_END = "2026-04-07"
19
+
20
+ MIN_BARS = 300 # drop stocks with fewer than this many bars in the test window
21
+ # ─────────────────────────────────────────────────────────────────────────────
22
+
23
+ def build(data_dir, test_start, test_end):
24
+ files = sorted(f for f in os.listdir(data_dir) if f.endswith(".csv"))
25
+ test_data = {}
26
+
27
+ for fname in tqdm(files, desc="Loading"):
28
+ stock_code = fname.replace(".csv", "")
29
+ path = os.path.join(data_dir, fname)
30
+
31
+ try:
32
+ df = pd.read_csv(
33
+ path,
34
+ usecols=["datetime", "open", "high", "low", "close", "volume", "turnover"],
35
+ parse_dates=["datetime"],
36
+ )
37
+ except Exception as e:
38
+ print(f" skip {fname}: {e}")
39
+ continue
40
+
41
+ df = df.rename(columns={"volume": "vol", "turnover": "amt"})
42
+ df = df.set_index("datetime").sort_index()
43
+ df = df[["open", "high", "low", "close", "vol", "amt"]]
44
+ df = df.dropna()
45
+
46
+ df = df[(df.index >= test_start) & (df.index <= test_end)]
47
+
48
+ if len(df) < MIN_BARS:
49
+ continue
50
+
51
+ test_data[stock_code] = df
52
+
53
+ return test_data
54
+
55
+
56
+ if __name__ == "__main__":
57
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
58
+
59
+ print(f"Building test_data.pkl")
60
+ print(f" Source : {DATA_DIR}")
61
+ print(f" Range : {TEST_START} ~ {TEST_END}")
62
+ print(f" Output : {OUTPUT_FILE}")
63
+ print()
64
+
65
+ test_data = build(DATA_DIR, TEST_START, TEST_END)
66
+
67
+ print(f"\nStocks loaded: {len(test_data)}")
68
+ sample_key = next(iter(test_data))
69
+ print(f"Sample ({sample_key}): {len(test_data[sample_key])} bars")
70
+ print(test_data[sample_key].head(3))
71
+
72
+ with open(OUTPUT_FILE, "wb") as f:
73
+ pickle.dump(test_data, f)
74
+
75
+ size_mb = os.path.getsize(OUTPUT_FILE) / 1024 / 1024
76
+ print(f"\nSaved → {OUTPUT_FILE} ({size_mb:.1f} MB)")
Kronos/finetune/check.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """查询 processed_datasets/test_data.pkl 覆盖的最早和最晚日期。"""
3
+
4
+ import argparse
5
+ import pickle
6
+ from pathlib import Path
7
+
8
+ import pandas as pd
9
+
10
+
11
+ DEFAULT_PATH = "finetune/data/processed_datasets/test_data.pkl"
12
+
13
+
14
+ def get_datetime_index(df: pd.DataFrame) -> pd.DatetimeIndex:
15
+ """兼容 DatetimeIndex 或名为 datetime 的普通列。"""
16
+ if isinstance(df.index, pd.DatetimeIndex):
17
+ return df.index
18
+
19
+ if "datetime" in df.columns:
20
+ return pd.to_datetime(df["datetime"], errors="coerce").dropna()
21
+
22
+ # 某些 pickle 可能把日期列保存成 index,但 index 名称不是 datetime。
23
+ converted = pd.to_datetime(df.index, errors="coerce")
24
+ return converted[~converted.isna()]
25
+
26
+
27
+ def main() -> None:
28
+ parser = argparse.ArgumentParser(description=__doc__)
29
+ parser.add_argument("path", nargs="?", default=DEFAULT_PATH, help="pickle 文件路径")
30
+ args = parser.parse_args()
31
+
32
+ path = Path(args.path)
33
+ print(f"正在加载:{path}")
34
+ print("注意:该文件约 13GB,加载可能需要较大内存。")
35
+
36
+ with path.open("rb") as file:
37
+ data = pickle.load(file)
38
+
39
+ if isinstance(data, dict):
40
+ items = data.items()
41
+ elif isinstance(data, pd.DataFrame):
42
+ items = [("<dataframe>", data)]
43
+ else:
44
+ raise TypeError(f"不支持的数据类型:{type(data).__name__}")
45
+
46
+ earliest = None
47
+ latest = None
48
+ earliest_symbol = latest_symbol = None
49
+ valid_symbols = 0
50
+
51
+ for symbol, df in items:
52
+ if not isinstance(df, pd.DataFrame) or df.empty:
53
+ continue
54
+
55
+ dates = get_datetime_index(df)
56
+ if len(dates) == 0:
57
+ continue
58
+
59
+ valid_symbols += 1
60
+ current_earliest = dates.min()
61
+ current_latest = dates.max()
62
+
63
+ if earliest is None or current_earliest < earliest:
64
+ earliest, earliest_symbol = current_earliest, symbol
65
+ if latest is None or current_latest > latest:
66
+ latest, latest_symbol = current_latest, symbol
67
+
68
+ if earliest is None:
69
+ print("没有找到有效日期。")
70
+ return
71
+
72
+ print(f"股票数量:{valid_symbols}")
73
+ print(f"最早日期:{earliest}(股票:{earliest_symbol})")
74
+ print(f"最晚日期:{latest}(股票:{latest_symbol})")
75
+ print(f"覆盖范围:{earliest.date()} ~ {latest.date()}")
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
Kronos/finetune/config copy.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ class Config:
4
+ """
5
+ Configuration class for the entire project.
6
+ """
7
+
8
+ def __init__(self):
9
+ # =================================================================
10
+ # Data & Feature Parameters
11
+ # =================================================================
12
+ # TODO: Update this path to your Qlib data directory.
13
+ self.qlib_data_path = "~/.qlib/qlib_data/cn_data_local"
14
+ self.instrument = 'all'
15
+
16
+ # Overall time range for data loading from Qlib.
17
+ self.dataset_begin_time = "2021-12-01"
18
+ self.dataset_end_time = '2026-04-05'
19
+
20
+ # Sliding window parameters for creating samples.
21
+ self.lookback_window = 672 # Number of past time steps for input.
22
+ self.predict_window = 49 # Number of future time steps for prediction.
23
+ self.max_context = 512 # Maximum context length for the model.
24
+
25
+ # Features to be used from the raw data.
26
+ self.feature_list = ['open', 'high', 'low', 'close', 'vol', 'amt']
27
+ # Time-based features to be generated.
28
+ self.time_feature_list = ['minute', 'hour', 'weekday', 'day', 'month']
29
+
30
+ # =================================================================
31
+ # Dataset Splitting & Paths
32
+ # =================================================================
33
+ # Note: The validation/test set starts earlier than the training/validation set ends
34
+ # to account for the `lookback_window`.
35
+ self.train_time_range = ["2011-01-01", "2015-12-10"]
36
+ self.val_time_range = ["2015-12-20", "2021-05-10"]
37
+ self.test_time_range = ["2022-01-01", "2026-04-05"]
38
+ self.backtest_time_range = ["2022-01-01", "2026-04-05"]
39
+
40
+ # TODO: Directory to save the processed, pickled datasets.
41
+ self.dataset_path = "./data/processed_datasets"
42
+
43
+ # =================================================================
44
+ # Training Hyperparameters
45
+ # =================================================================
46
+ self.clip = 5.0 # Clipping value for normalized data to prevent outliers.
47
+
48
+ self.epochs = 30
49
+ self.log_interval = 100 # Log training status every N batches.
50
+ self.batch_size = 50 # Batch size per GPU.
51
+
52
+ # Number of samples to draw for one "epoch" of training/validation.
53
+ # This is useful for large datasets where a true epoch is too long.
54
+ self.n_train_iter = 2000 * self.batch_size
55
+ self.n_val_iter = 400 * self.batch_size
56
+
57
+ # Learning rates for different model components.
58
+ self.tokenizer_learning_rate = 2e-4
59
+ self.predictor_learning_rate = 4e-5
60
+
61
+ # Gradient accumulation to simulate a larger batch size.
62
+ self.accumulation_steps = 1
63
+
64
+ # AdamW optimizer parameters.
65
+ self.adam_beta1 = 0.9
66
+ self.adam_beta2 = 0.95
67
+ self.adam_weight_decay = 0.1
68
+
69
+ # Miscellaneous
70
+ self.seed = 100 # Global random seed for reproducibility.
71
+
72
+ # =================================================================
73
+ # Experiment Logging & Saving
74
+ # =================================================================
75
+ self.use_comet = False # Set to False if you don't want to use Comet ML
76
+ self.comet_config = {
77
+ # It is highly recommended to load secrets from environment variables
78
+ # for security purposes. Example: os.getenv("COMET_API_KEY")
79
+ "api_key": "YOUR_COMET_API_KEY",
80
+ "project_name": "Kronos-Finetune-Demo",
81
+ "workspace": "your_comet_workspace" # TODO: Change to your Comet ML workspace name
82
+ }
83
+ self.comet_tag = 'finetune_demo'
84
+ self.comet_name = 'finetune_demo'
85
+
86
+ # Base directory for saving model checkpoints and results.
87
+ # Using a general 'outputs' directory is a common practice.
88
+ self.save_path = "./outputs/models"
89
+ self.tokenizer_save_folder_name = 'finetune_tokenizer_demo'
90
+ self.predictor_save_folder_name = 'finetune_predictor_demo'
91
+ self.backtest_save_folder_name = 'finetune_backtest_demo'
92
+
93
+ # Path for backtesting results.
94
+ self.backtest_result_path = "./outputs/backtest_results"
95
+
96
+ # =================================================================
97
+ # Model & Checkpoint Paths
98
+ # =================================================================
99
+ # TODO: Update these paths to your pretrained model locations.
100
+ # These can be local paths or Hugging Face Hub model identifiers.
101
+ self.pretrained_tokenizer_path = "NeoQuasar/Kronos-Tokenizer-base"
102
+ self.pretrained_predictor_path = "NeoQuasar/Kronos-base"
103
+
104
+
105
+ # Paths to the fine-tuned models, derived from the save_path.
106
+ # These will be generated automatically during training.
107
+ self.finetuned_tokenizer_path = f"{self.save_path}/{self.tokenizer_save_folder_name}/checkpoints/best_model"
108
+ self.finetuned_predictor_path = f"{self.save_path}/{self.predictor_save_folder_name}/checkpoints/best_model"
109
+
110
+ # =================================================================
111
+ # Backtesting Parameters
112
+ # =================================================================
113
+ self.backtest_n_symbol_hold = 5 # Number of symbols to hold in the portfolio.
114
+ self.backtest_n_symbol_drop = 3 # Number of symbols to drop from the pool.
115
+ self.backtest_hold_thresh = 0 # Minimum holding period for a stock.
116
+ self.inference_T = 0.6
117
+ self.inference_top_p = 0.9
118
+ self.inference_top_k = 0
119
+ self.inference_sample_count = 5
120
+ self.backtest_batch_size = 256
121
+ self.backtest_benchmark = self._set_benchmark(self.instrument)
122
+
123
+ def _set_benchmark(self, instrument):
124
+ dt_benchmark = {
125
+ 'csi800': "SH000906",
126
+ 'csi1000': "SH000852",
127
+ 'csi300': "SH000300",
128
+ 'all': "SH000300",
129
+ }
130
+ if instrument in dt_benchmark:
131
+ return dt_benchmark[instrument]
132
+ else:
133
+ raise ValueError(f"Benchmark not defined for instrument: {instrument}")
Kronos/finetune/config.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ class Config:
4
+ """
5
+ Configuration class for the entire project.
6
+ """
7
+
8
+ def __init__(self):
9
+ # =================================================================
10
+ # Data & Feature Parameters
11
+ # =================================================================
12
+ # TODO: Update this path to your Qlib data directory.
13
+ self.qlib_data_path = "~/.qlib/qlib_data/cn_data_local"
14
+ self.instrument = 'all'
15
+
16
+ # Overall time range for data loading from Qlib.
17
+ self.dataset_begin_time = "2021-12-01"
18
+ self.dataset_end_time = '2026-04-05'
19
+
20
+ # Sliding window parameters for creating samples.
21
+ self.lookback_window = 672 # Number of past time steps for input.
22
+ self.predict_window = 49 # Number of future time steps for prediction.
23
+ self.max_context = 512 # Maximum context length for the model.
24
+
25
+ # Features to be used from the raw data.
26
+ self.feature_list = ['open', 'high', 'low', 'close', 'vol', 'amt']
27
+ # Time-based features to be generated.
28
+ self.time_feature_list = ['minute', 'hour', 'weekday', 'day', 'month']
29
+
30
+ # =================================================================
31
+ # Dataset Splitting & Paths
32
+ # =================================================================
33
+ # Note: The validation/test set starts earlier than the training/validation set ends
34
+ # to account for the `lookback_window`.
35
+ self.train_time_range = ["2011-01-01", "2015-12-10"]
36
+ self.val_time_range = ["2015-12-20", "2024-05-10"]
37
+ # Signal dates to retain in qlib_test.py. The source cache starts
38
+ # earlier so the 672-bar warm-up can be discarded before saving.
39
+ self.test_time_range = ["2025-01-01", "2026-04-05"]
40
+ self.backtest_time_range = ["2025-01-01", "2026-04-05"]
41
+
42
+ # TODO: Directory to save the processed, pickled datasets.
43
+ self.dataset_path = "./data/processed_datasets"
44
+ self.test_data_file = "test_data.pkl"
45
+
46
+ # =================================================================
47
+ # Training Hyperparameters
48
+ # =================================================================
49
+ self.clip = 5.0 # Clipping value for normalized data to prevent outliers.
50
+
51
+ self.epochs = 30
52
+ self.log_interval = 100 # Log training status every N batches.
53
+ self.batch_size = 50 # Batch size per GPU.
54
+
55
+ # Number of samples to draw for one "epoch" of training/validation.
56
+ # This is useful for large datasets where a true epoch is too long.
57
+ self.n_train_iter = 2000 * self.batch_size
58
+ self.n_val_iter = 400 * self.batch_size
59
+
60
+ # Learning rates for different model components.
61
+ self.tokenizer_learning_rate = 2e-4
62
+ self.predictor_learning_rate = 4e-5
63
+
64
+ # Gradient accumulation to simulate a larger batch size.
65
+ self.accumulation_steps = 1
66
+
67
+ # AdamW optimizer parameters.
68
+ self.adam_beta1 = 0.9
69
+ self.adam_beta2 = 0.95
70
+ self.adam_weight_decay = 0.1
71
+
72
+ # Miscellaneous
73
+ self.seed = 100 # Global random seed for reproducibility.
74
+
75
+ # =================================================================
76
+ # Experiment Logging & Saving
77
+ # =================================================================
78
+ self.use_comet = False # Set to False if you don't want to use Comet ML
79
+ self.comet_config = {
80
+ # It is highly recommended to load secrets from environment variables
81
+ # for security purposes. Example: os.getenv("COMET_API_KEY")
82
+ "api_key": "YOUR_COMET_API_KEY",
83
+ "project_name": "Kronos-Finetune-Demo",
84
+ "workspace": "your_comet_workspace" # TODO: Change to your Comet ML workspace name
85
+ }
86
+ self.comet_tag = 'finetune_demo'
87
+ self.comet_name = 'finetune_demo'
88
+
89
+ # Base directory for saving model checkpoints and results.
90
+ # Using a general 'outputs' directory is a common practice.
91
+ self.save_path = "./outputs/models"
92
+ self.signal_result_path = "./outputs/predictions"
93
+ self.signal_result_name = "kronos_5min_signals_2022_20260407"
94
+ self.tokenizer_save_folder_name = 'finetune_tokenizer_demo'
95
+ self.predictor_save_folder_name = 'finetune_predictor_demo'
96
+ self.backtest_save_folder_name = 'finetune_backtest_demo'
97
+
98
+ # Path for backtesting results.
99
+ self.backtest_result_path = "./outputs/backtest_results"
100
+
101
+ # =================================================================
102
+ # Model & Checkpoint Paths
103
+ # =================================================================
104
+ # TODO: Update these paths to your pretrained model locations.
105
+ # These can be local paths or Hugging Face Hub model identifiers.
106
+ self.pretrained_tokenizer_path = "NeoQuasar/Kronos-Tokenizer-base"
107
+ self.pretrained_predictor_path = "NeoQuasar/Kronos-base"
108
+
109
+
110
+ # Paths to the fine-tuned models, derived from the save_path.
111
+ # These will be generated automatically during training.
112
+ self.finetuned_tokenizer_path = f"{self.save_path}/{self.tokenizer_save_folder_name}/checkpoints/best_model"
113
+ self.finetuned_predictor_path = f"{self.save_path}/{self.predictor_save_folder_name}/checkpoints/best_model"
114
+
115
+ # =================================================================
116
+ # Backtesting Parameters
117
+ # =================================================================
118
+ self.backtest_n_symbol_hold = 5 # Number of symbols to hold in the portfolio.
119
+ self.backtest_n_symbol_drop = 3 # Number of symbols to drop from the pool.
120
+ self.backtest_hold_thresh = 0 # Minimum holding period for a stock.
121
+ self.inference_T = 0.6
122
+ self.inference_top_p = 0.9
123
+ self.inference_top_k = 0
124
+ self.inference_sample_count = 5
125
+ self.backtest_batch_size = 256
126
+ self.backtest_benchmark = self._set_benchmark(self.instrument)
127
+
128
+ def _set_benchmark(self, instrument):
129
+ dt_benchmark = {
130
+ 'csi800': "SH000906",
131
+ 'csi1000': "SH000852",
132
+ 'csi300': "SH000300",
133
+ 'all': "SH000300",
134
+ }
135
+ if instrument in dt_benchmark:
136
+ return dt_benchmark[instrument]
137
+ else:
138
+ raise ValueError(f"Benchmark not defined for instrument: {instrument}")
Kronos/finetune/data/processed_datasets/test_data.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04e47eb6e1968c2cc1ec9d4ea2c84ad0dc9b83bd1687153ef198c8679381d730
3
+ size 4449693687
Kronos/finetune/dataset.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ import random
3
+ import numpy as np
4
+ import torch
5
+ from torch.utils.data import Dataset
6
+ from config import Config
7
+
8
+
9
+ class QlibDataset(Dataset):
10
+ """
11
+ A PyTorch Dataset for handling Qlib financial time series data.
12
+
13
+ This dataset pre-computes all possible start indices for sliding windows
14
+ and then randomly samples from them during training/validation.
15
+
16
+ Args:
17
+ data_type (str): The type of dataset to load, either 'train' or 'val'.
18
+
19
+ Raises:
20
+ ValueError: If `data_type` is not 'train' or 'val'.
21
+ """
22
+
23
+ def __init__(self, data_type: str = 'train'):
24
+ self.config = Config()
25
+ if data_type not in ['train', 'val']:
26
+ raise ValueError("data_type must be 'train' or 'val'")
27
+ self.data_type = data_type
28
+
29
+ # Use a dedicated random number generator for sampling to avoid
30
+ # interfering with other random processes (e.g., in model initialization).
31
+ self.py_rng = random.Random(self.config.seed)
32
+
33
+ # Set paths and number of samples based on the data type.
34
+ if data_type == 'train':
35
+ self.data_path = f"{self.config.dataset_path}/train_data.pkl"
36
+ self.n_samples = self.config.n_train_iter
37
+ else:
38
+ self.data_path = f"{self.config.dataset_path}/val_data.pkl"
39
+ self.n_samples = self.config.n_val_iter
40
+
41
+ with open(self.data_path, 'rb') as f:
42
+ self.data = pickle.load(f)
43
+
44
+ self.window = self.config.lookback_window + self.config.predict_window + 1
45
+
46
+ self.symbols = list(self.data.keys())
47
+ self.feature_list = self.config.feature_list
48
+ self.time_feature_list = self.config.time_feature_list
49
+
50
+ # Pre-compute all possible (symbol, start_index) pairs.
51
+ self.indices = []
52
+ print(f"[{data_type.upper()}] Pre-computing sample indices...")
53
+ for symbol in self.symbols:
54
+ df = self.data[symbol].reset_index()
55
+ series_len = len(df)
56
+ num_samples = series_len - self.window + 1
57
+
58
+ if num_samples > 0:
59
+ # Generate time features and store them directly in the dataframe.
60
+ df['minute'] = df['datetime'].dt.minute
61
+ df['hour'] = df['datetime'].dt.hour
62
+ df['weekday'] = df['datetime'].dt.weekday
63
+ df['day'] = df['datetime'].dt.day
64
+ df['month'] = df['datetime'].dt.month
65
+ # Keep only necessary columns to save memory.
66
+ self.data[symbol] = df[self.feature_list + self.time_feature_list]
67
+
68
+ # Add all valid starting indices for this symbol to the global list.
69
+ for i in range(num_samples):
70
+ self.indices.append((symbol, i))
71
+
72
+ # The effective dataset size is the minimum of the configured iterations
73
+ # and the total number of available samples.
74
+ self.n_samples = min(self.n_samples, len(self.indices))
75
+ print(f"[{data_type.upper()}] Found {len(self.indices)} possible samples. Using {self.n_samples} per epoch.")
76
+
77
+ def set_epoch_seed(self, epoch: int):
78
+ """
79
+ Sets a new seed for the random sampler for each epoch. This is crucial
80
+ for reproducibility in distributed training.
81
+
82
+ Args:
83
+ epoch (int): The current epoch number.
84
+ """
85
+ epoch_seed = self.config.seed + epoch
86
+ self.py_rng.seed(epoch_seed)
87
+
88
+ def __len__(self) -> int:
89
+ """Returns the number of samples per epoch."""
90
+ return self.n_samples
91
+
92
+ def __getitem__(self, idx: int) -> tuple[torch.Tensor, torch.Tensor]:
93
+
94
+ # Select a random sample from the entire pool of indices.
95
+ random_idx = self.py_rng.randint(0, len(self.indices) - 1)
96
+ symbol, start_idx = self.indices[random_idx]
97
+
98
+ # Extract the sliding window from the dataframe.
99
+ df = self.data[symbol]
100
+ end_idx = start_idx + self.window
101
+ win_df = df.iloc[start_idx:end_idx]
102
+
103
+ # Separate main features and time features.
104
+ x = win_df[self.feature_list].values.astype(np.float32)
105
+ x_stamp = win_df[self.time_feature_list].values.astype(np.float32)
106
+
107
+ # Normalize the window. Mean and std are calculated strictly on the
108
+ # lookback window (past data) to prevent future data leakage.
109
+ past_len = self.config.lookback_window
110
+ past_x = x[:past_len]
111
+
112
+ x_mean = np.mean(past_x, axis=0)
113
+ x_std = np.std(past_x, axis=0)
114
+
115
+ # Apply normalization and robust clipping to the entire sequence
116
+ x = (x - x_mean) / (x_std + 1e-5)
117
+ x = np.clip(x, -self.config.clip, self.config.clip)
118
+
119
+ # Convert to PyTorch tensors.
120
+ x_tensor = torch.from_numpy(x)
121
+ x_stamp_tensor = torch.from_numpy(x_stamp)
122
+
123
+ return x_tensor, x_stamp_tensor
124
+
125
+
126
+ if __name__ == '__main__':
127
+ # Example usage and verification.
128
+ print("Creating training dataset instance...")
129
+ train_dataset = QlibDataset(data_type='train')
130
+
131
+ print(f"Dataset length: {len(train_dataset)}")
132
+
133
+ if len(train_dataset) > 0:
134
+ try_x, try_x_stamp = train_dataset[100] # Index 100 is ignored.
135
+ print(f"Sample feature shape: {try_x.shape}")
136
+ print(f"Sample time feature shape: {try_x_stamp.shape}")
137
+ else:
138
+ print("Dataset is empty.")
Kronos/finetune/merge_predictions.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ import pickle
5
+ from collections import defaultdict
6
+
7
+ import pandas as pd
8
+
9
+
10
+ EXPECTED_SIGNALS = ("cc", "oc", "oo2")
11
+
12
+
13
+ def atomic_pickle_dump(value, path):
14
+ """Write a pickle atomically."""
15
+ parent = os.path.dirname(path)
16
+ if parent:
17
+ os.makedirs(parent, exist_ok=True)
18
+
19
+ tmp_path = f"{path}.tmp.{os.getpid()}"
20
+ try:
21
+ with open(tmp_path, "wb") as f:
22
+ pickle.dump(value, f, protocol=pickle.HIGHEST_PROTOCOL)
23
+ f.flush()
24
+ os.fsync(f.fileno())
25
+ os.replace(tmp_path, path)
26
+ finally:
27
+ if os.path.exists(tmp_path):
28
+ os.unlink(tmp_path)
29
+
30
+
31
+ def atomic_json_dump(value, path):
32
+ """Write JSON atomically."""
33
+ parent = os.path.dirname(path)
34
+ if parent:
35
+ os.makedirs(parent, exist_ok=True)
36
+
37
+ tmp_path = f"{path}.tmp.{os.getpid()}"
38
+ try:
39
+ with open(tmp_path, "w", encoding="utf-8") as f:
40
+ json.dump(value, f, ensure_ascii=False, indent=2)
41
+ f.flush()
42
+ os.fsync(f.fileno())
43
+ os.replace(tmp_path, path)
44
+ finally:
45
+ if os.path.exists(tmp_path):
46
+ os.unlink(tmp_path)
47
+
48
+
49
+ def atomic_csv_dump(dataframe, path):
50
+ """Write a CSV atomically."""
51
+ parent = os.path.dirname(path)
52
+ if parent:
53
+ os.makedirs(parent, exist_ok=True)
54
+
55
+ tmp_path = f"{path}.tmp.{os.getpid()}"
56
+ try:
57
+ dataframe.to_csv(tmp_path, index=False)
58
+ os.replace(tmp_path, path)
59
+ finally:
60
+ if os.path.exists(tmp_path):
61
+ os.unlink(tmp_path)
62
+
63
+
64
+ def load_json(path):
65
+ with open(path, "r", encoding="utf-8") as f:
66
+ return json.load(f)
67
+
68
+
69
+ def expected_rank_sample_count(full_size, rank, world_size):
70
+ """Number of items in range(rank, full_size, world_size)."""
71
+ if rank >= full_size:
72
+ return 0
73
+ return (full_size - 1 - rank) // world_size + 1
74
+
75
+
76
+ def validate_and_load_manifests(
77
+ shard_dir,
78
+ expected_world_size,
79
+ ):
80
+ manifests = []
81
+
82
+ for rank in range(expected_world_size):
83
+ manifest_path = os.path.join(
84
+ shard_dir,
85
+ f"rank_{rank:04d}.done.json",
86
+ )
87
+ if not os.path.isfile(manifest_path):
88
+ raise RuntimeError(
89
+ f"Rank {rank} is incomplete: missing {manifest_path}"
90
+ )
91
+
92
+ manifest = load_json(manifest_path)
93
+
94
+ if manifest.get("rank") != rank:
95
+ raise RuntimeError(
96
+ f"{manifest_path}: expected rank {rank}, "
97
+ f"got {manifest.get('rank')}"
98
+ )
99
+ if manifest.get("world_size") != expected_world_size:
100
+ raise RuntimeError(
101
+ f"{manifest_path}: expected world_size "
102
+ f"{expected_world_size}, "
103
+ f"got {manifest.get('world_size')}"
104
+ )
105
+ if tuple(manifest.get("signals", [])) != EXPECTED_SIGNALS:
106
+ raise RuntimeError(
107
+ f"{manifest_path}: unexpected signals "
108
+ f"{manifest.get('signals')}"
109
+ )
110
+
111
+ manifests.append(manifest)
112
+
113
+ run_ids = {manifest.get("run_id") for manifest in manifests}
114
+ if len(run_ids) != 1:
115
+ raise RuntimeError(
116
+ f"Manifests belong to different runs: {run_ids}"
117
+ )
118
+
119
+ full_sizes = {
120
+ manifest.get("full_dataset_size")
121
+ for manifest in manifests
122
+ }
123
+ if len(full_sizes) != 1 or None in full_sizes:
124
+ raise RuntimeError(
125
+ f"Inconsistent full_dataset_size values: {full_sizes}"
126
+ )
127
+
128
+ full_dataset_size = next(iter(full_sizes))
129
+
130
+ for manifest in manifests:
131
+ rank = manifest["rank"]
132
+ assigned = expected_rank_sample_count(
133
+ full_dataset_size,
134
+ rank,
135
+ expected_world_size,
136
+ )
137
+ if manifest.get("num_samples") != assigned:
138
+ raise RuntimeError(
139
+ f"Rank {rank}: manifest contains "
140
+ f"{manifest.get('num_samples')} samples, "
141
+ f"but deterministic partitioning assigns {assigned}"
142
+ )
143
+
144
+ total_samples = sum(
145
+ manifest["num_samples"]
146
+ for manifest in manifests
147
+ )
148
+ if total_samples != full_dataset_size:
149
+ raise RuntimeError(
150
+ f"Sample coverage mismatch: manifests contain "
151
+ f"{total_samples} samples, but the full dataset has "
152
+ f"{full_dataset_size}"
153
+ )
154
+
155
+ return manifests, run_ids.pop(), full_dataset_size
156
+
157
+
158
+ def load_all_shards(shard_dir, manifests):
159
+ merged = defaultdict(list)
160
+
161
+ for manifest in manifests:
162
+ rank = manifest["rank"]
163
+ rank_record_counts = defaultdict(int)
164
+
165
+ for part_index in range(manifest["parts"]):
166
+ part_path = os.path.join(
167
+ shard_dir,
168
+ f"rank_{rank:04d}_part_{part_index:06d}.pkl",
169
+ )
170
+ if not os.path.isfile(part_path):
171
+ raise RuntimeError(
172
+ f"Rank {rank} is missing shard part: {part_path}"
173
+ )
174
+
175
+ with open(part_path, "rb") as f:
176
+ part_result = pickle.load(f)
177
+
178
+ unexpected = set(part_result) - set(EXPECTED_SIGNALS)
179
+ if unexpected:
180
+ raise RuntimeError(
181
+ f"{part_path}: unexpected signals {unexpected}"
182
+ )
183
+
184
+ for signal_name, records in part_result.items():
185
+ merged[signal_name].extend(records)
186
+ rank_record_counts[signal_name] += len(records)
187
+
188
+ for signal_name in EXPECTED_SIGNALS:
189
+ actual = rank_record_counts[signal_name]
190
+ expected = manifest["num_samples"]
191
+ if actual != expected:
192
+ raise RuntimeError(
193
+ f"Rank {rank}, signal {signal_name}: loaded "
194
+ f"{actual} records, expected {expected}"
195
+ )
196
+
197
+ print(
198
+ f"Loaded rank {rank:04d}: "
199
+ f"{manifest['num_samples']} samples from "
200
+ f"{manifest['parts']} part(s)"
201
+ )
202
+
203
+ return merged
204
+
205
+
206
+ def records_to_prediction_dataframes(
207
+ merged,
208
+ full_dataset_size,
209
+ ):
210
+ prediction_dfs = {}
211
+
212
+ for signal_name in EXPECTED_SIGNALS:
213
+ records = merged.get(signal_name, [])
214
+
215
+ if len(records) != full_dataset_size:
216
+ raise RuntimeError(
217
+ f"{signal_name}: loaded {len(records)} records, "
218
+ f"expected {full_dataset_size}"
219
+ )
220
+
221
+ frame = pd.DataFrame(
222
+ records,
223
+ columns=["datetime", "instrument", "score"],
224
+ )
225
+ frame["datetime"] = pd.to_datetime(frame["datetime"])
226
+
227
+ duplicate_mask = frame.duplicated(
228
+ subset=["datetime", "instrument"],
229
+ keep=False,
230
+ )
231
+ if duplicate_mask.any():
232
+ duplicate_examples = frame.loc[
233
+ duplicate_mask,
234
+ ["datetime", "instrument"],
235
+ ].head(10)
236
+ raise RuntimeError(
237
+ f"{signal_name}: found "
238
+ f"{int(duplicate_mask.sum())} duplicated "
239
+ f"(datetime, instrument) rows. Examples:\n"
240
+ f"{duplicate_examples.to_string(index=False)}"
241
+ )
242
+
243
+ # pivot, rather than pivot_table, ensures duplicates can never be
244
+ # silently averaged.
245
+ prediction_dfs[signal_name] = (
246
+ frame
247
+ .pivot(
248
+ index="datetime",
249
+ columns="instrument",
250
+ values="score",
251
+ )
252
+ .sort_index()
253
+ .sort_index(axis=1)
254
+ )
255
+
256
+ return prediction_dfs
257
+
258
+
259
+ def save_outputs(
260
+ prediction_dfs,
261
+ save_dir,
262
+ shard_dir,
263
+ run_id,
264
+ world_size,
265
+ full_dataset_size,
266
+ ):
267
+ os.makedirs(save_dir, exist_ok=True)
268
+
269
+ predictions_path = os.path.join(
270
+ save_dir,
271
+ "predictions.pkl",
272
+ )
273
+ atomic_pickle_dump(prediction_dfs, predictions_path)
274
+ print(f"Saved complete predictions: {predictions_path}")
275
+
276
+ valid_row_counts = {}
277
+ for signal_name, prediction_df in prediction_dfs.items():
278
+ long_df = (
279
+ prediction_df
280
+ .rename_axis("signal_date", axis="index")
281
+ .rename_axis("code", axis="columns")
282
+ .reset_index()
283
+ .melt(
284
+ id_vars="signal_date",
285
+ var_name="code",
286
+ value_name="pred",
287
+ )
288
+ .dropna(subset=["pred"])
289
+ .sort_values(["signal_date", "code"])
290
+ .reset_index(drop=True)
291
+ )
292
+
293
+ long_path = os.path.join(
294
+ save_dir,
295
+ f"signals_{signal_name}.csv",
296
+ )
297
+ atomic_csv_dump(long_df, long_path)
298
+ valid_row_counts[signal_name] = len(long_df)
299
+ print(
300
+ f"Saved {signal_name}: {len(long_df)} valid rows -> "
301
+ f"{long_path}"
302
+ )
303
+
304
+ all_dates = [
305
+ pd.Timestamp(date)
306
+ for prediction_df in prediction_dfs.values()
307
+ for date in prediction_df.index
308
+ ]
309
+
310
+ source_metadata_path = os.path.join(
311
+ shard_dir,
312
+ "run_metadata.json",
313
+ )
314
+ source_metadata = (
315
+ load_json(source_metadata_path)
316
+ if os.path.isfile(source_metadata_path)
317
+ else {}
318
+ )
319
+
320
+ metadata = {
321
+ **source_metadata,
322
+ "run_id": run_id,
323
+ "world_size": world_size,
324
+ "shard_dir": os.path.abspath(shard_dir),
325
+ "full_dataset_size": full_dataset_size,
326
+ "signals": list(EXPECTED_SIGNALS),
327
+ "valid_rows": valid_row_counts,
328
+ "actual_signal_start": (
329
+ min(all_dates).strftime("%Y-%m-%d")
330
+ if all_dates
331
+ else None
332
+ ),
333
+ "actual_signal_end": (
334
+ max(all_dates).strftime("%Y-%m-%d")
335
+ if all_dates
336
+ else None
337
+ ),
338
+ "label_or_metrics_generated": False,
339
+ "qlib_backtest_generated": False,
340
+ }
341
+
342
+ metadata_path = os.path.join(
343
+ save_dir,
344
+ "prediction_metadata.json",
345
+ )
346
+ atomic_json_dump(metadata, metadata_path)
347
+ print(f"Saved metadata: {metadata_path}")
348
+
349
+
350
+ def merge_predictions(
351
+ shard_dir,
352
+ save_dir,
353
+ expected_world_size,
354
+ ):
355
+ shard_dir = os.path.abspath(shard_dir)
356
+ save_dir = os.path.abspath(save_dir)
357
+
358
+ if not os.path.isdir(shard_dir):
359
+ raise FileNotFoundError(
360
+ f"Shard directory does not exist: {shard_dir}"
361
+ )
362
+
363
+ manifests, run_id, full_dataset_size = (
364
+ validate_and_load_manifests(
365
+ shard_dir,
366
+ expected_world_size,
367
+ )
368
+ )
369
+
370
+ print(
371
+ f"Validated run {run_id}: {expected_world_size} rank(s), "
372
+ f"{full_dataset_size} total samples"
373
+ )
374
+
375
+ merged = load_all_shards(shard_dir, manifests)
376
+ prediction_dfs = records_to_prediction_dataframes(
377
+ merged,
378
+ full_dataset_size,
379
+ )
380
+ save_outputs(
381
+ prediction_dfs,
382
+ save_dir,
383
+ shard_dir,
384
+ run_id,
385
+ expected_world_size,
386
+ full_dataset_size,
387
+ )
388
+
389
+ print("Merge completed successfully.")
390
+
391
+
392
+ def build_argument_parser():
393
+ parser = argparse.ArgumentParser(
394
+ description=(
395
+ "Validate and merge distributed Kronos prediction shards."
396
+ )
397
+ )
398
+ parser.add_argument(
399
+ "--shard-dir",
400
+ required=True,
401
+ help="Directory containing rank_XXXX_part_XXXXXX.pkl files.",
402
+ )
403
+ parser.add_argument(
404
+ "--save-dir",
405
+ required=True,
406
+ help="Directory for predictions.pkl and signals_*.csv.",
407
+ )
408
+ parser.add_argument(
409
+ "--world-size",
410
+ type=int,
411
+ required=True,
412
+ help="Total number of ranks used by the inference run.",
413
+ )
414
+ return parser
415
+
416
+
417
+ def main():
418
+ args = build_argument_parser().parse_args()
419
+
420
+ if args.world_size <= 0:
421
+ raise ValueError("--world-size must be positive")
422
+
423
+ merge_predictions(
424
+ shard_dir=args.shard_dir,
425
+ save_dir=args.save_dir,
426
+ expected_world_size=args.world_size,
427
+ )
428
+
429
+
430
+ if __name__ == "__main__":
431
+ main()
Kronos/finetune/outputs/backtest_results/finetune_backtest_demo/predictions.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2d947b7221a569bd2b8bb05a5ff2bf8786300d40541ac9f9a0633a8d4f89d5c0
3
+ size 25311074
Kronos/finetune/qlib_data_preprocess.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+ import numpy as np
4
+ import pandas as pd
5
+ import qlib
6
+ from qlib.config import REG_CN
7
+ from qlib.data import D
8
+ from qlib.data.dataset.loader import QlibDataLoader
9
+ from tqdm import trange
10
+
11
+ from config import Config
12
+
13
+
14
+ class QlibDataPreprocessor:
15
+ """
16
+ A class to handle the loading, processing, and splitting of Qlib financial data.
17
+ """
18
+
19
+ def __init__(self):
20
+ """Initializes the preprocessor with configuration and data fields."""
21
+ self.config = Config()
22
+ self.data_fields = ['open', 'close', 'high', 'low', 'volume', 'vwap']
23
+ self.data = {} # A dictionary to store processed data for each symbol.
24
+
25
+ def initialize_qlib(self):
26
+ """Initializes the Qlib environment."""
27
+ print("Initializing Qlib...")
28
+ qlib.init(provider_uri=self.config.qlib_data_path, region=REG_CN)
29
+
30
+ def load_qlib_data(self):
31
+ """
32
+ Loads raw data from Qlib, processes it symbol by symbol, and stores
33
+ it in the `self.data` attribute.
34
+ """
35
+ print("Loading and processing data from Qlib...")
36
+ data_fields_qlib = ['$' + f for f in self.data_fields]
37
+ cal: np.ndarray = D.calendar()
38
+
39
+ # Determine the actual start and end times to load, including buffer for lookback and predict windows.
40
+ start_index = cal.searchsorted(pd.Timestamp(self.config.dataset_begin_time))
41
+ end_index = cal.searchsorted(pd.Timestamp(self.config.dataset_end_time))
42
+
43
+ # Check if start_index lookbackw_window will cause negative index
44
+ adjusted_start_index = max(start_index - self.config.lookback_window, 0)
45
+ real_start_time = cal[adjusted_start_index]
46
+
47
+ # Check if end_index exceeds the range of the array
48
+ if end_index >= len(cal):
49
+ end_index = len(cal) - 1
50
+ elif cal[end_index] != pd.Timestamp(self.config.dataset_end_time):
51
+ end_index -= 1
52
+
53
+ # Check if end_index+predictw_window will exceed the range of the array
54
+ adjusted_end_index = min(end_index + self.config.predict_window, len(cal) - 1)
55
+ real_end_time = cal[adjusted_end_index]
56
+
57
+ # Load data using Qlib's data loader.
58
+ data_df = QlibDataLoader(config=data_fields_qlib).load(
59
+ self.config.instrument, real_start_time, real_end_time
60
+ )
61
+ data_df = data_df.stack().unstack(level=1) # Reshape for easier access.
62
+
63
+ symbol_list = list(data_df.columns)
64
+ for i in trange(len(symbol_list), desc="Processing Symbols"):
65
+ symbol = symbol_list[i]
66
+ symbol_df = data_df[symbol]
67
+
68
+ # Pivot the table to have features as columns and datetime as index.
69
+ symbol_df = symbol_df.reset_index().rename(columns={'level_1': 'field'})
70
+ symbol_df = pd.pivot(symbol_df, index='datetime', columns='field', values=symbol)
71
+ symbol_df = symbol_df.rename(columns={f'${field}': field for field in self.data_fields})
72
+
73
+ # Calculate amount and select final features.
74
+ symbol_df['vol'] = symbol_df['volume']
75
+ symbol_df['amt'] = (symbol_df['open'] + symbol_df['high'] + symbol_df['low'] + symbol_df['close']) / 4 * symbol_df['vol']
76
+ symbol_df = symbol_df[self.config.feature_list]
77
+
78
+ # Filter out symbols with insufficient data.
79
+ symbol_df = symbol_df.dropna()
80
+ if len(symbol_df) < self.config.lookback_window + self.config.predict_window + 1:
81
+ continue
82
+
83
+ self.data[symbol] = symbol_df
84
+
85
+ def prepare_dataset(self):
86
+ """
87
+ Splits the loaded data into train, validation, and test sets and saves them to disk.
88
+ """
89
+ print("Splitting data into train, validation, and test sets...")
90
+ train_data, val_data, test_data = {}, {}, {}
91
+
92
+ symbol_list = list(self.data.keys())
93
+ for i in trange(len(symbol_list), desc="Preparing Datasets"):
94
+ symbol = symbol_list[i]
95
+ symbol_df = self.data[symbol]
96
+
97
+ # Define time ranges from config.
98
+ train_start, train_end = self.config.train_time_range
99
+ val_start, val_end = self.config.val_time_range
100
+ test_start, test_end = self.config.test_time_range
101
+
102
+ # Create boolean masks for each dataset split.
103
+ train_mask = (symbol_df.index >= train_start) & (symbol_df.index <= train_end)
104
+ val_mask = (symbol_df.index >= val_start) & (symbol_df.index <= val_end)
105
+ test_mask = (symbol_df.index >= test_start) & (symbol_df.index <= test_end)
106
+
107
+ # Apply masks to create the final datasets.
108
+ train_data[symbol] = symbol_df[train_mask]
109
+ val_data[symbol] = symbol_df[val_mask]
110
+ test_data[symbol] = symbol_df[test_mask]
111
+
112
+ # Save the datasets using pickle.
113
+ os.makedirs(self.config.dataset_path, exist_ok=True)
114
+ with open(f"{self.config.dataset_path}/train_data.pkl", 'wb') as f:
115
+ pickle.dump(train_data, f)
116
+ with open(f"{self.config.dataset_path}/val_data.pkl", 'wb') as f:
117
+ pickle.dump(val_data, f)
118
+ with open(f"{self.config.dataset_path}/test_data.pkl", 'wb') as f:
119
+ pickle.dump(test_data, f)
120
+
121
+ print("Datasets prepared and saved successfully.")
122
+
123
+
124
+ if __name__ == '__main__':
125
+ # This block allows the script to be run directly to perform data preprocessing.
126
+ preprocessor = QlibDataPreprocessor()
127
+ preprocessor.initialize_qlib()
128
+ preprocessor.load_qlib_data()
129
+ preprocessor.prepare_dataset()
130
+
Kronos/finetune/qlib_test copy.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import argparse
4
+ import pickle
5
+ from collections import defaultdict
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ import torch
10
+ import torch.distributed as dist
11
+ from torch.utils.data import Dataset, DataLoader, Subset
12
+ from tqdm import trange, tqdm
13
+ from matplotlib import pyplot as plt
14
+
15
+ import qlib
16
+ from qlib.config import REG_CN
17
+ from qlib.backtest import backtest, executor, CommonInfrastructure
18
+ from qlib.contrib.evaluate import risk_analysis
19
+ from qlib.contrib.strategy import TopkDropoutStrategy
20
+ from qlib.utils import flatten_dict
21
+ from qlib.utils.time import Freq
22
+
23
+ # Ensure project root is in the Python path
24
+ sys.path.append("../")
25
+ from config import Config
26
+ from model.kronos import Kronos, KronosTokenizer, auto_regressive_inference
27
+ from utils.training_utils import setup_ddp, cleanup_ddp
28
+
29
+
30
+ # =================================================================================
31
+ # 1. Data Loading and Processing for Inference
32
+ # =================================================================================
33
+
34
+ class QlibTestDataset(Dataset):
35
+ """
36
+ PyTorch Dataset for handling Qlib test data, specifically for inference.
37
+
38
+ This dataset iterates through all possible sliding windows sequentially. It also
39
+ yields metadata like symbol and timestamp, which are crucial for mapping
40
+ predictions back to the original time series.
41
+ """
42
+
43
+ def __init__(self, data: dict, config: Config):
44
+ self.data = data
45
+ self.config = config
46
+ self.window_size = config.lookback_window + config.predict_window
47
+ self.symbols = list(self.data.keys())
48
+ self.feature_list = config.feature_list
49
+ self.time_feature_list = config.time_feature_list
50
+ self.indices = []
51
+
52
+ print("Preprocessing and building indices for test dataset...")
53
+ for symbol in self.symbols:
54
+ df = self.data[symbol].reset_index()
55
+ # Generate time features on-the-fly
56
+ df['minute'] = df['datetime'].dt.minute
57
+ df['hour'] = df['datetime'].dt.hour
58
+ df['weekday'] = df['datetime'].dt.weekday
59
+ df['day'] = df['datetime'].dt.day
60
+ df['month'] = df['datetime'].dt.month
61
+ self.data[symbol] = df # Store preprocessed dataframe
62
+
63
+ num_samples = len(df) - self.window_size + 1
64
+ if num_samples > 0:
65
+ for i in range(0, num_samples, 48):
66
+ timestamp = df.iloc[i + self.config.lookback_window - 1]['datetime']
67
+ self.indices.append((symbol, i, timestamp))
68
+
69
+ def __len__(self) -> int:
70
+ return len(self.indices)
71
+
72
+ def __getitem__(self, idx: int):
73
+ symbol, start_idx, timestamp = self.indices[idx]
74
+ df = self.data[symbol]
75
+
76
+ context_end = start_idx + self.config.lookback_window
77
+ predict_end = context_end + self.config.predict_window
78
+
79
+ context_df = df.iloc[start_idx:context_end]
80
+ predict_df = df.iloc[context_end:predict_end]
81
+
82
+ x = context_df[self.feature_list].values.astype(np.float32)
83
+ x_stamp = context_df[self.time_feature_list].values.astype(np.float32)
84
+ y_stamp = predict_df[self.time_feature_list].values.astype(np.float32)
85
+
86
+ # Instance-level normalization, consistent with training
87
+ x_mean, x_std = np.mean(x, axis=0), np.std(x, axis=0)
88
+ x = (x - x_mean) / (x_std + 1e-5)
89
+ x = np.clip(x, -self.config.clip, self.config.clip)
90
+
91
+ return torch.from_numpy(x), torch.from_numpy(x_stamp), torch.from_numpy(y_stamp), symbol, timestamp
92
+
93
+
94
+ # =================================================================================
95
+ # 2. Backtesting Logic
96
+ # =================================================================================
97
+
98
+ class QlibBacktest:
99
+ """
100
+ A wrapper class for conducting backtesting experiments using Qlib.
101
+ """
102
+
103
+ def __init__(self, config: Config):
104
+ self.config = config
105
+ self.initialize_qlib()
106
+
107
+ def initialize_qlib(self):
108
+ """Initializes the Qlib environment."""
109
+ print("Initializing Qlib for backtesting...")
110
+ qlib.init(provider_uri=self.config.qlib_data_path, region=REG_CN)
111
+
112
+ def run_single_backtest(self, signal_series: pd.Series):
113
+ """
114
+ Runs a single backtest for a given prediction signal.
115
+
116
+ Returns:
117
+ tuple: (report_df, analysis, bench_analysis)
118
+ """
119
+ strategy = TopkDropoutStrategy(
120
+ topk=self.config.backtest_n_symbol_hold,
121
+ n_drop=self.config.backtest_n_symbol_drop,
122
+ hold_thresh=self.config.backtest_hold_thresh,
123
+ signal=signal_series,
124
+ )
125
+ executor_config = {
126
+ "time_per_step": "day",
127
+ "generate_portfolio_metrics": True,
128
+ "delay_execution": True,
129
+ }
130
+ backtest_config = {
131
+ "start_time": self.config.backtest_time_range[0],
132
+ "end_time": self.config.backtest_time_range[1],
133
+ "account": 100_000_000,
134
+ "benchmark": self.config.backtest_benchmark,
135
+ "exchange_kwargs": {
136
+ "freq": "day", "limit_threshold": 0.095, "deal_price": "open",
137
+ "open_cost": 0.001, "close_cost": 0.0015, "min_cost": 5,
138
+ },
139
+ "executor": executor.SimulatorExecutor(**executor_config),
140
+ }
141
+
142
+ portfolio_metric_dict, _ = backtest(strategy=strategy, **backtest_config)
143
+ analysis_freq = "{0}{1}".format(*Freq.parse("day"))
144
+ report, _ = portfolio_metric_dict.get(analysis_freq)
145
+
146
+ bench_analysis = risk_analysis(report["bench"], freq=analysis_freq)
147
+ analysis = {
148
+ "excess_return_without_cost": risk_analysis(report["return"] - report["bench"], freq=analysis_freq),
149
+ "excess_return_with_cost": risk_analysis(report["return"] - report["bench"] - report["cost"], freq=analysis_freq),
150
+ }
151
+ print("\n--- Backtest Analysis ---")
152
+ print("Benchmark Return:", bench_analysis, sep='\n')
153
+ print("\nExcess Return (w/o cost):", analysis["excess_return_without_cost"], sep='\n')
154
+ print("\nExcess Return (w/ cost):", analysis["excess_return_with_cost"], sep='\n')
155
+
156
+ report_df = pd.DataFrame({
157
+ "cum_bench": report["bench"].cumsum(),
158
+ "cum_return_w_cost": (report["return"] - report["cost"]).cumsum(),
159
+ "cum_ex_return_w_cost": (report["return"] - report["bench"] - report["cost"]).cumsum(),
160
+ })
161
+ return report_df, analysis, bench_analysis
162
+
163
+ def run_and_plot_results(self, signals: dict, save_dir: str = None):
164
+ """
165
+ Runs backtests for multiple signals, plots cumulative return curves,
166
+ and saves metrics + curves to files if save_dir is provided.
167
+ """
168
+ import datetime
169
+ return_df, ex_return_df, bench_df = pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
170
+ all_analysis = {}
171
+
172
+ for signal_name, pred_df in signals.items():
173
+ print(f"\nBacktesting signal: {signal_name}...")
174
+ pred_series = pred_df.stack()
175
+ pred_series.index.names = ['datetime', 'instrument']
176
+ pred_series = pred_series.swaplevel().sort_index()
177
+ report_df, analysis, bench_analysis = self.run_single_backtest(pred_series)
178
+
179
+ return_df[signal_name] = report_df['cum_return_w_cost']
180
+ ex_return_df[signal_name] = report_df['cum_ex_return_w_cost']
181
+ if 'return' not in bench_df:
182
+ bench_df['return'] = report_df['cum_bench']
183
+ all_analysis[signal_name] = {'analysis': analysis, 'bench_analysis': bench_analysis}
184
+
185
+ # Plotting results
186
+ fig, axes = plt.subplots(2, 1, figsize=(12, 8), sharex=True)
187
+ return_df.plot(ax=axes[0], title='Cumulative Return with Cost', grid=True)
188
+ axes[0].plot(bench_df['return'], label=self.config.instrument.upper(), color='black', linestyle='--')
189
+ axes[0].legend()
190
+ axes[0].set_ylabel("Cumulative Return")
191
+
192
+ ex_return_df.plot(ax=axes[1], title='Cumulative Excess Return with Cost', grid=True)
193
+ axes[1].legend()
194
+ axes[1].set_xlabel("Date")
195
+ axes[1].set_ylabel("Cumulative Excess Return")
196
+
197
+ plt.tight_layout()
198
+
199
+ if save_dir:
200
+ os.makedirs(save_dir, exist_ok=True)
201
+
202
+ # Save plot
203
+ plot_path = os.path.join(save_dir, "backtest_curves.png")
204
+ plt.savefig(plot_path, dpi=200)
205
+ print(f"Plot saved to {plot_path}")
206
+
207
+ # Save cumulative return curves as CSV
208
+ curves_df = pd.concat([bench_df, return_df, ex_return_df], axis=1)
209
+ curves_df.columns = (
210
+ ['bench_cumret'] +
211
+ [f'{s}_cumret' for s in return_df.columns] +
212
+ [f'{s}_cum_exret' for s in ex_return_df.columns]
213
+ )
214
+ curves_path = os.path.join(save_dir, "backtest_curves.csv")
215
+ curves_df.to_csv(curves_path)
216
+ print(f"Curves saved to {curves_path}")
217
+
218
+ # Save metrics summary as text
219
+ summary_path = os.path.join(save_dir, "backtest_summary.txt")
220
+ with open(summary_path, 'w') as f:
221
+ f.write(f"Generated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
222
+ f.write(f"Backtest Period: {self.config.backtest_time_range[0]} ~ {self.config.backtest_time_range[1]}\n")
223
+ f.write(f"Hold Top-K: {self.config.backtest_n_symbol_hold}, Drop: {self.config.backtest_n_symbol_drop}\n\n")
224
+ for signal_name, data in all_analysis.items():
225
+ f.write(f"{'='*50}\n")
226
+ f.write(f"Signal: {signal_name}\n")
227
+ f.write(f"{'='*50}\n")
228
+ f.write("Benchmark:\n")
229
+ f.write(data['bench_analysis'].to_string())
230
+ f.write("\n\nExcess Return (w/o cost):\n")
231
+ f.write(data['analysis']['excess_return_without_cost'].to_string())
232
+ f.write("\n\nExcess Return (w/ cost):\n")
233
+ f.write(data['analysis']['excess_return_with_cost'].to_string())
234
+ f.write("\n\n")
235
+ print(f"Summary saved to {summary_path}")
236
+
237
+ else:
238
+ plt.savefig("../figures/backtest_result_example.png", dpi=200)
239
+
240
+ plt.show()
241
+
242
+
243
+ # =================================================================================
244
+ # 3. Inference Logic
245
+ # =================================================================================
246
+
247
+ def load_models(device: torch.device) -> tuple[KronosTokenizer, Kronos]:
248
+ """Loads the fine-tuned tokenizer and predictor model."""
249
+ print(f"Loading models onto device: {device}...")
250
+ # tokenizer = KronosTokenizer.from_pretrained(config['tokenizer_path']).to(device).eval()
251
+ # model = Kronos.from_pretrained(config['model_path']).to(device).eval()
252
+ tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base").to(device).to(torch.bfloat16).eval()
253
+ model = Kronos.from_pretrained("NeoQuasar/Kronos-base").to(device).to(torch.bfloat16).eval()
254
+ # model = torch.compile(model)
255
+ return tokenizer, model
256
+
257
+
258
+ def collate_fn_for_inference(batch):
259
+ """
260
+ Custom collate function to handle batches containing Tensors, strings, and Timestamps.
261
+
262
+ Args:
263
+ batch (list): A list of samples, where each sample is the tuple returned by
264
+ QlibTestDataset.__getitem__.
265
+
266
+ Returns:
267
+ A single tuple containing the batched data.
268
+ """
269
+ # Unzip the list of samples into separate lists for each data type
270
+ x, x_stamp, y_stamp, symbols, timestamps = zip(*batch)
271
+
272
+ # Stack the tensors to create a batch
273
+ x_batch = torch.stack(x, dim=0)
274
+ x_stamp_batch = torch.stack(x_stamp, dim=0)
275
+ y_stamp_batch = torch.stack(y_stamp, dim=0)
276
+
277
+ # Return the strings and timestamps as lists
278
+ return x_batch, x_stamp_batch, y_stamp_batch, list(symbols), list(timestamps)
279
+
280
+
281
+ def generate_predictions(config: dict, test_data: dict, rank: int = 0, world_size: int = 1, local_rank: int = 0):
282
+ """
283
+ Runs inference on the test dataset to generate prediction signals.
284
+ Supports both single-GPU and multi-GPU (torchrun) modes.
285
+
286
+ In multi-GPU mode, each rank processes a disjoint slice of the dataset.
287
+ Results are gathered to rank 0, which returns the merged DataFrames.
288
+ Other ranks return None.
289
+ """
290
+ device = torch.device(f"cuda:{local_rank}" if torch.cuda.is_available() else "cpu")
291
+ tokenizer, model = load_models(device)
292
+
293
+ full_dataset = QlibTestDataset(data=test_data, config=Config())
294
+
295
+ # Each rank handles every world_size-th sample: rank0→[0,2,4,...], rank1→[1,3,5,...]
296
+ rank_indices = list(range(rank, len(full_dataset), world_size))
297
+ dataset = Subset(full_dataset, rank_indices)
298
+
299
+ loader = DataLoader(
300
+ dataset,
301
+ batch_size=config['batch_size'] // config['sample_count'],
302
+ shuffle=False,
303
+ num_workers=8,
304
+ collate_fn=collate_fn_for_inference
305
+ )
306
+
307
+ results = defaultdict(list)
308
+ with torch.no_grad(), torch.autocast(device_type='cuda', dtype=torch.bfloat16):
309
+ for x, x_stamp, y_stamp, symbols, timestamps in tqdm(loader, desc=f"Inference [rank {rank}]", disable=rank != 0):
310
+ preds = auto_regressive_inference(
311
+ tokenizer, model, x.to(device), x_stamp.to(device), y_stamp.to(device),
312
+ max_context=config['max_context'], pred_len=config['pred_len'], clip=config['clip'],
313
+ T=config['T'], top_k=config['top_k'], top_p=config['top_p'], sample_count=config['sample_count']
314
+ )
315
+ # You can try commenting on this line to keep the history data
316
+ preds = preds[:, -config['pred_len']:, :]
317
+
318
+ # Convert to float32 numpy for signal calculation
319
+ if isinstance(preds, torch.Tensor):
320
+ preds = preds.float().cpu().numpy()
321
+
322
+ # The 'close' price is at index 3 in `feature_list`
323
+ last_day_close = x[:, -1, 3].numpy()
324
+ signals = {
325
+ 'last': preds[:, -1, 3] - last_day_close,
326
+ 'mean': np.mean(preds[:, :, 3], axis=1) - last_day_close,
327
+ 'max': np.max(preds[:, :, 3], axis=1) - last_day_close,
328
+ 'min': np.min(preds[:, :, 3], axis=1) - last_day_close,
329
+ }
330
+
331
+ for i in range(len(symbols)):
332
+ for sig_type, sig_values in signals.items():
333
+ results[sig_type].append((timestamps[i], symbols[i], sig_values[i]))
334
+
335
+ # Gather results from all ranks to rank 0
336
+ if world_size > 1:
337
+ all_results = [None] * world_size
338
+ dist.all_gather_object(all_results, dict(results))
339
+ else:
340
+ all_results = [dict(results)]
341
+
342
+ if rank != 0:
343
+ return None
344
+
345
+ # Merge results from all ranks and build DataFrames
346
+ if rank == 0:
347
+ print("Post-processing predictions into DataFrames...")
348
+ merged = defaultdict(list)
349
+ for rank_result in all_results:
350
+ for sig_type, records in rank_result.items():
351
+ merged[sig_type].extend(records)
352
+
353
+ prediction_dfs = {}
354
+ for sig_type, records in merged.items():
355
+ df = pd.DataFrame(records, columns=['datetime', 'instrument', 'score'])
356
+ pivot_df = df.pivot_table(index='datetime', columns='instrument', values='score')
357
+ prediction_dfs[sig_type] = pivot_df.sort_index()
358
+
359
+ return prediction_dfs
360
+
361
+
362
+ # =================================================================================
363
+ # 4. Main Execution
364
+ # =================================================================================
365
+
366
+ def main():
367
+ """Main function to set up config, run inference, and execute backtesting.
368
+
369
+ Single-GPU: python qlib_test.py --device cuda:0
370
+ Multi-GPU: torchrun --standalone --nproc_per_node=N qlib_test.py
371
+ """
372
+ # Detect whether launched by torchrun (multi-GPU) or plain python (single-GPU)
373
+ is_distributed = int(os.environ.get("WORLD_SIZE", 1)) > 1
374
+
375
+ if is_distributed:
376
+ rank, world_size, local_rank = setup_ddp()
377
+ else:
378
+ parser = argparse.ArgumentParser(description="Run Kronos Inference and Backtesting")
379
+ parser.add_argument("--device", type=str, default="cuda:0", help="Device for inference (e.g., 'cuda:0', 'cpu')")
380
+ args = parser.parse_args()
381
+ rank, world_size = 0, 1
382
+ local_rank = int(args.device.split(":")[-1]) if args.device.startswith("cuda:") else 0
383
+
384
+ # --- 1. Configuration Setup ---
385
+ base_config = Config()
386
+
387
+ run_config = {
388
+ 'data_path': base_config.dataset_path,
389
+ 'result_save_path': base_config.backtest_result_path,
390
+ 'result_name': base_config.backtest_save_folder_name,
391
+ 'tokenizer_path': base_config.finetuned_tokenizer_path,
392
+ 'model_path': base_config.finetuned_predictor_path,
393
+ 'max_context': base_config.max_context,
394
+ 'pred_len': base_config.predict_window,
395
+ 'clip': base_config.clip,
396
+ 'T': base_config.inference_T,
397
+ 'top_k': base_config.inference_top_k,
398
+ 'top_p': base_config.inference_top_p,
399
+ 'sample_count': base_config.inference_sample_count,
400
+ 'batch_size': base_config.backtest_batch_size,
401
+ }
402
+
403
+ if rank == 0:
404
+ print(f"--- Running with {world_size} GPU(s) ---")
405
+ for key, val in run_config.items():
406
+ print(f"{key:>20}: {val}")
407
+ print("-" * 35)
408
+
409
+ # --- 2. Load Data (all ranks load, avoids rank-0 bottleneck) ---
410
+ test_data_path = os.path.join(run_config['data_path'], "test_data.pkl")
411
+ if rank == 0:
412
+ print(f"Loading test data from {test_data_path}...")
413
+ with open(test_data_path, 'rb') as f:
414
+ test_data = pickle.load(f)
415
+
416
+ # --- 3. Generate Predictions ---
417
+ model_preds = generate_predictions(run_config, test_data, rank=rank, world_size=world_size, local_rank=local_rank)
418
+
419
+ # --- 4 & 5. Save and Backtest (rank 0 only) ---
420
+ if rank == 0:
421
+ save_dir = os.path.join(run_config['result_save_path'], run_config['result_name'])
422
+ os.makedirs(save_dir, exist_ok=True)
423
+ predictions_file = os.path.join(save_dir, "predictions.pkl")
424
+ print(f"Saving prediction signals to {predictions_file}...")
425
+ with open(predictions_file, 'wb') as f:
426
+ pickle.dump(model_preds, f)
427
+
428
+ backtester = QlibBacktest(base_config)
429
+ backtester.run_and_plot_results(model_preds, save_dir=save_dir)
430
+
431
+ if is_distributed:
432
+ cleanup_ddp()
433
+
434
+
435
+ if __name__ == '__main__':
436
+ main()
437
+
438
+
Kronos/finetune/qlib_test.py ADDED
@@ -0,0 +1,645 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ import pickle
5
+ import sys
6
+ import time
7
+ from collections import defaultdict
8
+ from contextlib import nullcontext
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ import torch
13
+ import torch.distributed as dist
14
+ from torch.utils.data import DataLoader, Dataset, Subset
15
+ from tqdm import tqdm
16
+
17
+
18
+ # Keep the original project layout assumption: this script normally lives in a
19
+ # subdirectory directly below the project root.
20
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
21
+ PROJECT_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, ".."))
22
+ if PROJECT_ROOT not in sys.path:
23
+ sys.path.insert(0, PROJECT_ROOT)
24
+
25
+ from config import Config
26
+ from model.kronos import Kronos, KronosTokenizer, auto_regressive_inference
27
+ from utils.training_utils import cleanup_ddp, setup_ddp
28
+
29
+
30
+ SIGNAL_NAMES = ("cc", "oc", "oo2")
31
+
32
+
33
+ def _atomic_pickle_dump(value, path):
34
+ """Write a pickle atomically so interruption cannot leave a partial file."""
35
+ parent = os.path.dirname(path)
36
+ if parent:
37
+ os.makedirs(parent, exist_ok=True)
38
+
39
+ tmp_path = f"{path}.tmp.{os.getpid()}"
40
+ try:
41
+ with open(tmp_path, "wb") as f:
42
+ pickle.dump(value, f, protocol=pickle.HIGHEST_PROTOCOL)
43
+ f.flush()
44
+ os.fsync(f.fileno())
45
+ os.replace(tmp_path, path)
46
+ finally:
47
+ if os.path.exists(tmp_path):
48
+ os.unlink(tmp_path)
49
+
50
+
51
+ def _atomic_json_dump(value, path):
52
+ """Write JSON atomically."""
53
+ parent = os.path.dirname(path)
54
+ if parent:
55
+ os.makedirs(parent, exist_ok=True)
56
+
57
+ tmp_path = f"{path}.tmp.{os.getpid()}"
58
+ try:
59
+ with open(tmp_path, "w", encoding="utf-8") as f:
60
+ json.dump(value, f, ensure_ascii=False, indent=2)
61
+ f.flush()
62
+ os.fsync(f.fileno())
63
+ os.replace(tmp_path, path)
64
+ finally:
65
+ if os.path.exists(tmp_path):
66
+ os.unlink(tmp_path)
67
+
68
+
69
+ def _validate_run_id(run_id):
70
+ """Prevent a run id from accidentally escaping the shard parent directory."""
71
+ if not run_id:
72
+ raise ValueError("run_id cannot be empty")
73
+ if os.path.basename(run_id) != run_id or run_id in {".", ".."}:
74
+ raise ValueError(
75
+ "run_id must be a directory name, not a path; "
76
+ f"received: {run_id!r}"
77
+ )
78
+ return run_id
79
+
80
+
81
+ def _new_distributed_run_id(rank, world_size, requested_run_id=None):
82
+ """Resolve one shard-directory name shared by all ranks.
83
+
84
+ Supplying --run-id (or KRONOS_RUN_ID) is recommended because it makes the
85
+ later offline merge command deterministic. If no id is supplied, rank 0
86
+ creates one and broadcasts it before inference starts. There is no
87
+ collective communication after inference begins.
88
+ """
89
+ if requested_run_id:
90
+ return _validate_run_id(requested_run_id)
91
+
92
+ if world_size == 1:
93
+ return _validate_run_id(
94
+ f"single_{time.strftime('%Y%m%d_%H%M%S')}_{os.getpid()}"
95
+ )
96
+
97
+ shared_run_id = [
98
+ f"run_{time.strftime('%Y%m%d_%H%M%S')}_{os.getpid()}"
99
+ if rank == 0
100
+ else None
101
+ ]
102
+ dist.broadcast_object_list(shared_run_id, src=0)
103
+ return _validate_run_id(shared_run_id[0])
104
+
105
+
106
+ class QlibTestDataset(Dataset):
107
+ """Sequential inference windows with symbol and signal-date metadata."""
108
+
109
+ def __init__(self, data, config):
110
+ self.data = data
111
+ self.config = config
112
+ self.window_size = config.lookback_window + config.predict_window
113
+ self.symbols = list(self.data.keys())
114
+ self.feature_list = config.feature_list
115
+ self.time_feature_list = config.time_feature_list
116
+ self.signal_start = pd.Timestamp(
117
+ config.test_time_range[0]
118
+ ).normalize()
119
+ self.signal_end = pd.Timestamp(
120
+ config.test_time_range[1]
121
+ ).normalize()
122
+ self.indices = []
123
+
124
+ print("Preprocessing and building indices for test dataset...", flush=True)
125
+
126
+ for symbol in self.symbols:
127
+ df = self.data[symbol].reset_index()
128
+
129
+ if "datetime" not in df.columns:
130
+ raise KeyError(
131
+ f"{symbol}: reset_index() did not produce a datetime column"
132
+ )
133
+
134
+ df["datetime"] = pd.to_datetime(df["datetime"])
135
+ df["minute"] = df["datetime"].dt.minute
136
+ df["hour"] = df["datetime"].dt.hour
137
+ df["weekday"] = df["datetime"].dt.weekday
138
+ df["day"] = df["datetime"].dt.day
139
+ df["month"] = df["datetime"].dt.month
140
+ self.data[symbol] = df
141
+
142
+ num_samples = len(df) - self.window_size + 1
143
+ if num_samples <= 0:
144
+ continue
145
+
146
+ # One signal window every 48 five-minute bars, matching the
147
+ # original inference logic.
148
+ for start_idx in range(0, num_samples, 48):
149
+ timestamp = pd.Timestamp(
150
+ df.iloc[
151
+ start_idx + self.config.lookback_window - 1
152
+ ]["datetime"]
153
+ )
154
+ signal_date = timestamp.normalize()
155
+
156
+ if self.signal_start <= signal_date <= self.signal_end:
157
+ self.indices.append((symbol, start_idx, signal_date))
158
+
159
+ print(
160
+ f"Inference signal range: {self.signal_start.date()} ~ "
161
+ f"{self.signal_end.date()} | valid samples: {len(self.indices)}",
162
+ flush=True,
163
+ )
164
+
165
+ def __len__(self):
166
+ return len(self.indices)
167
+
168
+ def __getitem__(self, idx):
169
+ symbol, start_idx, signal_date = self.indices[idx]
170
+ df = self.data[symbol]
171
+
172
+ context_end = start_idx + self.config.lookback_window
173
+ predict_end = context_end + self.config.predict_window
174
+
175
+ context_df = df.iloc[start_idx:context_end]
176
+ predict_df = df.iloc[context_end:predict_end]
177
+
178
+ x = context_df[self.feature_list].values.astype(np.float32)
179
+ x_stamp = context_df[
180
+ self.time_feature_list
181
+ ].values.astype(np.float32)
182
+ y_stamp = predict_df[
183
+ self.time_feature_list
184
+ ].values.astype(np.float32)
185
+
186
+ # Raw last context bar. It is used as the denominator for returns.
187
+ current_values = x[-1].copy()
188
+
189
+ # Instance-level normalization, consistent with training.
190
+ x_mean = np.mean(x, axis=0)
191
+ x_std = np.std(x, axis=0)
192
+ x = (x - x_mean) / (x_std + 1e-5)
193
+ x = np.clip(x, -self.config.clip, self.config.clip)
194
+
195
+ return (
196
+ torch.from_numpy(x),
197
+ torch.from_numpy(x_stamp),
198
+ torch.from_numpy(y_stamp),
199
+ symbol,
200
+ signal_date,
201
+ torch.from_numpy(current_values),
202
+ torch.from_numpy(x_mean.astype(np.float32)),
203
+ torch.from_numpy(x_std.astype(np.float32)),
204
+ )
205
+
206
+
207
+ def collate_fn_for_inference(batch):
208
+ """Stack tensor fields while preserving symbols and pandas timestamps."""
209
+ (
210
+ x,
211
+ x_stamp,
212
+ y_stamp,
213
+ symbols,
214
+ timestamps,
215
+ current_values,
216
+ x_mean,
217
+ x_std,
218
+ ) = zip(*batch)
219
+
220
+ return (
221
+ torch.stack(x, dim=0),
222
+ torch.stack(x_stamp, dim=0),
223
+ torch.stack(y_stamp, dim=0),
224
+ list(symbols),
225
+ list(timestamps),
226
+ torch.stack(current_values, dim=0),
227
+ torch.stack(x_mean, dim=0),
228
+ torch.stack(x_std, dim=0),
229
+ )
230
+
231
+
232
+ def load_models(config, device):
233
+ """Load the tokenizer and predictor onto one rank's device."""
234
+ print(f"Loading models onto device: {device}...", flush=True)
235
+
236
+ model_dtype = (
237
+ torch.bfloat16
238
+ if device.type == "cuda"
239
+ else torch.float32
240
+ )
241
+
242
+ tokenizer = (
243
+ KronosTokenizer
244
+ .from_pretrained(config["tokenizer_path"])
245
+ .to(device)
246
+ .to(model_dtype)
247
+ .eval()
248
+ )
249
+ model = (
250
+ Kronos
251
+ .from_pretrained(config["model_path"])
252
+ .to(device)
253
+ .to(model_dtype)
254
+ .eval()
255
+ )
256
+ return tokenizer, model
257
+
258
+
259
+ def _calculate_return(numerator, denominator):
260
+ """Calculate numerator / denominator - 1 with invalid values as NaN."""
261
+ result = np.full(numerator.shape, np.nan, dtype=np.float32)
262
+ valid = (
263
+ np.isfinite(numerator)
264
+ & np.isfinite(denominator)
265
+ & (np.abs(denominator) > 1e-8)
266
+ )
267
+ result[valid] = numerator[valid] / denominator[valid] - 1.0
268
+ return result
269
+
270
+
271
+ def generate_prediction_shards(
272
+ config,
273
+ base_config,
274
+ test_data,
275
+ rank=0,
276
+ world_size=1,
277
+ local_rank=0,
278
+ ):
279
+ """Run one rank's inference and persist independent checkpoint shards.
280
+
281
+ Every rank writes its own part files and one final .done.json manifest.
282
+ No rank waits for another rank after inference. Final output construction
283
+ is intentionally delegated to merge_predictions.py.
284
+ """
285
+ device = torch.device(
286
+ config.get("device", f"cuda:{local_rank}")
287
+ )
288
+
289
+ if device.type == "cuda" and not torch.cuda.is_available():
290
+ raise RuntimeError(f"Requested {device}, but CUDA is unavailable")
291
+ if config["pred_len"] < 49:
292
+ raise ValueError(
293
+ "predict_window must be at least 49 for cc/oc/oo2 signals"
294
+ )
295
+ if config["sample_count"] <= 0:
296
+ raise ValueError("sample_count must be positive")
297
+
298
+ tokenizer, model = load_models(config, device)
299
+ full_dataset = QlibTestDataset(test_data, base_config)
300
+
301
+ # range is a compact sequence; unlike list(range(...)), it does not create
302
+ # another large Python list on every rank.
303
+ rank_indices = range(rank, len(full_dataset), world_size)
304
+ rank_dataset = Subset(full_dataset, rank_indices)
305
+
306
+ per_rank_batch_size = max(
307
+ 1,
308
+ config["batch_size"] // config["sample_count"],
309
+ )
310
+
311
+ loader = DataLoader(
312
+ rank_dataset,
313
+ batch_size=per_rank_batch_size,
314
+ shuffle=False,
315
+ num_workers=0,
316
+ collate_fn=collate_fn_for_inference,
317
+ )
318
+
319
+ shard_dir = config["shard_dir"]
320
+ checkpoint_batches = max(
321
+ 1,
322
+ int(config.get("checkpoint_batches", 64)),
323
+ )
324
+ os.makedirs(shard_dir, exist_ok=True)
325
+
326
+ # If the same run id is deliberately rerun, an old completion marker must
327
+ # never make the offline merger believe this rank has already completed.
328
+ manifest_path = os.path.join(
329
+ shard_dir,
330
+ f"rank_{rank:04d}.done.json",
331
+ )
332
+ if os.path.exists(manifest_path):
333
+ os.unlink(manifest_path)
334
+
335
+ results = defaultdict(list)
336
+ part_index = 0
337
+ batch_count = 0
338
+ processed_samples = 0
339
+
340
+ autocast_context = (
341
+ torch.autocast(
342
+ device_type="cuda",
343
+ dtype=torch.bfloat16,
344
+ )
345
+ if device.type == "cuda"
346
+ else nullcontext()
347
+ )
348
+
349
+ with torch.no_grad(), autocast_context:
350
+ for batch_index, batch in enumerate(
351
+ tqdm(
352
+ loader,
353
+ desc=f"Inference [rank {rank}]",
354
+ disable=rank != 0,
355
+ ),
356
+ start=1,
357
+ ):
358
+ (
359
+ x,
360
+ x_stamp,
361
+ y_stamp,
362
+ symbols,
363
+ timestamps,
364
+ current_values,
365
+ x_mean,
366
+ x_std,
367
+ ) = batch
368
+
369
+ preds = auto_regressive_inference(
370
+ tokenizer,
371
+ model,
372
+ x.to(device),
373
+ x_stamp.to(device),
374
+ y_stamp.to(device),
375
+ max_context=config["max_context"],
376
+ pred_len=config["pred_len"],
377
+ clip=config["clip"],
378
+ T=config["T"],
379
+ top_k=config["top_k"],
380
+ top_p=config["top_p"],
381
+ sample_count=config["sample_count"],
382
+ )
383
+
384
+ # Keep only the generated future bars if the helper also returns
385
+ # history.
386
+ preds = preds[:, -config["pred_len"]:, :]
387
+
388
+ if isinstance(preds, torch.Tensor):
389
+ preds = preds.float().cpu().numpy()
390
+ else:
391
+ preds = np.asarray(preds, dtype=np.float32)
392
+
393
+ # Undo the per-instance normalization before computing returns.
394
+ x_mean_np = x_mean.numpy()[:, None, :]
395
+ x_std_np = x_std.numpy()[:, None, :]
396
+ preds_raw = preds * (x_std_np + 1e-5) + x_mean_np
397
+ current_values_np = current_values.numpy()
398
+
399
+ current_close = current_values_np[:, 3]
400
+ signals = {
401
+ # T+1 last close / T close - 1
402
+ "cc": _calculate_return(
403
+ preds_raw[:, 47, 3],
404
+ current_close,
405
+ ),
406
+ # T+1 first open / T close - 1
407
+ "oc": _calculate_return(
408
+ preds_raw[:, 0, 0],
409
+ current_close,
410
+ ),
411
+ # T+2 first open / T+1 first open - 1
412
+ "oo2": _calculate_return(
413
+ preds_raw[:, 48, 0],
414
+ preds_raw[:, 0, 0],
415
+ ),
416
+ }
417
+
418
+ for sample_offset, (timestamp, symbol) in enumerate(
419
+ zip(timestamps, symbols)
420
+ ):
421
+ for signal_name in SIGNAL_NAMES:
422
+ results[signal_name].append(
423
+ (
424
+ timestamp,
425
+ symbol,
426
+ signals[signal_name][sample_offset],
427
+ )
428
+ )
429
+
430
+ batch_count = batch_index
431
+ processed_samples += len(symbols)
432
+
433
+ if batch_index % checkpoint_batches == 0:
434
+ part_path = os.path.join(
435
+ shard_dir,
436
+ f"rank_{rank:04d}_part_{part_index:06d}.pkl",
437
+ )
438
+ _atomic_pickle_dump(dict(results), part_path)
439
+ results = defaultdict(list)
440
+ part_index += 1
441
+
442
+ # Write the last partial part. An empty rank still writes one empty part,
443
+ # which makes its successful completion explicit.
444
+ if results or part_index == 0:
445
+ part_path = os.path.join(
446
+ shard_dir,
447
+ f"rank_{rank:04d}_part_{part_index:06d}.pkl",
448
+ )
449
+ _atomic_pickle_dump(dict(results), part_path)
450
+ part_index += 1
451
+
452
+ expected_rank_samples = len(rank_dataset)
453
+ if processed_samples != expected_rank_samples:
454
+ raise RuntimeError(
455
+ f"Rank {rank} processed {processed_samples} samples, "
456
+ f"but its assigned subset contains {expected_rank_samples}"
457
+ )
458
+
459
+ manifest = {
460
+ "run_id": config["run_id"],
461
+ "rank": rank,
462
+ "world_size": world_size,
463
+ "batches": batch_count,
464
+ "parts": part_index,
465
+ "num_samples": processed_samples,
466
+ "full_dataset_size": len(full_dataset),
467
+ "signals": list(SIGNAL_NAMES),
468
+ }
469
+ _atomic_json_dump(manifest, manifest_path)
470
+
471
+ print(
472
+ f"[rank {rank}] Complete: {processed_samples} samples, "
473
+ f"{part_index} shard(s) -> {shard_dir}",
474
+ flush=True,
475
+ )
476
+
477
+
478
+ def build_argument_parser():
479
+ parser = argparse.ArgumentParser(
480
+ description=(
481
+ "Generate Kronos prediction shards. "
482
+ "Run merge_predictions.py after all ranks finish."
483
+ )
484
+ )
485
+ parser.add_argument(
486
+ "--device",
487
+ default="cuda:0",
488
+ help="Single-process device. torchrun assigns devices automatically.",
489
+ )
490
+ parser.add_argument(
491
+ "--run-id",
492
+ default=os.environ.get("KRONOS_RUN_ID"),
493
+ help=(
494
+ "Shared shard run id. Defaults to KRONOS_RUN_ID, or an "
495
+ "automatically generated id."
496
+ ),
497
+ )
498
+ parser.add_argument(
499
+ "--checkpoint-batches",
500
+ type=int,
501
+ default=int(
502
+ os.environ.get("KRONOS_CHECKPOINT_BATCHES", "64")
503
+ ),
504
+ help="Write one checkpoint shard every N inference batches.",
505
+ )
506
+ # Compatibility with torchrun versions that inject this CLI argument.
507
+ parser.add_argument(
508
+ "--local-rank",
509
+ "--local_rank",
510
+ type=int,
511
+ default=None,
512
+ help=argparse.SUPPRESS,
513
+ )
514
+ return parser
515
+
516
+
517
+ def main():
518
+ args = build_argument_parser().parse_args()
519
+ is_distributed = int(os.environ.get("WORLD_SIZE", "1")) > 1
520
+
521
+ if is_distributed:
522
+ rank, world_size, local_rank = setup_ddp()
523
+ requested_device = (
524
+ f"cuda:{local_rank}"
525
+ if torch.cuda.is_available()
526
+ else "cpu"
527
+ )
528
+ else:
529
+ rank = 0
530
+ world_size = 1
531
+ local_rank = (
532
+ int(args.device.split(":")[-1])
533
+ if args.device.startswith("cuda:")
534
+ else 0
535
+ )
536
+ requested_device = args.device
537
+
538
+ try:
539
+ run_id = _new_distributed_run_id(
540
+ rank,
541
+ world_size,
542
+ requested_run_id=args.run_id,
543
+ )
544
+
545
+ base_config = Config()
546
+ result_dir = os.path.join(
547
+ base_config.signal_result_path,
548
+ base_config.signal_result_name,
549
+ )
550
+ shard_dir = os.path.join(
551
+ result_dir,
552
+ ".inference_shards",
553
+ run_id,
554
+ )
555
+
556
+ run_config = {
557
+ "run_id": run_id,
558
+ "device": requested_device,
559
+ "data_path": base_config.dataset_path,
560
+ "test_data_file": base_config.test_data_file,
561
+ "result_save_path": base_config.signal_result_path,
562
+ "result_name": base_config.signal_result_name,
563
+ "tokenizer_path": base_config.pretrained_tokenizer_path,
564
+ "model_path": base_config.pretrained_predictor_path,
565
+ "max_context": base_config.max_context,
566
+ "pred_len": base_config.predict_window,
567
+ "clip": base_config.clip,
568
+ "T": base_config.inference_T,
569
+ "top_k": base_config.inference_top_k,
570
+ "top_p": base_config.inference_top_p,
571
+ "sample_count": base_config.inference_sample_count,
572
+ "batch_size": base_config.backtest_batch_size,
573
+ "shard_dir": shard_dir,
574
+ "checkpoint_batches": args.checkpoint_batches,
575
+ }
576
+
577
+ if rank == 0:
578
+ os.makedirs(shard_dir, exist_ok=True)
579
+
580
+ run_metadata = {
581
+ "run_id": run_id,
582
+ "world_size": world_size,
583
+ "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
584
+ "source_test_data": os.path.join(
585
+ run_config["data_path"],
586
+ run_config["test_data_file"],
587
+ ),
588
+ "signal_start": base_config.test_time_range[0],
589
+ "signal_end": base_config.test_time_range[1],
590
+ "lookback_window": base_config.lookback_window,
591
+ "predict_window": base_config.predict_window,
592
+ "stride_bars": 48,
593
+ "signals": list(SIGNAL_NAMES),
594
+ "feature_list": base_config.feature_list,
595
+ }
596
+ _atomic_json_dump(
597
+ run_metadata,
598
+ os.path.join(shard_dir, "run_metadata.json"),
599
+ )
600
+
601
+ print(f"--- Running with {world_size} process(es) ---")
602
+ for key, value in run_config.items():
603
+ print(f"{key:>20}: {value}")
604
+ print("-" * 45, flush=True)
605
+
606
+ test_data_path = os.path.join(
607
+ run_config["data_path"],
608
+ run_config["test_data_file"],
609
+ )
610
+ print(
611
+ f"[rank {rank}] Loading test data from {test_data_path}...",
612
+ flush=True,
613
+ )
614
+ with open(test_data_path, "rb") as f:
615
+ test_data = pickle.load(f)
616
+
617
+ generate_prediction_shards(
618
+ run_config,
619
+ base_config,
620
+ test_data,
621
+ rank=rank,
622
+ world_size=world_size,
623
+ local_rank=local_rank,
624
+ )
625
+
626
+ if rank == 0:
627
+ print(
628
+ "\nInference ranks write shards only; no online merge is "
629
+ "performed.\n"
630
+ "After torchrun exits successfully, run:\n"
631
+ f" python merge_predictions.py "
632
+ f"--shard-dir {shard_dir} "
633
+ f"--save-dir {result_dir} "
634
+ f"--world-size {world_size}",
635
+ flush=True,
636
+ )
637
+ finally:
638
+ # The user's cleanup_ddp() only calls destroy_process_group(); it has
639
+ # no barrier, so completed ranks do not wait for slower ranks here.
640
+ if is_distributed:
641
+ cleanup_ddp()
642
+
643
+
644
+ if __name__ == "__main__":
645
+ main()
Kronos/finetune/train_predictor.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import json
4
+ import time
5
+ from time import gmtime, strftime
6
+ import torch.distributed as dist
7
+ import torch
8
+ from torch.utils.data import DataLoader
9
+ from torch.utils.data.distributed import DistributedSampler
10
+ from torch.nn.parallel import DistributedDataParallel as DDP
11
+
12
+ import comet_ml
13
+
14
+ # Ensure project root is in path
15
+ sys.path.append('../')
16
+ from config import Config
17
+ from dataset import QlibDataset
18
+ from model.kronos import KronosTokenizer, Kronos
19
+ # Import shared utilities
20
+ from utils.training_utils import (
21
+ setup_ddp,
22
+ cleanup_ddp,
23
+ set_seed,
24
+ get_model_size,
25
+ format_time
26
+ )
27
+
28
+
29
+ def create_dataloaders(config: dict, rank: int, world_size: int):
30
+ """
31
+ Creates and returns distributed dataloaders for training and validation.
32
+
33
+ Args:
34
+ config (dict): A dictionary of configuration parameters.
35
+ rank (int): The global rank of the current process.
36
+ world_size (int): The total number of processes.
37
+
38
+ Returns:
39
+ tuple: (train_loader, val_loader, train_dataset, valid_dataset).
40
+ """
41
+ print(f"[Rank {rank}] Creating distributed dataloaders...")
42
+ train_dataset = QlibDataset('train')
43
+ valid_dataset = QlibDataset('val')
44
+ print(f"[Rank {rank}] Train dataset size: {len(train_dataset)}, Validation dataset size: {len(valid_dataset)}")
45
+
46
+ train_sampler = DistributedSampler(train_dataset, num_replicas=world_size, rank=rank, shuffle=True)
47
+ val_sampler = DistributedSampler(valid_dataset, num_replicas=world_size, rank=rank, shuffle=False)
48
+
49
+ train_loader = DataLoader(
50
+ train_dataset, batch_size=config['batch_size'], sampler=train_sampler,
51
+ num_workers=config.get('num_workers', 2), pin_memory=True, drop_last=True
52
+ )
53
+ val_loader = DataLoader(
54
+ valid_dataset, batch_size=config['batch_size'], sampler=val_sampler,
55
+ num_workers=config.get('num_workers', 2), pin_memory=True, drop_last=False
56
+ )
57
+ return train_loader, val_loader, train_dataset, valid_dataset
58
+
59
+
60
+ def train_model(model, tokenizer, device, config, save_dir, logger, rank, world_size):
61
+ """
62
+ The main training and validation loop for the predictor.
63
+ """
64
+ start_time = time.time()
65
+ if rank == 0:
66
+ effective_bs = config['batch_size'] * world_size
67
+ print(f"Effective BATCHSIZE per GPU: {config['batch_size']}, Total: {effective_bs}")
68
+
69
+ train_loader, val_loader, train_dataset, valid_dataset = create_dataloaders(config, rank, world_size)
70
+
71
+ optimizer = torch.optim.AdamW(
72
+ model.parameters(),
73
+ lr=config['predictor_learning_rate'],
74
+ betas=(config['adam_beta1'], config['adam_beta2']),
75
+ weight_decay=config['adam_weight_decay']
76
+ )
77
+ scheduler = torch.optim.lr_scheduler.OneCycleLR(
78
+ optimizer, max_lr=config['predictor_learning_rate'],
79
+ steps_per_epoch=len(train_loader), epochs=config['epochs'],
80
+ pct_start=0.03, div_factor=10
81
+ )
82
+
83
+ best_val_loss = float('inf')
84
+ dt_result = {}
85
+ batch_idx_global = 0
86
+
87
+ for epoch_idx in range(config['epochs']):
88
+ epoch_start_time = time.time()
89
+ model.train()
90
+ train_loader.sampler.set_epoch(epoch_idx)
91
+
92
+ train_dataset.set_epoch_seed(epoch_idx * 10000 + rank)
93
+ valid_dataset.set_epoch_seed(0)
94
+
95
+ for i, (batch_x, batch_x_stamp) in enumerate(train_loader):
96
+ batch_x = batch_x.to(device, non_blocking=True)
97
+ batch_x_stamp = batch_x_stamp.to(device, non_blocking=True)
98
+
99
+ # Tokenize input data on-the-fly
100
+ with torch.no_grad():
101
+ token_seq_0, token_seq_1 = tokenizer.encode(batch_x, half=True)
102
+
103
+ # Prepare inputs and targets for the language model
104
+ token_in = [token_seq_0[:, :-1], token_seq_1[:, :-1]]
105
+ token_out = [token_seq_0[:, 1:], token_seq_1[:, 1:]]
106
+
107
+ # Forward pass and loss calculation
108
+ logits = model(token_in[0], token_in[1], batch_x_stamp[:, :-1, :])
109
+ loss, s1_loss, s2_loss = model.module.head.compute_loss(logits[0], logits[1], token_out[0], token_out[1])
110
+
111
+ # Backward pass and optimization
112
+ optimizer.zero_grad()
113
+ loss.backward()
114
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=3.0)
115
+ optimizer.step()
116
+ scheduler.step()
117
+
118
+ # Logging (Master Process Only)
119
+ if rank == 0 and (batch_idx_global + 1) % config['log_interval'] == 0:
120
+ lr = optimizer.param_groups[0]['lr']
121
+ print(
122
+ f"[Rank {rank}, Epoch {epoch_idx + 1}/{config['epochs']}, Step {i + 1}/{len(train_loader)}] "
123
+ f"LR {lr:.6f}, Loss: {loss.item():.4f}"
124
+ )
125
+ if rank == 0 and logger:
126
+ lr = optimizer.param_groups[0]['lr']
127
+ logger.log_metric('train_predictor_loss_batch', loss.item(), step=batch_idx_global)
128
+ logger.log_metric('train_S1_loss_each_batch', s1_loss.item(), step=batch_idx_global)
129
+ logger.log_metric('train_S2_loss_each_batch', s2_loss.item(), step=batch_idx_global)
130
+ logger.log_metric('predictor_learning_rate', lr, step=batch_idx_global)
131
+
132
+ batch_idx_global += 1
133
+
134
+ # --- Validation Loop ---
135
+ model.eval()
136
+ tot_val_loss_sum_rank = 0.0
137
+ val_batches_processed_rank = 0
138
+ with torch.no_grad():
139
+ for batch_x, batch_x_stamp in val_loader:
140
+ batch_x = batch_x.to(device, non_blocking=True)
141
+ batch_x_stamp = batch_x_stamp.to(device, non_blocking=True)
142
+
143
+ token_seq_0, token_seq_1 = tokenizer.encode(batch_x, half=True)
144
+ token_in = [token_seq_0[:, :-1], token_seq_1[:, :-1]]
145
+ token_out = [token_seq_0[:, 1:], token_seq_1[:, 1:]]
146
+
147
+ logits = model(token_in[0], token_in[1], batch_x_stamp[:, :-1, :])
148
+ val_loss, _, _ = model.module.head.compute_loss(logits[0], logits[1], token_out[0], token_out[1])
149
+
150
+ tot_val_loss_sum_rank += val_loss.item()
151
+ val_batches_processed_rank += 1
152
+
153
+ # Reduce validation metrics
154
+ val_loss_sum_tensor = torch.tensor(tot_val_loss_sum_rank, device=device)
155
+ val_batches_tensor = torch.tensor(val_batches_processed_rank, device=device)
156
+ dist.all_reduce(val_loss_sum_tensor, op=dist.ReduceOp.SUM)
157
+ dist.all_reduce(val_batches_tensor, op=dist.ReduceOp.SUM)
158
+
159
+ avg_val_loss = val_loss_sum_tensor.item() / val_batches_tensor.item() if val_batches_tensor.item() > 0 else 0
160
+
161
+ # --- End of Epoch Summary & Checkpointing (Master Process Only) ---
162
+ if rank == 0:
163
+ print(f"\n--- Epoch {epoch_idx + 1}/{config['epochs']} Summary ---")
164
+ print(f"Validation Loss: {avg_val_loss:.4f}")
165
+ print(f"Time This Epoch: {format_time(time.time() - epoch_start_time)}")
166
+ print(f"Total Time Elapsed: {format_time(time.time() - start_time)}\n")
167
+ if logger:
168
+ logger.log_metric('val_predictor_loss_epoch', avg_val_loss, epoch=epoch_idx)
169
+
170
+ if avg_val_loss < best_val_loss:
171
+ best_val_loss = avg_val_loss
172
+ save_path = f"{save_dir}/checkpoints/best_model"
173
+ model.module.save_pretrained(save_path)
174
+ print(f"Best model saved to {save_path} (Val Loss: {best_val_loss:.4f})")
175
+
176
+ dist.barrier()
177
+
178
+ dt_result['best_val_loss'] = best_val_loss
179
+ return dt_result
180
+
181
+
182
+ def main(config: dict):
183
+ """Main function to orchestrate the DDP training process."""
184
+ rank, world_size, local_rank = setup_ddp()
185
+ device = torch.device(f"cuda:{local_rank}")
186
+ set_seed(config['seed'], rank)
187
+
188
+ save_dir = os.path.join(config['save_path'], config['predictor_save_folder_name'])
189
+
190
+ # Logger and summary setup (master process only)
191
+ comet_logger, master_summary = None, {}
192
+ if rank == 0:
193
+ os.makedirs(os.path.join(save_dir, 'checkpoints'), exist_ok=True)
194
+ master_summary = {
195
+ 'start_time': strftime("%Y-%m-%dT%H-%M-%S", gmtime()),
196
+ 'save_directory': save_dir,
197
+ 'world_size': world_size,
198
+ }
199
+ if config['use_comet']:
200
+ comet_logger = comet_ml.Experiment(
201
+ api_key=config['comet_config']['api_key'],
202
+ project_name=config['comet_config']['project_name'],
203
+ workspace=config['comet_config']['workspace'],
204
+ )
205
+ comet_logger.add_tag(config['comet_tag'])
206
+ comet_logger.set_name(config['comet_name'])
207
+ comet_logger.log_parameters(config)
208
+ print("Comet Logger Initialized.")
209
+
210
+ dist.barrier()
211
+
212
+ # Model Initialization
213
+ tokenizer = KronosTokenizer.from_pretrained(config['finetuned_tokenizer_path'])
214
+ tokenizer.eval().to(device)
215
+
216
+ model = Kronos.from_pretrained(config['pretrained_predictor_path'])
217
+ model.to(device)
218
+ model = DDP(model, device_ids=[local_rank], find_unused_parameters=False)
219
+
220
+ if rank == 0:
221
+ print(f"Predictor Model Size: {get_model_size(model.module)}")
222
+
223
+ # Start Training
224
+ dt_result = train_model(
225
+ model, tokenizer, device, config, save_dir, comet_logger, rank, world_size
226
+ )
227
+
228
+ if rank == 0:
229
+ master_summary['final_result'] = dt_result
230
+ with open(os.path.join(save_dir, 'summary.json'), 'w') as f:
231
+ json.dump(master_summary, f, indent=4)
232
+ print('Training finished. Summary file saved.')
233
+ if comet_logger: comet_logger.end()
234
+
235
+ cleanup_ddp()
236
+
237
+
238
+ if __name__ == '__main__':
239
+ # Usage: torchrun --standalone --nproc_per_node=NUM_GPUS train_predictor.py
240
+ if "WORLD_SIZE" not in os.environ:
241
+ raise RuntimeError("This script must be launched with `torchrun`.")
242
+
243
+ config_instance = Config()
244
+ main(config_instance.__dict__)
Kronos/finetune/train_tokenizer.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import json
4
+ import time
5
+ from time import gmtime, strftime
6
+ import argparse
7
+ import datetime
8
+ import torch.distributed as dist
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from torch.utils.data import DataLoader
12
+ from torch.utils.data.distributed import DistributedSampler
13
+ from torch.nn.parallel import DistributedDataParallel as DDP
14
+
15
+ import comet_ml
16
+
17
+ # Ensure project root is in path
18
+ sys.path.append("../")
19
+ from config import Config
20
+ from dataset import QlibDataset
21
+ from model.kronos import KronosTokenizer
22
+ # Import shared utilities
23
+ from utils.training_utils import (
24
+ setup_ddp,
25
+ cleanup_ddp,
26
+ set_seed,
27
+ get_model_size,
28
+ format_time,
29
+ )
30
+
31
+
32
+ def create_dataloaders(config: dict, rank: int, world_size: int):
33
+ """
34
+ Creates and returns distributed dataloaders for training and validation.
35
+
36
+ Args:
37
+ config (dict): A dictionary of configuration parameters.
38
+ rank (int): The global rank of the current process.
39
+ world_size (int): The total number of processes.
40
+
41
+ Returns:
42
+ tuple: A tuple containing (train_loader, val_loader, train_dataset, valid_dataset).
43
+ """
44
+ print(f"[Rank {rank}] Creating distributed dataloaders...")
45
+ train_dataset = QlibDataset('train')
46
+ valid_dataset = QlibDataset('val')
47
+ print(f"[Rank {rank}] Train dataset size: {len(train_dataset)}, Validation dataset size: {len(valid_dataset)}")
48
+
49
+ train_sampler = DistributedSampler(train_dataset, num_replicas=world_size, rank=rank, shuffle=True)
50
+ val_sampler = DistributedSampler(valid_dataset, num_replicas=world_size, rank=rank, shuffle=False)
51
+
52
+ train_loader = DataLoader(
53
+ train_dataset,
54
+ batch_size=config['batch_size'],
55
+ sampler=train_sampler,
56
+ shuffle=False, # Shuffle is handled by the sampler
57
+ num_workers=config.get('num_workers', 2),
58
+ pin_memory=True,
59
+ drop_last=True
60
+ )
61
+ val_loader = DataLoader(
62
+ valid_dataset,
63
+ batch_size=config['batch_size'],
64
+ sampler=val_sampler,
65
+ shuffle=False,
66
+ num_workers=config.get('num_workers', 2),
67
+ pin_memory=True,
68
+ drop_last=False
69
+ )
70
+ print(f"[Rank {rank}] Dataloaders created. Train steps/epoch: {len(train_loader)}, Val steps: {len(val_loader)}")
71
+ return train_loader, val_loader, train_dataset, valid_dataset
72
+
73
+
74
+ def train_model(model, device, config, save_dir, logger, rank, world_size):
75
+ """
76
+ The main training and validation loop for the tokenizer.
77
+
78
+ Args:
79
+ model (DDP): The DDP-wrapped model to train.
80
+ device (torch.device): The device for the current process.
81
+ config (dict): Configuration dictionary.
82
+ save_dir (str): Directory to save checkpoints.
83
+ logger (comet_ml.Experiment): Comet logger instance.
84
+ rank (int): Global rank of the process.
85
+ world_size (int): Total number of processes.
86
+
87
+ Returns:
88
+ tuple: A tuple containing the trained model and a dictionary of results.
89
+ """
90
+ start_time = time.time()
91
+ if rank == 0:
92
+ effective_bs = config['batch_size'] * world_size * config['accumulation_steps']
93
+ print(f"[Rank {rank}] BATCHSIZE (per GPU): {config['batch_size']}")
94
+ print(f"[Rank {rank}] Effective total batch size: {effective_bs}")
95
+
96
+ train_loader, val_loader, train_dataset, valid_dataset = create_dataloaders(config, rank, world_size)
97
+
98
+ optimizer = torch.optim.AdamW(
99
+ model.parameters(),
100
+ lr=config['tokenizer_learning_rate'],
101
+ weight_decay=config['adam_weight_decay']
102
+ )
103
+
104
+ scheduler = torch.optim.lr_scheduler.OneCycleLR(
105
+ optimizer=optimizer,
106
+ max_lr=config['tokenizer_learning_rate'],
107
+ steps_per_epoch=len(train_loader),
108
+ epochs=config['epochs'],
109
+ pct_start=0.03,
110
+ div_factor=10
111
+ )
112
+
113
+ best_val_loss = float('inf')
114
+ dt_result = {}
115
+ batch_idx_global_train = 0
116
+
117
+ for epoch_idx in range(config['epochs']):
118
+ epoch_start_time = time.time()
119
+ model.train()
120
+ train_loader.sampler.set_epoch(epoch_idx)
121
+
122
+ # Set dataset seeds for reproducible sampling
123
+ train_dataset.set_epoch_seed(epoch_idx * 10000 + rank)
124
+ valid_dataset.set_epoch_seed(0) # Keep validation sampling consistent
125
+
126
+ for i, (ori_batch_x, _) in enumerate(train_loader):
127
+ ori_batch_x = ori_batch_x.to(device, non_blocking=True)
128
+
129
+ # --- Gradient Accumulation Loop ---
130
+ current_batch_total_loss = 0.0
131
+ for j in range(config['accumulation_steps']):
132
+ start_idx = j * (ori_batch_x.shape[0] // config['accumulation_steps'])
133
+ end_idx = (j + 1) * (ori_batch_x.shape[0] // config['accumulation_steps'])
134
+ batch_x = ori_batch_x[start_idx:end_idx]
135
+
136
+ # Forward pass
137
+ zs, bsq_loss, _, _ = model(batch_x)
138
+ z_pre, z = zs
139
+
140
+ # Loss calculation
141
+ recon_loss_pre = F.mse_loss(z_pre, batch_x)
142
+ recon_loss_all = F.mse_loss(z, batch_x)
143
+ recon_loss = recon_loss_pre + recon_loss_all
144
+ loss = (recon_loss + bsq_loss) / 2 # Assuming w_1=w_2=1
145
+
146
+ loss_scaled = loss / config['accumulation_steps']
147
+ current_batch_total_loss += loss.item()
148
+ loss_scaled.backward()
149
+
150
+ # --- Optimizer Step after Accumulation ---
151
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=2.0)
152
+ optimizer.step()
153
+ scheduler.step()
154
+ optimizer.zero_grad()
155
+
156
+ # --- Logging (Master Process Only) ---
157
+ if rank == 0 and (batch_idx_global_train + 1) % config['log_interval'] == 0:
158
+ avg_loss = current_batch_total_loss / config['accumulation_steps']
159
+ print(
160
+ f"[Rank {rank}, Epoch {epoch_idx + 1}/{config['epochs']}, Step {i + 1}/{len(train_loader)}] "
161
+ f"LR {optimizer.param_groups[0]['lr']:.6f}, Loss: {avg_loss:.4f}"
162
+ )
163
+ if rank == 0 and logger:
164
+ avg_loss = current_batch_total_loss / config['accumulation_steps']
165
+ logger.log_metric('train_tokenizer_loss_batch', avg_loss, step=batch_idx_global_train)
166
+ logger.log_metric(f'train_vqvae_vq_loss_each_batch', bsq_loss.item(), step=batch_idx_global_train)
167
+ logger.log_metric(f'train_recon_loss_pre_each_batch', recon_loss_pre.item(), step=batch_idx_global_train)
168
+ logger.log_metric(f'train_recon_loss_each_batch', recon_loss_all.item(), step=batch_idx_global_train)
169
+ logger.log_metric('tokenizer_learning_rate', optimizer.param_groups[0]["lr"], step=batch_idx_global_train)
170
+
171
+ batch_idx_global_train += 1
172
+
173
+ # --- Validation Loop ---
174
+ model.eval()
175
+ tot_val_loss_sum_rank = 0.0
176
+ val_sample_count_rank = 0
177
+ with torch.no_grad():
178
+ for ori_batch_x, _ in val_loader:
179
+ ori_batch_x = ori_batch_x.to(device, non_blocking=True)
180
+ zs, _, _, _ = model(ori_batch_x)
181
+ _, z = zs
182
+ val_loss_item = F.mse_loss(z, ori_batch_x)
183
+
184
+ tot_val_loss_sum_rank += val_loss_item.item() * ori_batch_x.size(0)
185
+ val_sample_count_rank += ori_batch_x.size(0)
186
+
187
+ # Reduce validation losses from all processes
188
+ val_loss_sum_tensor = torch.tensor(tot_val_loss_sum_rank, device=device)
189
+ val_count_tensor = torch.tensor(val_sample_count_rank, device=device)
190
+ dist.all_reduce(val_loss_sum_tensor, op=dist.ReduceOp.SUM)
191
+ dist.all_reduce(val_count_tensor, op=dist.ReduceOp.SUM)
192
+
193
+ avg_val_loss = val_loss_sum_tensor.item() / val_count_tensor.item() if val_count_tensor.item() > 0 else 0
194
+
195
+ # --- End of Epoch Summary & Checkpointing (Master Process Only) ---
196
+ if rank == 0:
197
+ print(f"\n--- Epoch {epoch_idx + 1}/{config['epochs']} Summary ---")
198
+ print(f"Validation Loss: {avg_val_loss:.4f}")
199
+ print(f"Time This Epoch: {format_time(time.time() - epoch_start_time)}")
200
+ print(f"Total Time Elapsed: {format_time(time.time() - start_time)}\n")
201
+ if logger:
202
+ logger.log_metric('val_tokenizer_loss_epoch', avg_val_loss, epoch=epoch_idx)
203
+
204
+ if avg_val_loss < best_val_loss:
205
+ best_val_loss = avg_val_loss
206
+ save_path = f"{save_dir}/checkpoints/best_model"
207
+ model.module.save_pretrained(save_path)
208
+ print(f"Best model saved to {save_path} (Val Loss: {best_val_loss:.4f})")
209
+ if logger:
210
+ logger.log_model("best_model", save_path)
211
+
212
+ dist.barrier() # Ensure all processes finish the epoch before starting the next one.
213
+
214
+ dt_result['best_val_loss'] = best_val_loss
215
+ return model, dt_result
216
+
217
+
218
+ def main(config: dict):
219
+ """
220
+ Main function to orchestrate the DDP training process.
221
+ """
222
+ rank, world_size, local_rank = setup_ddp()
223
+ device = torch.device(f"cuda:{local_rank}")
224
+ set_seed(config['seed'], rank)
225
+
226
+ save_dir = os.path.join(config['save_path'], config['tokenizer_save_folder_name'])
227
+
228
+ # Logger and summary setup (master process only)
229
+ comet_logger, master_summary = None, {}
230
+ if rank == 0:
231
+ os.makedirs(os.path.join(save_dir, 'checkpoints'), exist_ok=True)
232
+ master_summary = {
233
+ 'start_time': strftime("%Y-%m-%dT%H-%M-%S", gmtime()),
234
+ 'save_directory': save_dir,
235
+ 'world_size': world_size,
236
+ }
237
+ if config['use_comet']:
238
+ comet_logger = comet_ml.Experiment(
239
+ api_key=config['comet_config']['api_key'],
240
+ project_name=config['comet_config']['project_name'],
241
+ workspace=config['comet_config']['workspace'],
242
+ )
243
+ comet_logger.add_tag(config['comet_tag'])
244
+ comet_logger.set_name(config['comet_name'])
245
+ comet_logger.log_parameters(config)
246
+ print("Comet Logger Initialized.")
247
+
248
+ dist.barrier() # Ensure save directory is created before proceeding
249
+
250
+ # Model Initialization
251
+ model = KronosTokenizer.from_pretrained(config['pretrained_tokenizer_path'])
252
+ model.to(device)
253
+ model = DDP(model, device_ids=[local_rank], find_unused_parameters=False)
254
+
255
+ if rank == 0:
256
+ print(f"Model Size: {get_model_size(model.module)}")
257
+
258
+ # Start Training
259
+ _, dt_result = train_model(
260
+ model, device, config, save_dir, comet_logger, rank, world_size
261
+ )
262
+
263
+ # Finalize and save summary (master process only)
264
+ if rank == 0:
265
+ master_summary['final_result'] = dt_result
266
+ with open(os.path.join(save_dir, 'summary.json'), 'w') as f:
267
+ json.dump(master_summary, f, indent=4)
268
+ print('Training finished. Summary file saved.')
269
+ if comet_logger:
270
+ comet_logger.end()
271
+
272
+ cleanup_ddp()
273
+
274
+
275
+ if __name__ == '__main__':
276
+ # Usage: torchrun --standalone --nproc_per_node=NUM_GPUS train_tokenizer.py
277
+ if "WORLD_SIZE" not in os.environ:
278
+ raise RuntimeError("This script must be launched with `torchrun`.")
279
+
280
+ config_instance = Config()
281
+ main(config_instance.__dict__)
Kronos/finetune/utils/__init__.py ADDED
File without changes
Kronos/finetune/utils/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (139 Bytes). View file
 
Kronos/finetune/utils/__pycache__/training_utils.cpython-39.pyc ADDED
Binary file (3.92 kB). View file
 
Kronos/finetune/utils/training_utils.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import datetime
4
+ import numpy as np
5
+ import torch
6
+ import torch.distributed as dist
7
+
8
+
9
+ def setup_ddp():
10
+ """
11
+ Initializes the distributed data parallel environment.
12
+
13
+ This function relies on environment variables set by `torchrun` or a similar
14
+ launcher. It initializes the process group and sets the CUDA device for the
15
+ current process.
16
+
17
+ Returns:
18
+ tuple: A tuple containing (rank, world_size, local_rank).
19
+ """
20
+ if not dist.is_available():
21
+ raise RuntimeError("torch.distributed is not available.")
22
+
23
+ dist.init_process_group(backend="nccl")
24
+ rank = int(os.environ["RANK"])
25
+ world_size = int(os.environ["WORLD_SIZE"])
26
+ local_rank = int(os.environ["LOCAL_RANK"])
27
+ torch.cuda.set_device(local_rank)
28
+ print(
29
+ f"[DDP Setup] Global Rank: {rank}/{world_size}, "
30
+ f"Local Rank (GPU): {local_rank} on device {torch.cuda.current_device()}"
31
+ )
32
+ return rank, world_size, local_rank
33
+
34
+
35
+ def cleanup_ddp():
36
+ """Cleans up the distributed process group."""
37
+ if dist.is_initialized():
38
+ dist.destroy_process_group()
39
+
40
+
41
+ def set_seed(seed: int, rank: int = 0):
42
+ """
43
+ Sets the random seed for reproducibility across all relevant libraries.
44
+
45
+ Args:
46
+ seed (int): The base seed value.
47
+ rank (int): The process rank, used to ensure different processes have
48
+ different seeds, which can be important for data loading.
49
+ """
50
+ actual_seed = seed + rank
51
+ random.seed(actual_seed)
52
+ np.random.seed(actual_seed)
53
+ torch.manual_seed(actual_seed)
54
+ if torch.cuda.is_available():
55
+ torch.cuda.manual_seed_all(actual_seed)
56
+ # The two lines below can impact performance, so they are often
57
+ # reserved for final experiments where reproducibility is critical.
58
+ torch.backends.cudnn.deterministic = True
59
+ torch.backends.cudnn.benchmark = False
60
+
61
+
62
+ def get_model_size(model: torch.nn.Module) -> str:
63
+ """
64
+ Calculates the number of trainable parameters in a PyTorch model and returns
65
+ it as a human-readable string.
66
+
67
+ Args:
68
+ model (torch.nn.Module): The PyTorch model.
69
+
70
+ Returns:
71
+ str: A string representing the model size (e.g., "175.0B", "7.1M", "50.5K").
72
+ """
73
+ total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
74
+
75
+ if total_params >= 1e9:
76
+ return f"{total_params / 1e9:.1f}B" # Billions
77
+ elif total_params >= 1e6:
78
+ return f"{total_params / 1e6:.1f}M" # Millions
79
+ else:
80
+ return f"{total_params / 1e3:.1f}K" # Thousands
81
+
82
+
83
+ def reduce_tensor(tensor: torch.Tensor, world_size: int, op=dist.ReduceOp.SUM) -> torch.Tensor:
84
+ """
85
+ Reduces a tensor's value across all processes in a distributed setup.
86
+
87
+ Args:
88
+ tensor (torch.Tensor): The tensor to be reduced.
89
+ world_size (int): The total number of processes.
90
+ op (dist.ReduceOp, optional): The reduction operation (SUM, AVG, etc.).
91
+ Defaults to dist.ReduceOp.SUM.
92
+
93
+ Returns:
94
+ torch.Tensor: The reduced tensor, which will be identical on all processes.
95
+ """
96
+ rt = tensor.clone()
97
+ dist.all_reduce(rt, op=op)
98
+ # Note: `dist.ReduceOp.AVG` is available in newer torch versions.
99
+ # For compatibility, manual division is sometimes used after a SUM.
100
+ if op == dist.ReduceOp.AVG:
101
+ rt /= world_size
102
+ return rt
103
+
104
+
105
+ def format_time(seconds: float) -> str:
106
+ """
107
+ Formats a duration in seconds into a human-readable H:M:S string.
108
+
109
+ Args:
110
+ seconds (float): The total seconds.
111
+
112
+ Returns:
113
+ str: The formatted time string (e.g., "0:15:32").
114
+ """
115
+ return str(datetime.timedelta(seconds=int(seconds)))
116
+
117
+
118
+
Kronos/finetune_csv/README.md ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Kronos Fine-tuning on Custom CSV Datasets
2
+
3
+ This module provides a comprehensive pipeline for fine-tuning Kronos models on your own CSV-formatted financial data. It supports both sequential training (tokenizer followed by predictor) and individual component training, with full distributed training capabilities.
4
+
5
+
6
+ ## 1. Data Preparation
7
+
8
+ ### Required Data Format
9
+
10
+ Your CSV file must contain the following columns:
11
+ - `timestamps`: DateTime stamps for each data point
12
+ - `open`: Opening price
13
+ - `high`: Highest price
14
+ - `low`: Lowest price
15
+ - `close`: Closing price
16
+ - `volume`: Trading volume
17
+ - `amount`: Trading amount
18
+
19
+ (volume and amount can be 0 if not available)
20
+
21
+ ### Sample Data Format
22
+
23
+ | timestamps | open | close | high | low | volume | amount |
24
+ |------------|------|-------|------|-----|--------|--------|
25
+ | 2019/11/26 9:35 | 182.45215 | 184.45215 | 184.95215 | 182.45215 | 15136000 | 0 |
26
+ | 2019/11/26 9:40 | 184.35215 | 183.85215 | 184.55215 | 183.45215 | 4433300 | 0 |
27
+ | 2019/11/26 9:45 | 183.85215 | 183.35215 | 183.95215 | 182.95215 | 3070900 | 0 |
28
+
29
+ > **Reference**: Check `data/HK_ali_09988_kline_5min_all.csv` for a complete example of the proper data format.
30
+
31
+
32
+ ## 2. Config Preparation
33
+
34
+
35
+ Please edit the correct data path & pretrained model path and set your training parameters.
36
+
37
+ ```yaml
38
+ # Data configuration
39
+ data:
40
+ data_path: "/path/to/your/data.csv"
41
+ lookback_window: 512 # Historical data points to use
42
+ predict_window: 48 # Future points to predict
43
+ max_context: 512 # Maximum context length
44
+
45
+ ...
46
+
47
+ ```
48
+ There are some other settings here, please see `configs/config_ali09988_candle-5min.yaml` for more comments.
49
+
50
+ ## 3. Training
51
+
52
+ ### Method 1: Sequential Training (Recommended)
53
+
54
+ The `train_sequential.py` script handles the complete training pipeline automatically:
55
+
56
+ ```bash
57
+ # Complete training (tokenizer + predictor)
58
+ python train_sequential.py --config configs/config_ali09988_candle-5min.yaml
59
+
60
+ # Skip existing models
61
+ python train_sequential.py --config configs/config_ali09988_candle-5min.yaml --skip-existing
62
+
63
+ # Only train tokenizer
64
+ python train_sequential.py --config configs/config_ali09988_candle-5min.yaml --skip-basemodel
65
+
66
+ # Only train predictor
67
+ python train_sequential.py --config configs/config_ali09988_candle-5min.yaml --skip-tokenizer
68
+ ```
69
+
70
+ ### Method 2: Individual Component Training
71
+
72
+ Train each component separately for more control:
73
+
74
+ ```bash
75
+ # Step 1: Train tokenizer
76
+ python finetune_tokenizer.py --config configs/config_ali09988_candle-5min.yaml
77
+
78
+ # Step 2: Train predictor (requires fine-tuned tokenizer)
79
+ python finetune_base_model.py --config configs/config_ali09988_candle-5min.yaml
80
+ ```
81
+
82
+ ### DDP Training
83
+
84
+ For faster training on multiple GPUs:
85
+
86
+ ```bash
87
+ # Set communication backend (nccl for NVIDIA GPUs, gloo for CPU/mixed)
88
+ DIST_BACKEND=nccl \
89
+ torchrun --standalone --nproc_per_node=8 train_sequential.py --config configs/config_ali09988_candle-5min.yaml
90
+ ```
91
+
92
+ ## 4. Training Results
93
+
94
+ The training process generates several outputs:
95
+
96
+ ### Model Checkpoints
97
+ - **Tokenizer**: Saved to `{base_save_path}/{exp_name}/tokenizer/best_model/`
98
+ - **Predictor**: Saved to `{base_save_path}/{exp_name}/basemodel/best_model/`
99
+
100
+ ### Training Logs
101
+ - **Console output**: Real-time training progress and metrics
102
+ - **Log files**: Detailed logs saved to `{base_save_path}/logs/`
103
+ - **Validation tracking**: Best models are saved based on validation loss
104
+
105
+ ## 5. Prediction Vis
106
+
107
+ The following images show example training results on alibaba (HK stock) data:
108
+
109
+ ![Training Result 1](examples/HK_ali_09988_kline_5min_all_historical_20250919_073929.png)
110
+
111
+ ![Training Result 2](examples/HK_ali_09988_kline_5min_all_historical_20250919_073944.png)
112
+
113
+ ![Training Result 3](examples/HK_ali_09988_kline_5min_all_historical_20250919_074012.png)
114
+
115
+ ![Training Result 4](examples/HK_ali_09988_kline_5min_all_historical_20250919_074042.png)
116
+
117
+ ![Training Result 5](examples/HK_ali_09988_kline_5min_all_historical_20250919_074251.png)
118
+
119
+
120
+