114 lines
3.5 KiB
Python
114 lines
3.5 KiB
Python
"""
|
|
测试 Tushare 接口返回数据
|
|
检查各个接口返回的实际字段
|
|
"""
|
|
import sys
|
|
import os
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
# 直接使用 token
|
|
token = '0ed6419a00d8923dc19c0b58fc92d94c9a0696949ab91a13aa58a0cc'
|
|
|
|
def test_tushare_api():
|
|
"""测试 Tushare API 返回的数据"""
|
|
print("=" * 60)
|
|
print("Tushare API 数据测试")
|
|
print("=" * 60)
|
|
print()
|
|
|
|
import tushare as ts
|
|
ts.set_token(token)
|
|
pro = ts.pro_api()
|
|
|
|
from datetime import datetime, timedelta
|
|
yesterday = (datetime.now() - timedelta(days=5)).strftime('%Y%m%d')
|
|
today = datetime.now().strftime('%Y%m%d')
|
|
|
|
# 1. 测试概念板块列表
|
|
print("1. 测试 ths_index (概念板块列表)")
|
|
print("-" * 40)
|
|
sectors_df = pro.ths_index(type='N')
|
|
print(f"返回列: {sectors_df.columns.tolist()}")
|
|
print(f"前3行数据:")
|
|
print(sectors_df.head(3))
|
|
print()
|
|
|
|
# 获取第一个板块的代码
|
|
if not sectors_df.empty:
|
|
first_sector_code = sectors_df.iloc[0]['ts_code']
|
|
first_sector_name = sectors_df.iloc[0]['name']
|
|
print(f"使用第一个板块测试: {first_sector_name} ({first_sector_code})")
|
|
print()
|
|
|
|
# 2. 测试板块日线数据
|
|
print("2. 测试 ths_daily (板块日线数据)")
|
|
print("-" * 40)
|
|
|
|
daily_df = pro.ths_daily(
|
|
ts_code=first_sector_code,
|
|
start_date=yesterday,
|
|
end_date=today
|
|
)
|
|
print(f"返回列: {daily_df.columns.tolist()}")
|
|
print(f"最新一天数据:")
|
|
if not daily_df.empty:
|
|
latest = daily_df.sort_values('trade_date').iloc[-1]
|
|
print(latest)
|
|
print()
|
|
|
|
# 3. 测试成分股数据
|
|
print("3. 测试 ths_member (成分股数据)")
|
|
print("-" * 40)
|
|
members_df = pro.ths_member(ts_code=first_sector_code)
|
|
print(f"返回列: {members_df.columns.tolist()}")
|
|
print(f"前5个成分股:")
|
|
print(members_df.head(5))
|
|
print()
|
|
|
|
# 4. 测试个股日线数据
|
|
if not members_df.empty:
|
|
first_stock_code = members_df.iloc[0]['con_code']
|
|
print(f"使用第一个成分股测试: {first_stock_code}")
|
|
print()
|
|
|
|
print("4. 测试 daily (个股日线数据)")
|
|
print("-" * 40)
|
|
stock_daily_df = pro.daily(
|
|
ts_code=first_stock_code,
|
|
start_date=yesterday,
|
|
end_date=today
|
|
)
|
|
print(f"返回列: {stock_daily_df.columns.tolist()}")
|
|
if not stock_daily_df.empty:
|
|
print(f"最新一天数据:")
|
|
latest_stock = stock_daily_df.sort_values('trade_date').iloc[-1]
|
|
print(latest_stock)
|
|
print()
|
|
|
|
# 5. 测试个股每日指标
|
|
print("5. 测试 daily_basic (个股每日指标)")
|
|
print("-" * 40)
|
|
basic_df = pro.daily_basic(
|
|
ts_code=first_stock_code,
|
|
trade_date=today,
|
|
fields='ts_code,trade_date,turnover_rate,volume_ratio,pe,pb'
|
|
)
|
|
print(f"返回列: {basic_df.columns.tolist()}")
|
|
if not basic_df.empty:
|
|
print(f"数据:")
|
|
print(basic_df)
|
|
print()
|
|
|
|
print("=" * 60)
|
|
print("测试完成")
|
|
print("=" * 60)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
test_tushare_api()
|
|
except Exception as e:
|
|
print(f"\n测试失败: {e}")
|
|
import traceback
|
|
traceback.print_exc()
|