Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Access Chinese financial market data (stocks, futures, funds) using the Tushare Pro API.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
scripts/stock_data_demo.py
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3"""4股票数据获取示例脚本5"""67import tushare as ts8import pandas as pd9import os1011# 读取环境变量中的token, 或者读取本地记录的token12token = os.getenv('TUSHARE_TOKEN') or ts.get_token()1314# 初始化pro接口15pro = ts.pro_api(token)161718def get_stock_list():19"""20获取股票列表21"""22try:23data = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date')24print("股票列表获取成功:")25print(data.head())26return data27except Exception as e:28print(f"获取股票列表失败:{e}")29return None303132def get_daily_data(ts_code, start_date, end_date):33"""34获取股票日线数据35"""36try:37data = pro.daily(ts_code=ts_code, start_date=start_date, end_date=end_date)38print(f"{ts_code}日线数据获取成功:")39print(data.head())40return data41except Exception as e:42print(f"获取日线数据失败:{e}")43return None444546def get_financial_data(ts_code, year, quarter):47"""48获取财务指标数据49"""50try:51data = pro.fina_indicator(ts_code=ts_code, year=year, quarter=quarter)52print(f"{ts_code}财务指标数据获取成功:")53print(data.head())54return data55except Exception as e:56print(f"获取财务指标数据失败:{e}")57return None585960def main():61"""62主函数63"""64print("===== tushare 股票数据获取示例 =====")6566# 获取股票列表67stock_list = get_stock_list()6869if stock_list is not None:70# 获取第一只股票的代码71ts_code = stock_list['ts_code'].iloc[0]72print(f"\n使用股票代码:{ts_code}")7374# 获取日线数据(最近30天)75import datetime76end_date = datetime.datetime.now().strftime('%Y%m%d')77start_date = (datetime.datetime.now() - datetime.timedelta(days=30)).strftime('%Y%m%d')78print(f"\n获取日线数据:{start_date} 至 {end_date}")79get_daily_data(ts_code, start_date, end_date)8081# 获取财务数据(最近一年)82current_year = datetime.datetime.now().year83print(f"\n获取财务数据:{current_year-1}年 第4季度")84get_financial_data(ts_code, current_year-1, 4)858687if __name__ == "__main__":88main()89