Python reproduces the GEM index market

Goal: Draw the ChiNext Index

Recently, there is a strange phenomenon: the fund does not rise when the market rises, and the fund changes when the market falls. Some colleagues suspect that there is a problem with the index, so we drew an index ourselves.
This time I chose the GEM to draw, because the number of stocks is small, so it is more suitable for learning.
But later it was discovered that there was a hole in this index. After wasting a day of self-exploration, it was only with the help of the goddess that the whole story was completely figured out.


Learning Content:

The index has a set of standard calculation formulas. The index calculation formula of the Shenzhen Growth Enterprise Market is published on the official website of the Shenzhen Stock Exchange. You can also download PDF and excel to tell you the constituent stocks and weights. Moreover, the fittest will be adjusted once every six months. It may not be the case for index funds. Adjust it quickly, so the index tracking should have a deviation.
The website address is as follows:
download the
formula
for calculating the component stock excel index. There is a question that cannot be solved before: the price can be converted according to the formula to match the official website data, but the transaction volume and the official website data cannot be combined, whether it is direct accumulation or weight accumulation. After I asked SJS, I learned that the trading volume here is the trading volume of the entire ChiNext, that is: when calculating the price, select the best 100 constituent stocks, and when calculating the trading volume, use the entire ChiNext stock. Volume, this is obviously not logical.
However, this is how many indexes of the GEM are currently calculated. Everything is not for... . .


effect:

The effect of painting by yourself is as follows:
Insert picture description here

The data published on the official website of the Shenzhen Stock Exchange is as follows: The
Insert picture description here
price can be consistent with the market situation of the Shenzhen Stock Exchange.
Flush quotation website announced the trading volume: As
Insert picture description here
you can see, the trading volume has finally matched the number. The printed data can also be matched with the minute volume published by the Shenzhen Stock Exchange.

The volume puzzle is finally solved. It really is KD.


Code part:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from jqdatasdk import *

auth('*','*')    #这里用户名密码需要前往聚宽官网自行申请
is_auth = is_auth()
if is_auth == True:
    print("登录成功")
else:
    print("连接失败")
#print(__version__)

cyb_Cons = pd.read_excel('399006_cons.xlsx')    #获取创业板的成分股
cyb_ConsNow = cyb_Cons[cyb_Cons['日期']=='2020-12-31']    #获取最新的一期成分股
#print(len(cyb_ConsNow))
#print(cyb_ConsNow.head)
zqdmList = np.array(cyb_ConsNow['样本代码'].values)     #成分股代码
#print(zqdmList)
quanzhong = np.array(cyb_ConsNow['权重(%)'].values)   #权重
quanzhong=quanzhong.copy()/100
#print(quanzhong)

#昨天的收盘价,是今天指数的基准
yestedayCYB = get_price(security='399006.XSHE', start_date='2021-01-15 14:58:00', end_date='2021-01-15 14:58:00', frequency='minute',fq='pre', fields=['close','volume','money'])
print(yestedayCYB)

#基数--昨天的收盘价,是今天指数的基准
jishu = float(yestedayCYB['close'].values)
#voljisu =  int(yestedayCYB['volume'].values)
print('基数值为:' + str(jishu))

temp = pd.DataFrame()     #用来缓存计算变量
tempyes = pd.DataFrame()    #用来缓存昨天的计算变量
volumetemp = pd.DataFrame()     #用来缓存计算变量
volumeYesTemp = pd.DataFrame()     #用来缓存计算变量
moneyTemp = pd.DataFrame()     #用来缓存计算金额
#获取股票每分钟信息
for zqdm in zqdmList:
    #print(type(zqdm))
    df = get_price(security=str(zqdm)+'.XSHE', start_date='2021-01-18 09:30:00', end_date='2021-01-18 15:00:00', frequency='minute', fields=['open', 'close','money','volume'])
    dfyes = get_price(security=str(zqdm) + '.XSHE', start_date='2021-01-15 14:58:00', end_date='2021-01-15 14:58:00', frequency='minute', fields=['close','money','volume'])
    qz = cyb_ConsNow[cyb_ConsNow['样本代码']==zqdm]['权重(%)'].values   #权重
    #print(qz)
    #print(df['close']*qz)
    temp[zqdm] = df['close'] * qz / 100
    tempyes[zqdm]=dfyes['close']*qz/100
    volumetemp[zqdm] = df['volume']/100/10000   #万手
    moneyTemp[zqdm] = df['money']/ 100000000   #亿元

print(temp.head(2))
print(tempyes.head(1))
print(temp.sum(axis=1))
print(tempyes.sum(axis=1))
jintian = pd.DataFrame()
zuotian = pd.DataFrame()
jintian['jq'] = temp.sum(axis=1)
zuotian['jq'] = tempyes.sum(axis=1)
zs = jishu*jintian['jq']/zuotian['jq'].values
print(zs)

x=np.array(df.index)    #时间序列
xx=np.arange(0,len(x),1)  # X轴长度
#画图参数
fig = plt.figure()
ax1 = fig.add_subplot(211)
plt.rcParams['font.sans-serif']=['SimHei']  #解决中文乱码
plt.rcParams['axes.unicode_minus'] = False

ax1.set_title('行情')
ax1.plot(xx,zs,c='blue')
plt.xlabel('交易时间(分钟)')
plt.ylabel('成交价格(元)')
ax1.legend('成交价格')
plt.grid()

#plt.show()

#画成交量
dfall=get_all_securities(types='stock', date='2021-01-18')
print(dfall['display_name'].index)
dfcyb= dfall[dfall['display_name'].index>='300000.XSHG']     #只要创业板股票
dfcyb2 = dfcyb[dfcyb['display_name'].index<='309999.XSHG']   #只要创业板股票
#print(dfcyb2.index)
cyblist = np.array(dfcyb2.index)
#print(cyblist)
vol = pd.DataFrame()     #用来缓存计算金额
for cybzqdm in cyblist:

    dfcyb = get_price(security=cybzqdm, start_date='2021-01-18 09:30:00', end_date='2021-01-18 15:00:00',
                   frequency='minute', fields=['volume'])
    vol[cybzqdm[0:6]]=dfcyb['volume']


#print(vol.head())
volsum = pd.DataFrame()     #用来缓存计算金额
volsum['volume'] = vol.sum(axis=1)
print(volsum.head())
print(np.round(volsum['volume'].values/1000000,2))   #单位换算成万手,保留两位小数

ax2 = fig.add_subplot(212)
ax2.bar(xx,np.round(volsum['volume'].values/1000000,2),color='red',label='left')
ax2.set_ylabel('成交量(万手)')
plt.xlabel('交易时间(分钟)')
plt.grid()
ax2.legend('成交量')
#plt.subplots_adjust(left=0.01)
plt.show()

Key points: data acquisition and screening
1. Inter-conversion between DataFrame and array.
2. Drawing tools
3. Get stock quotes
4. Convert stock trading volume

Guess you like

Origin blog.csdn.net/weixin_43290383/article/details/112727428