""" 更新股票缓存数据(从上年1月1日起) """ import os import json import glob from datetime import datetime, timedelta from services.stock_service import get_stock_fund_flow, save_cached_data def update_all_caches(): cache_dir = 'stock_data_cache' if not os.path.exists(cache_dir): print("缓存目录不存在") return cache_files = glob.glob(f'{cache_dir}/*.json') print(f"找到 {len(cache_files)} 个缓存文件") # 日期范围:从上年1月1日到今天 end_date = datetime.now().strftime('%Y-%m-%d') start_date = f'{datetime.now().year - 1}-01-01' print(f"更新日期范围: {start_date} ~ {end_date}") updated = 0 failed = 0 for i, cache_file in enumerate(cache_files): stock_code = os.path.basename(cache_file).replace('.json', '') print(f"[{i+1}/{len(cache_files)}] 更新 {stock_code}...", end=" ", flush=True) try: # 检查现有缓存数据范围 with open(cache_file, 'r', encoding='utf-8') as f: data = json.load(f) records = data.get('records', []) if records: first_date = records[0].get('日期', '') # 如果已经有上年1月的数据,跳过 if first_date and first_date <= start_date: print(f"已有上年数据({first_date}),跳过") continue # 需要更新 df, name, error = get_stock_fund_flow(stock_code, start_date, end_date) if error: print(f"错误: {error}") failed += 1 elif df is not None and len(df) > 0: save_cached_data(stock_code, df, name) print(f"成功 ({len(df)}条)") updated += 1 else: print("无数据") failed += 1 except Exception as e: print(f"异常: {e}") failed += 1 print(f"\n完成! 更新: {updated}, 失败: {failed}") if __name__ == '__main__': update_all_caches()