waditu / tushare

TuShare is a utility for crawling historical data of China stocks
BSD 3-Clause "New" or "Revised" License
12.87k stars 4.29k forks source link

复权因子接口和前复权的计算公式? #1555

Closed run27017 closed 3 years ago

run27017 commented 3 years ago

从复权因子接口获取的复权因子,如何计算前复权的数据呢?我使用如下公式计算前复权数据:

当日收盘价 * (当日复权因子 / 最新复权因子)

发现并不能完全匹配 ts.pro_bar 返回的前复权数据。

使用的是如下的测试代码:

import tushare as ts
from config import config

def is_qfq_match(stock_code, start_date, end_date):
    tradings = pro.daily(ts_code='000002.SZ', start_date=start_date, end_date=end_date)
    tradings_qfq = ts.pro_bar(api=pro, ts_code=stock_code, adj='qfq', freq='D', start_date=start_date, end_date=end_date)
    factors = pro.adj_factor(ts_code='000002.SZ', start_date=start_date, end_date=end_date)

    close_qfq_calc = tradings.close * (factors.adj_factor / factors.adj_factor[0])
    diff = (close_qfq_calc - tradings_qfq.close).abs()
    return (diff > 0.1).any()

pro = ts.pro_api(config['DB_ENGINE.DATA_API']['token'])

stock_code = '000002.SZ'
years = reversed(range(2000, 2022))
for year in years:
    print(year, is_qfq_match(stock_code, f'{year}0101', f'{year}1231'))

输出效果:

2021 False
2020 False
2019 False
2018 False
2017 False
2016 False
2015 True
2014 False
2013 False
2012 True
2011 False
2010 False
2009 False
2008 False
2007 True
2006 True
2005 True
2004 False
2003 True
2002 False
2001 True
2000 True

误差设为一角钱(相对来说算是比较大的了),发现有若干年份不是完全匹配。

run27017 commented 3 years ago

我错了,有个重大的发现,行情数据和复权因子的日期不完全匹配,复权因子的日期会多一些。所以以下的数据调整必要:

tradings = pd.merge(tradings, factors, on=['trade_date'], how='left')

经此修改后,一切正常:

2021 False
2020 False
2019 False
2018 False
2017 False
2016 False
2015 False
2014 False
2013 False
2012 False
2011 False
2010 False
2009 False
2008 False
2007 False
2006 False
2005 False
2004 False
2003 False
2002 False
2001 False
2000 False

以上是误差超过1角钱的情况,经测试即使时2分钱,也在精度范围以内的。可接受。