log
2026-07-11 e565b77640285d6c433c9edf82505157733314ca
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
#!/usr/bin/env python3
"""
P1任务:风控体系完善模块
功能:
1. 策略容量评估(最大资金容量)
2. 冲击成本评估
3. 流动性风险分析
4. 风格暴露分析(大盘/小盘、价值/成长)
5. 因子拥挤度分析
 
目标:建立完整的风险控制体系,确保系统安全稳健
"""
 
import pandas as pd
import numpy as np
from typing import Dict, List, Tuple, Optional
from datetime import datetime
from collections import defaultdict
import json
import os
import warnings
 
warnings.filterwarnings('ignore')
 
 
class RiskControlSystem:
    """风控体系"""
    
    def __init__(self, data_path: str, config: Dict = None):
        self.data_path = data_path
        self.config = config or self._default_config()
        self.df = None
        self.results = {}
        self.filters = {
            'ST股票': lambda row: not str(row.get('name', '')).startswith('ST'),
            '停牌股票': lambda row: row.get('is_suspended', 0) == 0,
            '退市股票': lambda row: not str(row.get('name', '')).startswith('*ST'),
        }
        self.control_summary = {}
        self._load_data()
    
    def _default_config(self) -> Dict:
        """默认配置"""
        return {
            'max_position_ratio': 0.10,
            'max_turnover_rate': 0.50,
            'liquidity_threshold': 10000000,
            'impact_cost_levels': [0.01, 0.05, 0.10],
            'base_impact_cost': 0.0005,
            'impact_cost_sqrt': 0.001,
            'small_cap_threshold': 0.4,
            'pe_value_threshold': 20,
            'growth_rate_threshold': 0.15,
            'top_n_concentration': 10,
            'hhi_threshold': 0.02,
        }
    
    def _load_data(self):
        """加载数据"""
        print(f"📂 加载数据: {self.data_path}")
        self.df = pd.read_pickle(self.data_path)
        
        if 'date' in self.df.columns:
            self.df['date'] = pd.to_datetime(self.df['date'])
        
        self.df = self.df.sort_values('date')
        print(f"✓ 数据加载成功: {self.df.shape}")
    
    def calculate_strategy_capacity(self, initial_capital: float = 10000000) -> Dict:
        """P1-1: 策略容量评估"""
        print("\n" + "=" * 70)
        print("📊 P1-1: 策略容量评估")
        print("=" * 70)
        
        capacity_analysis = {}
        
        # 基于流动性估算
        if 'volume' in self.df.columns:
            avg_daily_value = self.df.groupby('stock_code').apply(
                lambda x: (x['close'] * x['volume']).mean()
            )
            liquidity_capacity = avg_daily_value.sum() * 0.1  # 日成交额的10%
        else:
            avg_price = self.df.groupby('stock_code')['close'].mean()
            liquidity_capacity = avg_price.sum() * 1000000  # 简化估算
        
        # 基于换手率估算
        turnover_capacity = initial_capital * self.config['max_turnover_rate'] * 12
        
        # 综合容量
        max_capacity = min(liquidity_capacity, turnover_capacity)
        recommended_capacity = max_capacity * 0.8  # 80%安全边际
        
        capacity_analysis = {
            'liquidity_capacity': float(liquidity_capacity),
            'turnover_capacity': float(turnover_capacity),
            'max_capacity': float(max_capacity),
            'recommended_capacity': float(recommended_capacity),
            'capacity_grade': 'A' if recommended_capacity >= initial_capital * 5 else 'B' if recommended_capacity >= initial_capital * 2 else 'C'
        }
        
        print(f"  流动性容量: ¥{liquidity_capacity:,.0f}")
        print(f"  换手率容量: ¥{turnover_capacity:,.0f}")
        print(f"  推荐容量:   ¥{recommended_capacity:,.0f}")
        print(f"  容量评级:   {capacity_analysis['capacity_grade']}")
        
        self.results['strategy_capacity'] = capacity_analysis
        return capacity_analysis
    
    def assess_impact_cost(self, trade_amounts: List[float] = None) -> Dict:
        """P1-2: 冲击成本评估"""
        print("\n" + "=" * 70)
        print("📊 P1-2: 冲击成本评估")
        print("=" * 70)
        
        if trade_amounts is None:
            trade_amounts = [100000, 500000, 1000000, 5000000, 10000000]
        
        impact_analysis = {'impact_by_amount': {}}
        
        base_impact = self.config['base_impact_cost']
        impact_sqrt = self.config['impact_cost_sqrt']
        
        for amount in trade_amounts:
            impact = base_impact * amount + impact_sqrt * np.sqrt(amount) * amount
            impact_rate = impact / amount
            
            risk_level = "低" if impact_rate < 0.001 else "中" if impact_rate < 0.003 else "高"
            
            impact_analysis['impact_by_amount'][f'{int(amount/10000)}万'] = {
                'amount': float(amount),
                'impact_rate': float(impact_rate),
                'risk_level': risk_level
            }
        
        print(f"  冲击成本分析:")
        for label, data in impact_analysis['impact_by_amount'].items():
            print(f"    {label}: {data['impact_rate']:.4%} ({data['risk_level']})")
        
        self.results['impact_cost'] = impact_analysis
        return impact_analysis
    
    def analyze_liquidity_risk(self) -> Dict:
        """P1-3: 流动性风险分析"""
        print("\n" + "=" * 70)
        print("📊 P1-3: 流动性风险分析")
        print("=" * 70)
        
        liquidity_analysis = {}
        
        # 个股流动性
        if 'volume' in self.df.columns:
            self.df['turnover'] = self.df['close'] * self.df['volume']
            stock_liquidity = self.df.groupby('stock_code')['turnover'].agg(['mean', 'std'])
            stock_liquidity['cv'] = stock_liquidity['std'] / stock_liquidity['mean']
            
            high_risk_count = (stock_liquidity['cv'] > 0.5).sum()
            total_stocks = len(stock_liquidity)
            
            liquidity_analysis = {
                'high_risk_count': int(high_risk_count),
                'total_stocks': int(total_stocks),
                'high_risk_ratio': float(high_risk_count / total_stocks),
                'liquidity_grade': '高风险' if high_risk_count > total_stocks * 0.3 else '中风险' if high_risk_count > total_stocks * 0.1 else '低风险'
            }
        else:
            liquidity_analysis = {
                'liquidity_grade': '未知(缺少成交量数据)'
            }
        
        print(f"  高风险股票数: {liquidity_analysis.get('high_risk_count', 0)}")
        print(f"  流动性评级: {liquidity_analysis['liquidity_grade']}")
        
        self.results['liquidity_risk'] = liquidity_analysis
        return liquidity_analysis
    
    def analyze_style_exposure(self) -> Dict:
        """P1-4: 风格暴露分析"""
        print("\n" + "=" * 70)
        print("📊 P1-4: 风格暴露分析")
        print("=" * 70)
        
        style_analysis = {}
        
        # 大盘/小盘
        avg_price = self.df.groupby('stock_code')['close'].mean()
        price_quantile = avg_price.rank(pct=True)
        
        large_cap_count = (price_quantile >= self.config['small_cap_threshold']).sum()
        total_stocks = len(avg_price)
        
        style_analysis['size_exposure'] = {
            'large_cap_ratio': float(large_cap_count / total_stocks),
            'small_cap_ratio': float((total_stocks - large_cap_count) / total_stocks),
            'size_tilt': '大盘倾向' if large_cap_count > total_stocks * 0.6 else '小盘倾向' if large_cap_count < total_stocks * 0.4 else '均衡'
        }
        
        # 价值/成长
        if 'pe_ttm' in self.df.columns:
            avg_pe = self.df.groupby('stock_code')['pe_ttm'].mean()
            value_count = (avg_pe <= self.config['pe_value_threshold']).sum()
            
            style_analysis['value_growth_exposure'] = {
                'value_ratio': float(value_count / total_stocks),
                'growth_ratio': float((total_stocks - value_count) / total_stocks),
                'style_tilt': '价值倾向' if value_count > total_stocks * 0.6 else '成长倾向' if value_count < total_stocks * 0.4 else '均衡'
            }
        
        print(f"  大小盘风格: {style_analysis['size_exposure']['size_tilt']}")
        if 'value_growth_exposure' in style_analysis:
            print(f"  价值成长风格: {style_analysis['value_growth_exposure']['style_tilt']}")
        
        self.results['style_exposure'] = style_analysis
        return style_analysis
    
    def analyze_factor_crowding(self) -> Dict:
        """P1-5: 因子拥挤度分析"""
        print("\n" + "=" * 70)
        print("📊 P1-5: 因子拥挤度分析")
        print("=" * 70)
        
        crowding_analysis = {}
        
        # 持仓集中度(基于因子得分)
        if 'factor_score' in self.df.columns and 'month' in self.df.columns:
            top_stocks = []
            for month in self.df['month'].unique():
                month_data = self.df[self.df['month'] == month]
                top_10 = month_data.nlargest(10, 'factor_score')['stock_code'].tolist()
                top_stocks.extend(top_10)
            
            stock_freq = pd.Series(top_stocks).value_counts()
            total_selections = len(top_stocks)
            
            hhi = float(((stock_freq / total_selections) ** 2).sum())
            
            crowding_analysis = {
                'unique_stocks': len(stock_freq),
                'total_selections': total_selections,
                'hhi': hhi,
                'top_10_concentration': float(stock_freq.head(10).sum() / total_selections),
                'crowding_grade': '高拥挤' if hhi > 0.02 else '中拥挤' if hhi > 0.01 else '低拥挤'
            }
        else:
            crowding_analysis = {
                'crowding_grade': '未知(缺少因子得分数据)'
            }
        
        print(f"  HHI指数: {crowding_analysis.get('hhi', 0):.4f}")
        print(f"  拥挤度评级: {crowding_analysis['crowding_grade']}")
        
        self.results['factor_crowding'] = crowding_analysis
        return crowding_analysis
    
    def generate_risk_report(self) -> Dict:
        """生成综合风控报告"""
        print("\n" + "=" * 70)
        print("🔍 综合风控评估报告")
        print("=" * 70)
        
        risk_report = {
            'overall_risk_level': 'unknown',
            'risk_score': 0,
            'issues': [],
            'recommendations': []
        }
        
        scores = []
        
        # 容量风险
        if 'strategy_capacity' in self.results:
            capacity_grade = self.results['strategy_capacity']['capacity_grade']
            capacity_score = 90 if capacity_grade == 'A' else 70 if capacity_grade == 'B' else 50
            scores.append(capacity_score)
        
        # 流动性风险
        if 'liquidity_risk' in self.results:
            liquidity_grade = self.results['liquidity_risk']['liquidity_grade']
            liquidity_score = 90 if '低' in liquidity_grade else 70 if '中' in liquidity_grade else 50
            scores.append(liquidity_score)
        
        # 拥挤度风险
        if 'factor_crowding' in self.results:
            crowding_grade = self.results['factor_crowding']['crowding_grade']
            crowding_score = 90 if '低' in crowding_grade else 70 if '中' in crowding_grade else 50
            scores.append(crowding_score)
        
        if scores:
            risk_report['risk_score'] = int(np.mean(scores))
        
        # 风险等级
        score = risk_report['risk_score']
        if score >= 80:
            risk_report['overall_risk_level'] = 'LOW (低风险)'
        elif score >= 60:
            risk_report['overall_risk_level'] = 'MEDIUM (中等风险)'
        else:
            risk_report['overall_risk_level'] = 'HIGH (高风险)'
        
        print(f"\n🎯 综合风险评分: {risk_report['risk_score']}/100")
        print(f"   风险等级: {risk_report['overall_risk_level']}")
        
        self.results['risk_report'] = risk_report
        return risk_report
    
    def run_full_analysis(self) -> Dict:
        """运行完整风控分析"""
        print("\n" + "=" * 70)
        print("🚀 P1风控体系完整分析")
        print("=" * 70)
        
        self.calculate_strategy_capacity()
        self.assess_impact_cost()
        self.analyze_liquidity_risk()
        self.analyze_style_exposure()
        self.analyze_factor_crowding()
        self.generate_risk_report()
        
        print("\n" + "=" * 70)
        print("✅ P1风控分析完成")
        print("=" * 70)
        
        return self.results
    
    def save_report(self, output_dir: str = '/Users/variya/.openclaw/workspace/projects/a-stock-advisor/reports'):
        """保存报告"""
        os.makedirs(output_dir, exist_ok=True)
        
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        
        # JSON报告
        json_path = os.path.join(output_dir, f'p1_risk_control_{timestamp}.json')
        with open(json_path, 'w', encoding='utf-8') as f:
            json.dump(self.results, f, indent=2, ensure_ascii=False, default=str)
        
        # Markdown报告
        md_report = self._generate_markdown_report()
        md_path = os.path.join(output_dir, f'p1_risk_control_{timestamp}.md')
        with open(md_path, 'w', encoding='utf-8') as f:
            f.write(md_report)
        
        print(f"\n✓ 报告已保存:")
        print(f"  JSON: {json_path}")
        print(f"  Markdown: {md_path}")
        
        return json_path, md_path
    
    def apply_all_controls(self, selected_stocks: pd.DataFrame, stock_list: pd.DataFrame, 
                          factor_data: pd.DataFrame) -> Tuple[pd.DataFrame, Dict]:
        """
        应用所有风险控制
        
        Args:
            selected_stocks: 已选股票
            stock_list: 股票列表
            factor_data: 因子数据
            
        Returns:
            (控制后的股票, 控制摘要)
        """
        control_summary = {
            '过滤前': len(selected_stocks),
            '过滤详情': {}
        }
        
        # 合并股票信息
        if len(stock_list) > 0 and '股票代码' in stock_list.columns:
            stock_info = stock_list.set_index('股票代码')
        else:
            stock_info = pd.DataFrame(index=selected_stocks.index)
        
        result = selected_stocks.copy()
        
        # 应用各项过滤
        for filter_name, filter_func in self.filters.items():
            before_count = len(result)
            
            # 应用过滤
            try:
                if len(stock_info) > 0:
                    mask = result.index.map(lambda code: filter_func(stock_info.loc[code]) if code in stock_info.index else True)
                else:
                    mask = pd.Series(True, index=result.index)
                
                result = result[mask]
            except Exception as e:
                print(f"⚠️ 过滤{filter_name}失败: {e}")
            
            after_count = len(result)
            filtered_count = before_count - after_count
            
            control_summary['过滤详情'][filter_name] = filtered_count
        
        control_summary['过滤后'] = len(result)
        
        self.control_summary = control_summary
        
        return result, control_summary
    
    def format_control_summary(self, summary: Dict) -> str:
        """
        格式化控制摘要
        
        Args:
            summary: 控制摘要
            
        Returns:
            格式化的摘要文本
        """
        lines = []
        lines.append("风险控制摘要:")
        lines.append(f"  过滤前: {summary['过滤前']}只")
        
        for filter_name, count in summary['过滤详情'].items():
            if count > 0:
                lines.append(f"  - {filter_name}: 过滤{count}只")
        
        lines.append(f"  过滤后: {summary['过滤后']}只")
        
        return "\n".join(lines)
    
    def _generate_markdown_report(self) -> str:
        """生成Markdown报告"""
        lines = []
        
        lines.append("# P1风控体系分析报告\n")
        lines.append(f"**生成时间:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        lines.append("---\n")
        
        # 综合评估
        if 'risk_report' in self.results:
            rr = self.results['risk_report']
            lines.append("## 🔍 综合风控评估\n")
            lines.append(f"- **风险评分:** {rr['risk_score']}/100\n")
            lines.append(f"- **风险等级:** {rr['overall_risk_level']}\n\n")
        
        # P1-1: 策略容量
        if 'strategy_capacity' in self.results:
            sc = self.results['strategy_capacity']
            lines.append("## 📊 P1-1: 策略容量评估\n")
            lines.append(f"- 推荐容量: ¥{sc['recommended_capacity']:,.0f}\n")
            lines.append(f"- 容量评级: {sc['capacity_grade']}\n\n")
        
        # P1-2: 冲击成本
        if 'impact_cost' in self.results:
            lines.append("## 📊 P1-2: 冲击成本评估\n")
            lines.append("| 交易规模 | 冲击成本率 | 风险等级 |\n")
            lines.append("|---------|-----------|----------|\n")
            for label, data in self.results['impact_cost']['impact_by_amount'].items():
                lines.append(f"| {label} | {data['impact_rate']:.4%} | {data['risk_level']} |\n")
            lines.append("\n")
        
        # P1-3: 流动性风险
        if 'liquidity_risk' in self.results:
            lr = self.results['liquidity_risk']
            lines.append("## 📊 P1-3: 流动性风险分析\n")
            lines.append(f"- 流动性评级: {lr['liquidity_grade']}\n")
            if 'high_risk_count' in lr:
                lines.append(f"- 高风险股票数: {lr['high_risk_count']}\n")
            lines.append("\n")
        
        # P1-4: 风格暴露
        if 'style_exposure' in self.results:
            se = self.results['style_exposure']
            lines.append("## 📊 P1-4: 风格暴露分析\n")
            if 'size_exposure' in se:
                lines.append(f"- 大小盘风格: {se['size_exposure']['size_tilt']}\n")
            if 'value_growth_exposure' in se:
                lines.append(f"- 价值成长风格: {se['value_growth_exposure']['style_tilt']}\n")
            lines.append("\n")
        
        # P1-5: 因子拥挤度
        if 'factor_crowding' in self.results:
            fc = self.results['factor_crowding']
            lines.append("## 📊 P1-5: 因子拥挤度分析\n")
            lines.append(f"- 拥挤度评级: {fc['crowding_grade']}\n")
            if 'hhi' in fc:
                lines.append(f"- HHI指数: {fc['hhi']:.4f}\n")
            lines.append("\n")
        
        # 风险控制摘要
        if self.control_summary:
            lines.append("## 🛡️ 风险控制摘要\n")
            lines.append(self.format_control_summary(self.control_summary))
            lines.append("\n")
        
        lines.append("---\n")
        lines.append("\n## 📋 总结\n\n")
        lines.append("本报告完成了P1风控体系的全面分析,包括策略容量、冲击成本、流动性风险、风格暴露和因子拥挤度五个维度。\n")
        
        return '\n'.join(lines)
 
 
def main():
    """主函数"""
    print("=" * 70)
    print("🚀 P1风控体系分析系统")
    print("=" * 70)
    
    rcs = RiskControlSystem(
        data_path='/Users/variya/.openclaw/workspace/projects/a-stock-advisor/data/mock_data.pkl'
    )
    
    results = rcs.run_full_analysis()
    rcs.save_report()
    
    return results
 
 
if __name__ == '__main__':
    main()