55 lines
1.7 KiB
Python
55 lines
1.7 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
获取最新沪深300成分股列表
|
|
准备为关羽云长准备回测数据
|
|
"""
|
|
import akshare as ak
|
|
import pandas as pd
|
|
import json
|
|
from datetime import datetime
|
|
|
|
print("🚀 获取最新沪深300成分股列表")
|
|
print(f"时间: {datetime.now()}")
|
|
|
|
try:
|
|
# 获取沪深300成分股和权重
|
|
hs300 = ak.index_stock_cons_weight_csindex(symbol="000300")
|
|
|
|
print(f"\n📊 获取成功,共 {len(hs300)} 只成分股")
|
|
print("\n前10只:")
|
|
print(hs300.head(10))
|
|
|
|
# 保存成分股列表
|
|
output_file = "/Volumes/stock/A股数据/stock_info/hs300_constituents_latest.csv"
|
|
hs300.to_csv(output_file, index=False, encoding='utf-8')
|
|
|
|
# 保存JSON格式
|
|
json_file = "/Volumes/stock/A股数据/stock_info/hs300_constituents_latest.json"
|
|
constituents = []
|
|
for _, row in hs300.iterrows():
|
|
code = str(row.get('code', '')).zfill(6)
|
|
name = row.get('name', '')
|
|
weight = row.get('weight', 0)
|
|
constituents.append({
|
|
"code": code,
|
|
"symbol": f"sh{code}" if code.startswith('6') else f"sz{code}",
|
|
"name": name,
|
|
"weight": weight,
|
|
"market": "sh" if code.startswith('6') else "sz"
|
|
})
|
|
|
|
with open(json_file, 'w', encoding='utf-8') as f:
|
|
json.dump(constituents, f, ensure_ascii=False, indent=2)
|
|
|
|
print(f"\n💾 已保存:")
|
|
print(f" CSV: {output_file}")
|
|
print(f" JSON: {json_file}")
|
|
print(f" 总计: {len(constituents)} 只股票")
|
|
|
|
print("\n✅ 沪深300成分股列表获取完成")
|
|
|
|
except Exception as e:
|
|
print(f"\n❌ 获取失败: {e}")
|
|
import traceback
|
|
traceback.print_exc()
|