金之塔用 Python 获取日内分时均价,每分钟日成交量和每时刻结算价,及交叉作用曲线延伸

import numpy as np
import pandas as pd
import datetime
首先补全数据,数据获取不全会有麻烦,得出不是正确的价格

获取当日时间:
dt=history_bars(symbolcode,2,‘1d’,‘datetime’,True,frequency==‘1d’)[-1]
day_time=datetime.datetime.strptime(str(int(dt)), “%Y%m%d%H%M%S”)
获取当前时间:
if context.run_info.run_type==“paper_trading”:
currect_time=datetime.datetime.strptime(str(int(dt+get_dynainf (symbolcode,207))), “%Y%m%d%H%M%S”)
else:
currect_time=context.now#history_bars(symbolcode,2, ‘self’, ‘datetime’)[-1]//‘tick’

获取价格及成交量:
#tcv=history_bars_date(symbolcode,begincount,finishtime,frequency,[‘datetime’,‘close’,‘volume’])
tcv=history_bars_date(symbolcode,day_time,currect_time,‘1m’,[‘datetime’,‘close’,‘volume’])

#-----------------------------------
1.获取当前即时日成交量与日内均价:
v_sum=np.array(tcv[:,2]).sum()
if v_sum>0:
v_price=np.dot(tcv[:,1],tcv[:,2])/v_sum

这个方法也可用来快速获取前一日结算价,只要时间改一下就行

if context.run_info.run_type==“paper_trading”:
day_volume=history_bars(symbolcode,1,‘1d’,‘volume’,True,True)[-1]
print(“day volume:%d”%day_volume+“dy volume:%d”%get_dynainf (symbolcode,8)+“v sum:%d”%v_sum)#三个成交量验证一下
print(len(tcv)) #大概算一下当日行情多少分钟

2.用numpy方法获取当日成交量与结算均价的数组:
v_s=np.cumsum(tcv[:,2])#np.sum()
p_s=np.cumsum(tcv[:,1]*tcv[:,2])/v_s
时间格式可以用DatetimeIndex转换:
t_s=pd.to_datetime([str(int(t)) for t in (tcv[:,0])])#.tolist()

print(pd.DataFrame(data=np.stack([v_s,p_s], axis=1),index=t_s,columns=[‘v_s’,‘p_s’]))

3.用循环方法获取当日成交量与结算均价的数组:
temp=0
time_list=[]
volume_sum=[]
volume_price=[]

for tcv_i in tcv:
time_list.append(datetime.datetime.strptime(str(int(tcv_i[0])), “%Y%m%d%H%M%S”))
temp+=tcv_i[2]*tcv_i[1]
if len(volume_sum):
volume_sum.append(tcv_i[2]+volume_sum[-1])
volume_price.append(temp/volume_sum[-1])
else:
volume_sum.append(tcv_i[2])
volume_price.append(tcv_i[1])

print(pd.DataFrame(data=np.stack([volume_sum,volume_price], axis=1),index=pd.to_datetime(time_list),columns=[‘volume_sum’,‘settle_price’]) )

2,3效率比较的话总体感觉3要快2倍以上

最后:假设两个连续的时间序列相交后每个时刻作用都为weight=1,用上面类似的方法:
价格与日内均价每次交叉后,突破后的作用曲线

arr=tcv[:,1]
compare = volume_price#np.zeros(arr.shape)
weight = np.ones(arr.shape)
或者也可以把arr=close-price,compare=np.zeros(arr.shape),类似零轴摆动

keep_count = np.zeros(arr.shape)
per_cv = np.zeros(arr.shape)
temp=0
per_cv[0]= arr[0]*weight[0]

for i in range(1, len(arr)):
if arr[i]==compare[i]:
keep_count[i]=0
elif arr[i]>compare[i]:
keep_count[i]=keep_count[i-1]+1 if keep_count[i-1]>=0 else 0
else:
keep_count[i]=keep_count[i-1]-1 if keep_count[i-1]<=0 else 0
if keep_count[i]==0:
temp=0
per_cv[i]= arr[i]*weight[i]
else:
temp+=arr[i]*weight[i]
per_cv[i]=temp/keep_count[i]

print(keep_count)
print(per_cv)
plot一下

也可以求出价格与ma cross后的的作用曲线,只要compare=ma就行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值