刺猬教你量化投资

刺猬教你量化投资(十五):自行计算复权价

2018-09-26  本文已影响20人  刺猬偷腥
以天齐锂业为例子

下面我们尝试运用此前介绍的各个知识点,尝试自行计算天齐锂业的后复权及前复权价格。

编写代码

import pandas as pd
# pd.set_option('expand_frame_repr', False)

#导入行情数据
df = DataAPI.MktEqudGet(secID=u"",ticker=u"002466",tradeDate=u"",beginDate=u"",endDate=u"",isOpen="",field=u"tradeDate,ticker,secShortName,openPrice,highestPrice,lowestPrice,closePrice,chgPct",pandas="1")
df.sort_values(by='tradeDate',inplace=True)

#检验数据库数据是否正常
df['checkchgPct'] = df.closePrice.pct_change()
df[abs(df.checkchgPct-df.chgPct)>0.0001]
del df['checkchgPct']

# 计算后复权值
df['hfqyinzi']=(df['chgPct']+1).cumprod()
initial_price = df.iloc[0]['closePrice']/(1+df.iloc[0]['chgPct'])
df['closePrice_hfq']=initial_price*df.hfqyinzi
df['openPrice_hfq']=df.openPrice/df.closePrice*df.closePrice_hfq
df['highestPrice_hfq']=df.highestPrice/df.closePrice*df.closePrice_hfq
df['lowestPrice_hfq']=df.lowestPrice/df.closePrice*df.closePrice_hfq

# 计算前复权
df1 = df[['tradeDate','ticker','secShortName','openPrice','highestPrice','lowestPrice','closePrice','chgPct']]
df1.sort_values(by='tradeDate',ascending=False,inplace=True)
df1['qfqyinzi']=(1/(df['chgPct']+1))
df1['qfqyinzi']=df1['qfqyinzi'].cumprod().shift(1)
df1['qfqyinzi'].iloc[0]=1.
df1['qfqyinzi']= df1['qfqyinzi'].round(4)  
last_closePrice = df1['closePrice'].iloc[0]
df1['closePrice_qfq']=last_closePrice*df1.qfqyinzi
df1

# 检验是否与数据库数据一致
df2 = DataAPI.MktEqudAdjGet(secID=u"",ticker=u"002466",tradeDate=u"",beginDate=u"",endDate=u"",isOpen="",field=u"tradeDate,ticker,secShortName,openPrice,highestPrice,lowestPrice,closePrice",pandas="1")
df3=pd.DataFrame
df3=pd.merge(df1,df2,how='inner',on='tradeDate')
df3['check_qfq']=df3.closePrice_y-df3.closePrice_qfq
df3['check_qfq']

#输出结果
df4 = df3[['tradeDate','ticker_x','secShortName_x','closePrice_x','closePrice_qfq']]
df123=pd.merge(df3,df,how='inner',on='tradeDate')
df4['closePrice_hfq'] = df123.closePrice_hfq
df4.columns = ['交易日期','证券代码','股票名称','收盘价','前复权价格','后复权价格']
df4.head(10)

运算结果

总结

人生苦短,我用Python。

刺猬偷腥
2018年9月26日

上一篇下一篇

猜你喜欢

热点阅读