log
2026-07-09 4baa0512c3590c50330ba4c487f328140e16fc2b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
#!/usr/bin/env python3
"""
持仓监控脚本
功能:计算组合波动率、VaR、行业偏离度、个股集中度,生成每日风险报告
"""
 
import sys
import os
import json
import pickle as pkl
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Tuple
 
class PortfolioMonitor:
    """持仓监控器"""
 
    def __init__(self):
        """初始化"""
        self.portfolio_file = 'data/portfolio_state.json'
        self.data_file = 'data/akshare_real_data_fixed.pkl'
        self.risk_report_file = 'reports/daily_risk_report.json'
 
    def load_portfolio(self) -> Dict:
        """加载持仓状态"""
        if os.path.exists(self.portfolio_file):
            try:
                with open(self.portfolio_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"加载持仓失败: {e}")
        return {'positions': []}
 
    def load_stock_data(self) -> pd.DataFrame:
        """加载股票数据"""
        try:
            with open(self.data_file, 'rb') as f:
                df = pkl.load(f)
            return df
        except Exception as e:
            print(f"加载数据失败: {e}")
            return pd.DataFrame()
 
    def calculate_portfolio_volatility(self, portfolio: Dict, stock_data: pd.DataFrame,
                                      days: int = 20) -> Dict:
        """
        计算组合波动率(20日年化)
 
        Args:
            portfolio: 持仓数据
            stock_data: 股票数据
            days: 计算周期
 
        Returns:
            波动率信息字典
        """
        if not portfolio.get('positions'):
            return {'volatility': 0, 'status': '无持仓', 'level': 'info', 'value': 'N/A'}
 
        positions = portfolio['positions']
 
        # 获取持仓股票代码
        stock_codes = [pos['stock_code'] for pos in positions]
        weights = [pos.get('current_value', 0) for pos in positions]
        total_weight = sum(weights)
 
        if total_weight == 0:
            return {'volatility': 0, 'status': '空仓', 'level': 'info', 'value': 'N/A'}
 
        weights = [w / total_weight for w in weights]
 
        # 计算每只股票的波动率
        stock_volatilities = []
 
        for code, weight in zip(stock_codes, weights):
            # 从数据中获取该股票的20日收益率
            try:
                # 处理股票代码格式:sh601899 -> 601899 或 300000
                code_num = code.replace('sh', '').replace('sz', '').replace('cn', '')
                
                # 尝试多种匹配方式
                stock_hist = stock_data[
                    (stock_data['stock_code'] == code) | 
                    (stock_data['stock_code'] == code_num) |
                    (stock_data['stock_code'].str.contains(code_num, na=False))
                ].copy()
 
                if len(stock_hist) < days:
                    # 如果数据不足,跳过
                    continue
 
                # 计算日收益率
                stock_hist = stock_hist.sort_values('date_dt')
                stock_hist['return'] = stock_hist['close'].pct_change()
 
                # 计算波动率(标准差)
                returns = stock_hist['return'].dropna().tail(days)
 
                if len(returns) > 0:
                    daily_vol = returns.std() * np.sqrt(252)  # 年化
                    stock_volatilities.append(daily_vol * weight)
            except Exception as e:
                print(f"计算{code}波动率失败: {e}")
                continue
 
        # 组合波动率 = sqrt(sum(w_i^2 * sigma_i^2 + 2 * sum(w_i * w_j * sigma_i * sigma_j * rho_ij)))
        # 这里简化使用加权平均
        portfolio_vol = sum(stock_volatilities)
 
        # 判断状态
        if portfolio_vol < 0.20:
            status = '正常'
            level = 'info'
        elif portfolio_vol < 0.25:
            status = '警告'
            level = 'warning'
        else:
            status = '危险'
            level = 'danger'
 
        return {
            'volatility': float(portfolio_vol),
            'status': status,
            'level': level,
            'value': f'{portfolio_vol:.1%}'
        }
 
    def calculate_var(self, portfolio: Dict, stock_data: pd.DataFrame,
                      days: int = 10, confidence: float = 0.95) -> Dict:
        """
        计算VaR(Value at Risk)
 
        Args:
            portfolio: 持仓数据
            stock_data: 股票数据
            days: 计算周期
            confidence: 置信度
 
        Returns:
            VaR信息字典
        """
        if not portfolio.get('positions'):
            return {'var': 0, 'status': '无持仓', 'level': 'info', 'value': 'N/A'}
 
        positions = portfolio['positions']
 
        # 获取持仓股票代码和权重
        stock_codes = [pos['stock_code'] for pos in positions]
        weights = [pos.get('current_value', 0) for pos in positions]
        total_weight = sum(weights)
 
        if total_weight == 0:
            return {'var': 0, 'status': '空仓', 'level': 'info', 'value': 'N/A'}
 
        weights = [w / total_weight for w in weights]
 
        # 获取每只股票的历史收益率
        all_returns = []
 
        for code, weight in zip(stock_codes, weights):
            try:
                # 处理股票代码格式
                code_num = code.replace('sh', '').replace('sz', '').replace('cn', '')
                
                stock_hist = stock_data[
                    (stock_data['stock_code'] == code) | 
                    (stock_data['stock_code'] == code_num) |
                    (stock_data['stock_code'].str.contains(code_num, na=False))
                ].copy()
 
                if len(stock_hist) < days:
                    continue
 
                stock_hist = stock_hist.sort_values('date_dt')
                stock_hist['return'] = stock_hist['close'].pct_change()
 
                returns = stock_hist['return'].dropna().tail(days)
 
                # 加权收益率
                weighted_returns = returns * weight
                all_returns.extend(weighted_returns.tolist())
            except Exception as e:
                print(f"计算{code}收益率失败: {e}")
                continue
 
        if not all_returns:
            return {'var': 0, 'status': '数据不足', 'level': 'warning', 'value': 'N/A', 'confidence': f'{confidence:.0%}'}
 
        # 计算组合收益率
        portfolio_returns = pd.Series(all_returns)
 
        # 计算VaR(历史模拟法)
        var = np.percentile(portfolio_returns, (1 - confidence) * 100)
 
        # VaR为负数,表示损失
        var_loss = -var
 
        # 判断状态
        if var_loss < 0.10:
            status = '正常'
            level = 'info'
        elif var_loss < 0.15:
            status = '警告'
            level = 'warning'
        else:
            status = '危险'
            level = 'danger'
 
        return {
            'var': float(var_loss),
            'status': status,
            'level': level,
            'value': f'{var_loss:.1%}',
            'confidence': f'{confidence:.0%}'
        }
 
    def calculate_industry_deviation(self, portfolio: Dict,
                                    benchmark: Dict = None) -> Dict:
        """
        计算行业偏离度
 
        Args:
            portfolio: 持仓数据
            benchmark: 基准行业权重
 
        Returns:
            行业偏离度信息
        """
        if not portfolio.get('positions'):
            return {'deviations': [], 'status': '无持仓', 'level': 'info'}
 
        positions = portfolio['positions']
 
        # 统计行业权重
        industry_weights = {}
        total_weight = sum(pos.get('current_value', 0) for pos in positions)
 
        if total_weight == 0:
            return {'deviations': [], 'status': '空仓', 'level': 'info'}
 
        for pos in positions:
            industry = pos.get('industry', '其他')
            weight = pos.get('current_value', 0) / total_weight * 100
            industry_weights[industry] = industry_weights.get(industry, 0) + weight
 
        # 如果没有提供基准,使用等权重作为基准
        if benchmark is None:
            num_industries = len(industry_weights)
            if num_industries == 0:
                return {'deviations': [], 'status': '无行业数据', 'level': 'info'}
            benchmark = {industry: 100 / num_industries for industry in industry_weights}
 
        # 计算偏离度
        deviations = []
        has_warning = False
 
        for industry, portfolio_weight in industry_weights.items():
            benchmark_weight = benchmark.get(industry, 100 / len(benchmark))
            deviation = portfolio_weight - benchmark_weight
 
            # 判断状态
            if abs(deviation) > 12:
                status = '警告'
                level = 'warning'
                has_warning = True
            elif abs(deviation) > 20:
                status = '危险'
                level = 'danger'
                has_warning = True
            else:
                status = '正常'
                level = 'info'
 
            deviations.append({
                'industry': industry,
                'portfolio_weight': round(portfolio_weight, 1),
                'benchmark_weight': round(benchmark_weight, 1),
                'deviation': round(deviation, 1),
                'status': status,
                'level': level
            })
 
        overall_status = '警告' if has_warning else '正常'
 
        return {
            'deviations': deviations,
            'status': overall_status,
            'level': 'warning' if has_warning else 'info'
        }
 
    def calculate_concentration(self, portfolio: Dict) -> Dict:
        """
        计算个股集中度
 
        Args:
            portfolio: 持仓数据
 
        Returns:
            集中度信息
        """
        if not portfolio.get('positions'):
            return {'concentrations': [], 'status': '无持仓', 'level': 'info'}
 
        positions = portfolio['positions']
        total_weight = sum(pos.get('current_value', 0) for pos in positions)
 
        if total_weight == 0:
            return {'concentrations': [], 'status': '空仓', 'level': 'info'}
 
        concentrations = []
        has_warning = False
 
        for pos in positions:
            weight = pos.get('current_value', 0) / total_weight * 100
 
            # 判断状态
            if weight > 15:
                status = '危险'
                level = 'danger'
                has_warning = True
            elif weight > 12:
                status = '警告'
                level = 'warning'
                has_warning = True
            else:
                status = '正常'
                level = 'info'
 
            concentrations.append({
                'code': pos.get('stock_code', 'N/A'),
                'name': pos.get('name', 'N/A'),
                'weight': round(weight, 1),
                'status': status,
                'level': level
            })
 
        overall_status = '警告' if has_warning else '正常'
 
        return {
            'concentrations': concentrations,
            'status': overall_status,
            'level': 'warning' if has_warning else 'info'
        }
 
    def calculate_max_drawdown(self, portfolio: Dict, stock_data: pd.DataFrame) -> Dict:
        """
        计算最大回撤
 
        Args:
            portfolio: 持仓数据
            stock_data: 股票数据
 
        Returns:
            最大回撤信息
        """
        if not portfolio.get('positions'):
            return {'max_drawdown': 0, 'status': '无持仓', 'level': 'info', 'value': 'N/A'}
 
        positions = portfolio['positions']
 
        # 获取持仓股票代码
        stock_codes = [pos['stock_code'] for pos in positions]
        weights = [pos.get('current_value', 0) for pos in positions]
        total_weight = sum(weights)
 
        if total_weight == 0:
            return {'max_drawdown': 0, 'status': '空仓', 'level': 'info', 'value': 'N/A'}
 
        weights = [w / total_weight for w in weights]
 
        # 计算组合净值曲线
        portfolio_values = []
 
        for code, weight in zip(stock_codes, weights):
            try:
                # 尝试多种匹配方式
                code_num = code.replace('sh', '').replace('sz', '').replace('cn', '')
                stock_hist = stock_data[
                    (stock_data['stock_code'] == code) | 
                    (stock_data['stock_code'] == code_num) |
                    (stock_data['stock_code'].str.contains(code_num, na=False))
                ].copy()
 
                if len(stock_hist) == 0:
                    continue
 
                stock_hist = stock_hist.sort_values('date_dt')
 
                # 检查close列是否存在且有值
                if 'close' not in stock_hist.columns or stock_hist['close'].isnull().all():
                    continue
 
                # 归一化价格(避免除零错误)
                first_close = stock_hist['close'].iloc[0]
                if first_close == 0:
                    continue
                
                normalized_prices = stock_hist['close'] / first_close
 
                # 加权
                weighted_values = normalized_prices * weight
                weighted_values_list = weighted_values.tolist()
 
                if len(portfolio_values) == 0:
                    portfolio_values = weighted_values_list
                else:
                    # 对齐日期(简化处理)
                    min_len = min(len(portfolio_values), len(weighted_values_list))
                    portfolio_values = [
                        portfolio_values[i] + weighted_values_list[i]
                        for i in range(min_len)
                    ]
            except Exception as e:
                print(f"计算{code}净值失败: {str(e)}")
                continue
 
        if len(portfolio_values) < 2:
            return {'max_drawdown': 0, 'status': '数据不足', 'level': 'warning'}
 
        # 计算回撤
        portfolio_series = pd.Series(portfolio_values)
        rolling_max = portfolio_series.expanding().max()
        drawdown = (portfolio_series - rolling_max) / rolling_max
        max_drawdown = drawdown.min()
 
        # 判断状态
        if max_drawdown > -0.10:
            status = '正常'
            level = 'info'
        elif max_drawdown > -0.15:
            status = '警告'
            level = 'warning'
        else:
            status = '危险'
            level = 'danger'
 
        return {
            'max_drawdown': float(max_drawdown),
            'status': status,
            'level': level,
            'value': f'{max_drawdown:.1%}'
        }
 
    def generate_risk_report(self) -> Dict:
        """生成每日风险报告"""
        print("=" * 60)
        print("📊 持仓风险监控")
        print("=" * 60)
 
        # 加载数据
        portfolio = self.load_portfolio()
        stock_data = self.load_stock_data()
 
        print(f"持仓数量: {len(portfolio.get('positions', []))}")
        print(f"数据日期范围: {len(stock_data)}条记录")
        print()
 
        # 计算各项指标
        volatility = self.calculate_portfolio_volatility(portfolio, stock_data)
        print(f"✓ 组合波动率: {volatility['value']} ({volatility['status']})")
 
        var = self.calculate_var(portfolio, stock_data)
        print(f"✓ VaR(10日,95%): {var['value']} ({var['status']})")
 
        drawdown = self.calculate_max_drawdown(portfolio, stock_data)
        print(f"✓ 最大回撤: {drawdown.get('value', '0%')} ({drawdown.get('status', 'N/A')})")
 
        industry = self.calculate_industry_deviation(portfolio)
        print(f"✓ 行业偏离度: {industry['status']}")
 
        concentration = self.calculate_concentration(portfolio)
        print(f"✓ 个股集中度: {concentration['status']}")
 
        print()
 
        # 汇总报告
        report = {
            'report_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'risk_indicators': {
                'volatility': volatility,
                'var': var,
                'max_drawdown': drawdown
            },
            'industry_deviation': industry,
            'concentration': concentration,
            'overall_status': self._calculate_overall_status([
                volatility['level'],
                var['level'],
                drawdown.get('level', 'info'),
                industry['level'],
                concentration['level']
            ])
        }
 
        # 保存报告
        os.makedirs(os.path.dirname(self.risk_report_file), exist_ok=True)
        with open(self.risk_report_file, 'w', encoding='utf-8') as f:
            json.dump(report, f, ensure_ascii=False, indent=2)
 
        print(f"✓ 风险报告已保存: {self.risk_report_file}")
        print("=" * 60)
        print()
 
        return report
 
    def _calculate_overall_status(self, levels: List[str]) -> str:
        """计算整体状态"""
        if 'danger' in levels:
            return 'danger'
        elif 'warning' in levels:
            return 'warning'
        else:
            return 'normal'
 
    def format_report(self, report: Dict) -> str:
        """格式化报告为文本"""
        lines = []
        lines.append('📊 每日风险监控')
        lines.append('')
 
        # 风险指标
        lines.append('一、风险指标')
        risk = report['risk_indicators']
        lines.append(f"• 组合波动率:{risk['volatility']['value']}({risk['volatility']['status']})")
        var_confidence = risk['var'].get('confidence', '95%')
        lines.append(f"• VaR({var_confidence}):{risk['var']['value']}({risk['var']['status']})")
        drawdown_val = risk['max_drawdown'].get('value', '0%')
        drawdown_status = risk['max_drawdown'].get('status', 'N/A')
        lines.append(f"• 最大回撤:{drawdown_val}({drawdown_status})")
        lines.append('')
 
        # 行业偏离度
        lines.append('二、行业偏离度')
        deviations = report['industry_deviation'].get('deviations', [])
        if deviations:
            for dev in deviations[:3]:
                sign = '+' if dev['deviation'] > 0 else ''
                lines.append(f"• {dev['industry']}:{sign}{dev['deviation']}%({dev['status']})")
        else:
            lines.append(f"• {report['industry_deviation'].get('status', '无数据')}")
        lines.append('')
 
        # 个股集中度
        lines.append('三、个股集中度')
        concentrations = report['concentration'].get('concentrations', [])
        if concentrations:
            for conc in concentrations[:3]:
                lines.append(f"• {conc['name']}:{conc['weight']}%({conc['status']})")
        else:
            lines.append(f"• {report['concentration'].get('status', '无数据')}")
        lines.append('')
 
        return '\n'.join(lines)
 
def main():
    """主函数"""
    monitor = PortfolioMonitor()
    report = monitor.generate_risk_report()
 
    # 打印格式化报告
    print(monitor.format_report(report))
 
    return report
 
if __name__ == "__main__":
    main()