小白也能轻松上手的金融数据神器——Tushare使用指南

前言
对于金融数据分析、量化投资入门或股票策略研究的小伙伴来说,数据是至关重要的“原材料”。然而许多初学者常常苦恼于如何轻松获取到可靠且多维度的市场数据。今天就给大家安利一款超实用的开源金融数据接口库——Tushare。无论你是数据分析小白,还是资深量化玩家,都能从 Tushare 中获益!


一、Tushare是什么?
Tushare 是一个基于 Python 的开源财经数据接口库,为用户提供了丰富的中国金融市场数据,包括但不限于以下内容:

  • 股票数据:沪深A股的日线数据、复权数据、财务数据、行情数据、分红配股数据等。
  • 指数数据:沪深指数、行业指数、概念指数等。
  • 期货数据:国内期货品种的行情数据。
  • 宏观经济数据:GDP、CPI、PMI 等宏观指标。
  • 新闻与公告:财经新闻、上市公司公告数据。

Tushare 的最大优势在于免费数据类型丰富接口调用简洁,并且以 Python 为基础,初学者只需几行代码就能快速开始数据获取与分析。


二、Tushare的核心特点

  1. 数据源丰富
    除了股票基本数据外,Tushare 还提供多种金融与宏观数据,为策略研究提供更多维度的参考。

  2. 更新及时
    Tushare 的数据更新通常相对及时,能够满足日常盘后数据分析需求。

  3. 易用性强
    几行 Python 代码便可轻松获取数据,配合 Pandas、NumPy、Matplotlib 等数据分析工具,实现从数据获取到分析、可视化的一站式流程。

  4. 社区活跃
    Tushare 在国内量化社区中拥有较高的人气和成熟的生态圈,遇到问题很容易在社区找到解决方案。


三、如何快速上手?
1. 环境准备

  • 确保已安装 Python(建议 Python3.X)
  • 安装所需数据分析工具包,如 pandas:
    pip install pandas
    
  • 安装 Tushare:
    pip install tushare
    

2. 注册获取 Token
从 2018 年开始,Tushare 升级为 Tushare Pro 接口,需要注册并获取 Token。

  • 前往 Tushare官网 注册一个账号
  • 登录后在个人中心获取专属的 Token

3. 初始化与测试

import tushare as ts

# 设置你的token
ts.set_token('YOUR_TOKEN_HERE')
pro = ts.pro_api()

# 测试获取上证指数日线数据
df = pro.daily(ts_code='000001.SH', start_date='20220101', end_date='20221231')
print(df.head())

运行上述代码,如果能正常输出数据,即表示你的 Tushare 环境已经搭建完成!


四、常用数据获取示例

  1. 获取股票基本信息
# 获取沪深股票基本信息
stock_basic = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date')
print(stock_basic.head())
  1. 获取日线行情数据
# 获取某只股票的日线行情数据
df = pro.daily(ts_code='600519.SH', start_date='20230101', end_date='20231231')
print(df.tail())
  1. 获取财务指标数据
# 获取上市公司财务指标(如净资产收益率ROE、净利率等)
fin_data = pro.fina_indicator(ts_code='600519.SH')
print(fin_data.head())
  1. 获取宏观数据
# 获取GDP数据(季度)
gdp_data = pro.cn_gdp(yoy='1')
print(gdp_data.head())

通过以上示例,可以看出调用接口非常简洁直观:**pro.接口名(参数...)**的方式几乎就可以满足大部分数据拉取需求。


五、与数据分析工具的无缝衔接
Tushare 返回的数据大多是 Pandas DataFrame 格式的表格数据。我们可以非常方便地与 Pandas、NumPy、Matplotlib、Seaborn 等工具结合,实现从数据预处理、特征提取、模型训练到图表可视化的全流程。

例如,我们可以快速绘制股价数据走势:

import matplotlib.pyplot as plt

df.set_index('trade_date', inplace=True)
df = df.sort_index()
df['close'].plot(figsize=(10, 4), title='贵州茅台股价走势', xlabel='日期', ylabel='价格')
plt.show()

六、总结与展望
Tushare 是国内量化入门与数据分析爱好者必备的工具。对于初学者,它是一个快速获取数据、验证策略的入口;对于进阶用户,它可提供丰富且多层次的数据源,为量化模型的优化提供坚实的数据基础。

在未来,随着国内量化市场的发展与数据需求的不断攀升,Tushare 的数据种类与深度也在持续扩张。无论你是准备写一个小型的量化回测脚本,还是计划构建一个专业的量化研究平台,Tushare 都能够帮你在数据获取层面节省大量时间与精力。

快试试 Tushare 吧

实战

收益

from re import template
import tushare as tu
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.express as px 
import plotly.graph_objects as go
# import plotnine as ggplot2
# import seaborn as sns
import statsmodels.api as sm
from statsmodels.formula.api import ols
from statsmodels.gam.api import GLMGam, BSplines
# from pygam import LinearGAM,s,f
import tushare as ts


ts.set_token('api')
pro=ts.pro_api()

# 策略参数
stock_code = '603138.SH'  # 股票代码
buy_threshold = 1.02   # 买入阈值
sell_threshold = 0.98  # 卖出阈值
window_size = 5       # 均线窗口大小
df=pro.daily(ts_code=stock_code,start_date='2023-01-15')
df.dropna(inplace=True)  # 去除缺失数据
df.sort_values(by='trade_date',inplace=True)
df['ma'] = df['close'].rolling(window=window_size).mean()
# 交易规则
hold_flag = False   # 持仓标志
buy_price = 0      # 买入价格
profit = 0          # 收益
for i in range(window_size, len(df)):
    # 判断买入
    if not hold_flag and df.iloc[i]['close'] > df.iloc[i]['ma'] * buy_threshold:
        hold_flag = True
        buy_price = df.iloc[i]['close']
        print('买入:', df.index[i], buy_price)

    # 判断卖出
    if hold_flag and df.iloc[i]['close'] < df.iloc[i]['ma'] * sell_threshold:
        hold_flag = False
        sell_price = df.iloc[i]['close']
        profit += (sell_price - buy_price) / buy_price
        print('卖出:', df.index[i], sell_price, '收益:', profit)

# 输出总收益率
print('总收益率:', profit)

买入: 455 23.53
卖出: 443 25.45 收益: 0.08159796005099865
买入: 440 26.18
卖出: 438 24.23 收益: 0.007113620860777131
买入: 430 25.02
卖出: 419 22.36 收益: -0.09920132718078963
买入: 414 24.81
卖出: 409 23.7 收益: -0.14394135136458647
买入: 407 26.11
卖出: 403 25.4 收益: -0.17113399786018205
买入: 400 28.11
卖出: 398 25.39 收益: -0.2678967157541699
买入: 387 20.63
卖出: 382 19.88 收益: -0.3042515388273643
买入: 370 19.49
卖出: 363 21.24 收益: -0.21446190311674346
买入: 348 20.94
卖出: 344 20.14 收益: -0.2526662966219966
买入: 329 19.77
卖出: 319 20.33 收益: -0.22434055054207758
买入: 312 21.62
卖出: 309 18.65 收益: -0.3617133535022997
买入: 306 20.16
卖出: 296 19.88 收益: -0.37560224239118867
买入: 283 19.68
卖出: 280 18.98 收益: -0.41117134808224554
买入: 271 16.99
卖出: 253 18.23 收益: -0.338187239783246
买入: 245 18.22
卖出: 235 18.78 收益: -0.30745178423988695
买入: 207 13.9
卖出: 204 12.8 收益: -0.3865884748873689
买入: 196 11.34
卖出: 189 12.47 收益: -0.28694120857343586
买入: 187 13.57
卖出: 183 13.0 收益: -0.3289456300914904
买入: 181 13.7
卖出: 169 14.51 收益: -0.2698215425002495
买入: 154 12.36
卖出: 144 12.87 收益: -0.2285594065779194
买入: 137 12.79
卖出: 132 12.18 收益: -0.27625291713304057
买入: 120 11.05
卖出: 113 11.05 收益: -0.27625291713304057
买入: 99 10.53
卖出: 95 10.0 收益: -0.3265853007987575
买入: 92 10.37
卖出: 82 9.9 收益: -0.371908348050445
买入: 73 9.94
卖出: 58 11.58 收益: -0.20691840841261797
买入: 56 12.21
卖出: 52 11.82 收益: -0.23885944035364995
买入: 51 12.46
卖出: 40 15.04 收益: -0.031796840032622814
买入: 35 15.39
卖出: 25 15.5 收益: -0.024649341657054298
买入: 21 16.05
卖出: 16 16.69 收益: 0.015226047751045427
买入: 11 17.59
卖出: 8 16.15 收益: -0.06663864809886937
买入: 2 17.4
总收益率: -0.06663864809886937

爬取股票

import tushare as ts
import pandas as pd
import os
import time
import glob
def get_stock_data(code, date1,  filename, length=100):
    df = pro.daily(ts_code=code, start_date=date1)
    df1 = pd.DataFrame(df)
    df1 = df1[['trade_date','open', 'high', 'close', 'low', 'vol', 'pct_chg']]
    df1 = df1.sort_values(by='trade_date')
    print('共有%s天数据' % len(df1))
    if (len(df1)>length):
        path = code+ '.xlsx'
        df1.to_excel(os.path.join(filename, path))


# # ------------------------更新股票数据------------------------ #
# # 将股票数据从本地文件的最后日期更新至当日
# # filename:具体到文件名如d:\data\000001.csv
def update_stock_data(filename):
    (filepath, tempfilename) = os.path.split(filename)
    (stock_code, extension) = os.path.splitext(tempfilename)
    f = open(filename, 'r')
    df = pd.read_excel(f)
    print('股票{}文件中的最新日期为:{}'.format(stock_code, df.iloc[-1, 1]))
    data_now = time.strftime('%Y%m%d', time.localtime(time.time()))
    print('更新日期至:%s' % data_now)
    nf = pro.daily(ts_code=stock_code, start_date=str(df.iloc[-1, 1]), end_date=data_now)
    nf = nf.sort_values(by='trade_date')
    nf = nf[['trade_date','open', 'high', 'close', 'low', 'vol', 'pct_chg']]
    nf = nf.iloc[1:]
    print('共有%s天数据' % len(nf))
    nf = pd.DataFrame(nf)
    nf.to_excel(filename, mode='a', header=False)
    f.close()
# # ------------------------获取股票长度----------------------- #
# # 辅助函数
def get_data_len(file_path):
	with open(file_path) as f:
		df = pd.read_excel(f)
		return len(df)
# # --------------------------文件合并------------------------- #
# # 将多个文件合并为一个文件,在文件末尾添加
# # filename是需要合并的文件夹,tfile是存放合并后文件的文件夹
def merge_stock_data(filename, tfile):
	csv_list = glob.glob(filename + '*.xlsx')
	print(u'共发现%s个CSV文件' % len(csv_list))
	f = open(csv_list[0])
	df = pd.read_excel(f)
	for i in range(1, len(csv_list)):
		f1 = open(csv_list[i], 'rb')
		df1 = pd.read_excel(f1)
		df = pd.concat([df, df1])
	df.to_excel(tfile+'train_mix.xlsx', index=None)

for i in range(1,50):
    name='{:0>6d}'.format(i)+'.SZ'
    get_stock_data(name, '20210101', 'stock_files/',200)

共有927天数据
共有927天数据
共有0天数据
共有925天数据
共有766天数据
共有927天数据
共有923天数据。。。。。。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值