新增功能: - 5个专业数据抓取器(公司信息、板块、财务、资金流、龙虎榜) - 一键执行脚本 run_all_fetchers.sh(完整/测试/自定义三种模式) - 扩展数据库Schema(11张新表) - 数据源迁移至免费API(东方财富、新浪、腾讯) 数据能力: - 公司基础信息:5,295只A股 - 板块数据:~400个板块 + 20万成分股关系 - 财务报表:利润表+资产负债表(最近4季) - 资金流:主力资金、大单、中单、小单(700天) - 龙虎榜:上榜记录+营业部明细(2年) - 总数据量:~395万条记录,3-5GB存储 技术亮点: - 断点续传支持 - UPSERT策略避免重复 - API限流控制 - 实时进度显示 - 错误容错机制 - 完整日志记录 文档更新: - README添加"全量数据抓取"章节 - 60+页技术方案文档 - 完整的使用指南和维护文档 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
12 KiB
12 KiB
全量数据抓取快速启动指南
🎯 当前状态
✅ 日线数据抓取: 进行中(154/5,498 已完成,预计今晚22:00完成) ⏳ 待实施: 公司信息、板块、财报、资金流、龙虎榜
📋 实施步骤
Step 1: 安装扩展数据库Schema(5分钟)
等待日线抓取完成后,执行:
cd /Users/brunogao/work/codes/shenye/examples/claude-stock/backend
# 1. 备份当前数据库(可选但推荐)
pg_dump -U stock_user -d stock_db > backup_$(date +%Y%m%d).sql
# 2. 安装扩展Schema
psql -U stock_user -d stock_db -f database/schema_extended.sql
# 3. 验证表创建
psql -U stock_user -d stock_db -c "\dt t_*"
预期输出:
✅ Extended database schema created successfully!
📊 New Tables: 11
- 板块相关: 3 tables
- 资金流: 2 tables
- 龙虎榜: 2 tables
- 财报: 3 tables
- 公司信息: 1 table
Step 2: 实施优先级计划
Phase 1: 基础信息(本周完成)
优先级: ⭐⭐⭐⭐⭐
目标:
- 公司基础信息(5,498条)
- 板块分类(~300个板块)
- 最近4季财报(~22,000条)
预计耗时: 2-4小时
Phase 2: 资金流数据(下周完成)
优先级: ⭐⭐⭐⭐
目标:
- 主力资金流(历史2年,~385万条)
- 龙虎榜数据(~5万条)
预计耗时: 4-6小时
Phase 3: 高级数据(可选)
优先级: ⭐⭐⭐
目标:
- 北向资金
- 股东信息
- 高管信息
预计耗时: 2-4小时
🚀 立即开始
选项A: 自动化脚本(推荐)
等我为您创建完整的自动化抓取脚本,执行:
# 安装扩展Schema
psql -U stock_user -d stock_db -f database/schema_extended.sql
# 运行全量抓取(分阶段执行)
./run_comprehensive_fetch.sh --phase 1 # 基础信息
./run_comprehensive_fetch.sh --phase 2 # 资金流
./run_comprehensive_fetch.sh --phase 3 # 高级数据
选项B: 手动分步执行
1. 公司基础信息
source .venv/bin/activate
python fetch_company_info.py
2. 板块数据
python fetch_sector_data.py
3. 财务数据
python fetch_financial_data.py --quarters 4
4. 资金流数据
python fetch_money_flow.py --start-date 2023-01-01
5. 龙虎榜数据
python fetch_top_list.py --start-date 2023-01-01
📊 数据抓取架构
┌─────────────────────────────────────────────────────────┐
│ 数据抓取总控制器 │
│ (ComprehensiveDataFetcher) │
├─────────────────────────────────────────────────────────┤
│ Phase 1 │ Phase 2 │ Phase 3 │
│ 基础信息 │ 资金流 │ 高级数据 │
├───────────────┼───────────────┼────────────────────────┤
│ ✓ 公司信息 │ ○ 主力资金流 │ ○ 北向资金 │
│ ✓ 板块分类 │ ○ 龙虎榜 │ ○ 股东信息 │
│ ✓ 财务报表 │ │ ○ 高管信息 │
└─────────────────────────────────────────────────────────┘
▼ ▼ ▼
┌─────────────────────────────────────────────────────────┐
│ 数据适配层 (Multi-Source) │
├─────────────────────────────────────────────────────────┤
│ EastMoney │ Sina │ Tencent │
│ (主力) │ (辅助) │ (备用) │
└─────────────────────────────────────────────────────────┘
▼ ▼ ▼
┌─────────────────────────────────────────────────────────┐
│ PostgreSQL + Redis (数据存储) │
└─────────────────────────────────────────────────────────┘
📈 预期结果
完成Phase 1后
数据表状态:
-- 检查数据量
SELECT 't_company_info' as table, COUNT(*) FROM t_company_info
UNION ALL
SELECT 't_sector_info', COUNT(*) FROM t_sector_info
UNION ALL
SELECT 't_income_statement', COUNT(*) FROM t_income_statement;
预期输出:
table | count
----------------------+-------
t_company_info | 5,498
t_sector_info | ~300
t_income_statement | ~22,000
完成Phase 2后
table | count
----------------------+-------
t_money_flow | ~385万
t_top_list | ~5万
完整数据量统计
-- 完整统计查询
SELECT
'daily_quotes' as data_type,
COUNT(*) as records,
MIN(trade_date) as earliest,
MAX(trade_date) as latest
FROM daily_quotes
UNION ALL
SELECT
'company_info',
COUNT(*),
NULL,
NULL
FROM t_company_info
UNION ALL
SELECT
'money_flow',
COUNT(*),
MIN(trade_date),
MAX(trade_date)
FROM t_money_flow
UNION ALL
SELECT
'financial_reports',
COUNT(*),
MIN(report_date),
MAX(report_date)
FROM t_income_statement;
🛠️ 技术实现要点
1. 东方财富API端点
# 已验证的API端点
EASTMONEY_APIS = {
# 基础数据
'stock_list': 'http://80.push2.eastmoney.com/api/qt/clist/get',
'company_info': 'http://emweb.securities.eastmoney.com/PC_HSF10/CompanySurvey/PageAjax',
# 板块数据
'sector_list': 'http://80.push2.eastmoney.com/api/qt/clist/get?fs=m:90+t:2',
'sector_constituents': 'http://push2.eastmoney.com/api/qt/slist/get',
# 财务数据
'financial': 'http://emweb.securities.eastmoney.com/PC_HSF10/NewFinanceAnalysis/ZBPageAjax',
# 资金流
'money_flow': 'http://push2.eastmoney.com/api/qt/stock/fflow/kline/get',
# 龙虎榜
'top_list': 'http://datacenter-web.eastmoney.com/api/data/v1/get',
}
2. 数据验证规则
VALIDATION_RULES = {
'company_info': {
'required': ['symbol', 'full_name', 'industry_sw_l1'],
'optional': ['main_business', 'list_date']
},
'money_flow': {
'required': ['symbol', 'trade_date', 'main_net_inflow'],
'checks': {
# 资金流入流出应该平衡
'balance': 'xlarge + large + medium + small = 0'
}
},
'financial': {
'required': ['symbol', 'report_date', 'net_profit_parent'],
'checks': {
# 资产=负债+权益
'balance_sheet': 'total_assets = total_liabilities + total_equity'
}
}
}
3. 容错与重试
class RobustFetcher:
"""健壮的数据抓取器"""
def fetch_with_retry(self, fetch_func, max_retries=3):
"""
带重试的抓取
"""
for attempt in range(max_retries):
try:
return fetch_func()
except Exception as e:
if attempt == max_retries - 1:
logger.error(f"Failed after {max_retries} retries: {e}")
raise
wait_time = 2 ** attempt
time.sleep(wait_time)
def fetch_with_fallback(self, sources, symbol):
"""
多数据源降级
"""
for source in sources:
try:
return self.adapters[source].fetch(symbol)
except Exception as e:
logger.warning(f"{source} failed: {e}")
raise DataFetchError("All sources failed")
📝 监控与维护
每日任务
# 1. 增量更新日线数据
python fetch_full_historical_data.py --mode incremental
# 2. 更新资金流数据(最新一天)
python fetch_money_flow.py --mode incremental
# 3. 检查龙虎榜
python fetch_top_list.py --mode incremental
每季度任务
# 1. 更新财报数据(每季度报告期后)
python fetch_financial_data.py --quarters 1
# 2. 更新公司信息
python fetch_company_info.py --update
数据质量检查
# 运行数据质量检查
python check_data_quality.py
输出示例:
✅ Data Quality Report
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 daily_quotes
Records: 3,848,600
Date Range: 2023-01-01 ~ 2025-12-19
Completeness: 99.2%
Missing Dates: 12 days
📊 t_money_flow
Records: 3,848,600
Completeness: 98.5%
Outliers: 142 records (0.004%)
📊 t_income_statement
Records: 22,000
Latest Quarter: 2024-09-30
Coverage: 5,498/5,498 stocks (100%)
⚠️ Warnings:
- 12 trading days missing in daily_quotes
- 142 outlier records in money_flow
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎓 最佳实践
1. 分批抓取
# 不要一次性抓取所有股票
# 分批进行,每批100只
BATCH_SIZE = 100
for i in range(0, len(all_stocks), BATCH_SIZE):
batch = all_stocks[i:i+BATCH_SIZE]
fetch_batch(batch)
time.sleep(1) # 避免限流
2. 进度追踪
# 记录进度到数据库
progress_tracker.update(
task='fetch_company_info',
total=5498,
completed=1000,
failed=2
)
3. 缓存策略
# 公司信息变化不频繁,可以缓存30天
@cache(ttl=30*24*3600)
def get_company_info(symbol):
return eastmoney.fetch_company_info(symbol)
# 资金流每日变化,缓存1小时
@cache(ttl=3600)
def get_money_flow(symbol, date):
return eastmoney.fetch_money_flow(symbol, date)
4. 错误处理
# 记录失败的任务,稍后重试
failed_tasks = []
for symbol in symbols:
try:
fetch_data(symbol)
except Exception as e:
failed_tasks.append({
'symbol': symbol,
'error': str(e),
'timestamp': datetime.now()
})
# 保存失败任务用于后续重试
save_failed_tasks(failed_tasks)
📞 下一步行动
立即执行(今晚日线抓取完成后)
-
安装扩展Schema
psql -U stock_user -d stock_db -f database/schema_extended.sql -
准备实施环境
# 确认数据库连接 python -c "import psycopg2; print('DB OK')" # 确认API访问 curl "http://80.push2.eastmoney.com/api/qt/clist/get?pn=1&pz=10"
本周目标
- ✅ 完成日线数据(5,498 × 2年)
- 🎯 实施Phase 1: 公司信息 + 板块 + 财报
- 🎯 数据验证和质量检查
需要我协助的事项
请告诉我您希望:
- 自动化脚本: 我可以创建完整的自动化抓取脚本
- 分步实施: 我可以逐个创建各数据类型的抓取器
- 定制需求: 如果有特定的数据需求或优先级调整
文档版本: v1.0 创建时间: 2025-12-21 状态: 等待日线抓取完成