feat: choose stock count for data update
| | |
| | | """打印信息消息""" |
| | | print(f"{Color.OKCYAN}ℹ {text}{Color.ENDC}") |
| | | |
| | | def run_script(script_name, description="", return_result=False): |
| | | def run_script(script_name, description="", return_result=False, args=None): |
| | | """运行脚本""" |
| | | if description: |
| | | print_info(f"正在执行: {description}") |
| | | script_path = scripts_dir / script_name |
| | | command = [sys.executable, str(script_path)] |
| | | if args: |
| | | command.extend(args) |
| | | |
| | | try: |
| | | result = subprocess.run( |
| | | [sys.executable, str(script_path)], |
| | | command, |
| | | cwd=project_root, |
| | | capture_output=False, |
| | | text=True |
| | |
| | | except Exception as e: |
| | | print_error(f"执行失败: {e}") |
| | | return False |
| | | |
| | | |
| | | def prompt_stock_count_args(): |
| | | """选择数据更新股票数量,并返回传给数据更新脚本的参数。""" |
| | | print(f"\n{Color.BOLD}【股票数量】{Color.ENDC}") |
| | | print("1. 快速更新 500 只股票 ⭐推荐") |
| | | print("2. 全量更新全部A股(较慢)") |
| | | print("3. 自定义数量") |
| | | print("0. 返回") |
| | | |
| | | choice = input("\n请选择股票数量 (0-3): ").strip() |
| | | if choice == '1': |
| | | return ["--n-stocks", "500"], "500只股票" |
| | | if choice == '2': |
| | | return ["--n-stocks", "all"], "全量A股" |
| | | if choice == '3': |
| | | value = input("请输入股票数量: ").strip() |
| | | if not value.isdigit() or int(value) <= 0: |
| | | print_error("股票数量必须是正整数") |
| | | return None, None |
| | | return ["--n-stocks", value], f"{value}只股票" |
| | | if choice == '0': |
| | | return None, None |
| | | |
| | | print_error("无效的选择") |
| | | return None, None |
| | | |
| | | def run_enhanced_factor_system(data_file=None): |
| | | """运行增强因子系统""" |
| | |
| | | run_enhanced_factor_system() |
| | | return result |
| | | elif choice == '3': |
| | | result = run_script('data_update_v2.py', "从AKShare在线获取数据") |
| | | args, stock_count_desc = prompt_stock_count_args() |
| | | if args is None: |
| | | return False |
| | | result = run_script( |
| | | 'data_update_v2.py', |
| | | f"从AKShare在线获取数据({stock_count_desc})", |
| | | args=args, |
| | | ) |
| | | if result: |
| | | print_info("数据更新完成,正在运行增强因子系统...") |
| | | run_enhanced_factor_system() |
| | |
| | | import numpy as np |
| | | import pickle |
| | | import json |
| | | import argparse |
| | | |
| | | os.makedirs('logs', exist_ok=True) |
| | | |
| | |
| | | if stock_list is None or len(stock_list) == 0: |
| | | return None |
| | | |
| | | if n_stocks: |
| | | if n_stocks is not None: |
| | | stock_list = stock_list.head(n_stocks) |
| | | return stock_list |
| | | |
| | |
| | | logger.info("📥 获取A股股票列表...") |
| | | stock_list = fetch_akshare_stock_list(ak) |
| | | |
| | | if n_stocks is not None: |
| | | stock_list = stock_list.head(n_stocks) |
| | | |
| | | consecutive_failures = 0 |
| | |
| | | logger.error("❌ AKShare股票列表无法转换为BaoStock代码") |
| | | return None |
| | | |
| | | if n_stocks is not None: |
| | | stock_list = stock_list.head(n_stocks) |
| | | logger.info(f"✓ 使用AKShare股票列表获取BaoStock历史行情: {len(stock_list)} 只股票") |
| | | else: |
| | |
| | | (stock_list['type'].astype(str) == '1') & |
| | | (stock_list['status'].astype(str) == '1') |
| | | ].copy() |
| | | if n_stocks is not None: |
| | | stock_list = stock_list.head(n_stocks) |
| | | logger.info(f"✓ BaoStock股票池数量: {len(stock_list)}") |
| | | |
| | |
| | | return df |
| | | |
| | | |
| | | def main(): |
| | | def parse_n_stocks(value): |
| | | """解析股票数量参数,all/全部 表示不限制。""" |
| | | if value is None: |
| | | return 500 |
| | | |
| | | normalized = str(value).strip().lower() |
| | | if normalized in ('all', 'full', '全部', '全量'): |
| | | return None |
| | | |
| | | try: |
| | | n_stocks = int(normalized) |
| | | except ValueError as exc: |
| | | raise argparse.ArgumentTypeError("股票数量必须是正整数,或 all") from exc |
| | | |
| | | if n_stocks <= 0: |
| | | raise argparse.ArgumentTypeError("股票数量必须是正整数,或 all") |
| | | return n_stocks |
| | | |
| | | |
| | | def parse_args(argv=None): |
| | | parser = argparse.ArgumentParser(description="更新A股真实行情数据") |
| | | parser.add_argument( |
| | | "--n-stocks", |
| | | default="500", |
| | | type=parse_n_stocks, |
| | | help="更新股票数量,正整数或 all/全部;默认 500", |
| | | ) |
| | | parser.add_argument( |
| | | "--days", |
| | | default=365, |
| | | type=int, |
| | | help="历史数据天数;默认 365", |
| | | ) |
| | | return parser.parse_args(argv) |
| | | |
| | | |
| | | def main(argv=None): |
| | | """主函数""" |
| | | args = parse_args(argv) |
| | | logger.info("="*60) |
| | | logger.info("数据更新任务开始 - 使用真实数据源") |
| | | logger.info("="*60) |
| | |
| | | os.makedirs('logs', exist_ok=True) |
| | | os.makedirs('data', exist_ok=True) |
| | | |
| | | df = fetch_real_stock_data_from_akshare(n_stocks=500, days=365) |
| | | stock_count_desc = "全部A股" if args.n_stocks is None else f"{args.n_stocks}只股票" |
| | | logger.info(f"更新范围: {stock_count_desc}, 历史天数: {args.days}") |
| | | |
| | | df = fetch_real_stock_data_from_akshare(n_stocks=args.n_stocks, days=args.days) |
| | | |
| | | if df is not None and len(df) > 0: |
| | | output_file = 'data/akshare_real_data_fixed.pkl' |
| | |
| | | 'create_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), |
| | | 'source': df.attrs.get('source', 'akshare_real'), |
| | | 'description': '从AKShare/BaoStock获取的真实A股数据', |
| | | 'requested_stock_count': 'all' if args.n_stocks is None else int(args.n_stocks), |
| | | 'requested_days': int(args.days), |
| | | 'stock_count': int(df['stock_code'].nunique()), |
| | | 'total_records': int(len(df)), |
| | | 'date_range': f"{df['date'].min()} to {df['date'].max()}" |
| | |
| | | self.assertNotIn("stdout", kwargs) |
| | | self.assertNotIn("stderr", kwargs) |
| | | |
| | | def test_run_script_passes_extra_args(self): |
| | | completed = subprocess.CompletedProcess( |
| | | args=[sys.executable, "fake.py"], |
| | | returncode=0, |
| | | ) |
| | | |
| | | with patch.object(a_stock_manager.subprocess, "run", return_value=completed) as run: |
| | | result = a_stock_manager.run_script( |
| | | "fake.py", |
| | | "fake task", |
| | | args=["--n-stocks", "all"], |
| | | ) |
| | | |
| | | self.assertTrue(result) |
| | | self.assertEqual( |
| | | run.call_args.args[0], |
| | | [ |
| | | sys.executable, |
| | | str(a_stock_manager.scripts_dir / "fake.py"), |
| | | "--n-stocks", |
| | | "all", |
| | | ], |
| | | ) |
| | | |
| | | def test_prompt_stock_count_args_supports_all(self): |
| | | with patch("builtins.input", return_value="2"): |
| | | args, description = a_stock_manager.prompt_stock_count_args() |
| | | |
| | | self.assertEqual(args, ["--n-stocks", "all"]) |
| | | self.assertIn("全量", description) |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | unittest.main() |
| | |
| | | ], |
| | | ) |
| | | |
| | | def test_parse_n_stocks_supports_all(self): |
| | | self.assertIsNone(data_update_v2.parse_n_stocks("all")) |
| | | self.assertIsNone(data_update_v2.parse_n_stocks("全部")) |
| | | self.assertEqual(data_update_v2.parse_n_stocks("6000"), 6000) |
| | | |
| | | def test_fetch_stock_list_from_akshare_all_keeps_full_list(self): |
| | | stock_list = pd.DataFrame( |
| | | [{"代码": f"{index:06d}", "名称": f"测试{index}"} for index in range(10)] |
| | | ) |
| | | |
| | | with patch.object( |
| | | data_update_v2, |
| | | "fetch_akshare_stock_list", |
| | | return_value=stock_list, |
| | | ): |
| | | with patch.dict(sys.modules, {"akshare": object()}): |
| | | result = data_update_v2.fetch_stock_list_from_akshare(n_stocks=None) |
| | | |
| | | self.assertEqual(len(result), 10) |
| | | |
| | | def test_akshare_history_failures_abort_before_full_stock_pool(self): |
| | | class FakeAkShare: |
| | | def __init__(self): |