所有函数¶
import pandas as pd
from jqdata import *
import warnings
warnings.filterwarnings("ignore")
def get_future_tick_stat(ticker,date):
"""
ticker = "RB1905.XSGE"
date = "2019-02-15"
获得tick数据的标记
"""
#获得前一个交易日
pre_day = str(get_trade_days(start_date=None, end_date=date, count=2)[0])
start_time = pre_day+' 20:00:00'
end_time = date + ' 15:30:00'
#获得tick数据
field = ['time','current','volume','money','position','a1_p','a1_v','b1_p','b1_v']
data = get_ticks(ticker,start_dt=start_time,end_dt=end_time,count=None,fields=field)
data = pd.DataFrame(data)
data.columns = ['time','lastPrice','volume','value','openInterest','askPrice1','askVolume1','bidPrice1','bidVolume1']
#对成交量按升序排列,因为郑州交易所的数据可能有错,同一秒的两个数据有颠倒情况(如FG905,20190121等等)导致再手为负
data = data.sort_values(by='volume')
#现手、增仓计算
data['现手']=data['volume']-data['volume'].shift(1)
data['增仓']=data['openInterest']-data['openInterest'].shift(1)
#------集合竞价的现手与增仓
data.loc[0,'现手']=data.loc[0,'volume']
#前一天的持仓量
temp = get_extras('futures_positions', ticker, start_date=pre_day, end_date=date, df=True).iloc[0,0]
#集合竞价增仓
data.loc[0,'增仓']=data.loc[0,'openInterest']-temp
#筛选非0tick
data_need=data[(data['volume']>0)&(data['现手']!=0)]
data_need = data_need.reset_index(drop=True)
#----------主买、主卖的判断
#昨天收盘价
price = get_price(ticker, start_date=None, end_date=date, frequency='daily', fields=['open','close'], skip_paused=False, fq=None, count=2)
preClosePrice = price.iloc[0,1]
openPrice = price.iloc[1,0]
#集合竞价成交主买主卖的判断
flag=[]
if openPrice>preClosePrice:
flag.append(1)
else:
flag.append(-1)
#所有tick主买主卖
data_need['主动买/卖'] = flag+[1 if data_need['lastPrice'][i]>=data_need['askPrice1'][i-1] else -1 for i in range(1,len(data_need))]
#----------买卖性质
temp=[]
for i in range(len(data_need)):
if data_need['现手'][i]==abs(data_need['增仓'][i]):
if data_need['增仓'][i]>0:
temp.append('双开')
else:
temp.append('双平')
else:
if data_need['主动买/卖'][i]==1:
if data_need['增仓'][i]>0:
temp.append('多开')
elif data_need['增仓'][i]<0:
temp.append('空平')
else:
temp.append('多换')
else:
if data_need['增仓'][i]>0:
temp.append('空开')
elif data_need['增仓'][i]<0:
temp.append('多平')
else:
temp.append('空换')
data_need['性质']=temp
#当笔tick的成交金额
temp2 = data_need['value']-data_need['value'].shift(1)
temp2 = temp2.tolist()[1:]
data_need['现值'] = [data_need.loc[0,'value']] + temp2
result = data_need[['time','lastPrice','volume','value','现手','现值','增仓','主动买/卖','性质']]
return result
def get_8stat(result,big_order=0):
"""
根据tick数据,计算八项统计,默认统计全部
"""
total_volume = sum(result['现手'])
duo_kai = sum(result[(result['性质']=='多开')&(result['现手']>=big_order)]['现手'])/total_volume
kon_pin = sum(result[(result['性质']=='空平')&(result['现手']>=big_order)]['现手'])/total_volume
kon_kai = sum(result[(result['性质']=='空开')&(result['现手']>=big_order)]['现手'])/total_volume
duo_pin = sum(result[(result['性质']=='多平')&(result['现手']>=big_order)]['现手'])/total_volume
duo_huan = sum(result[(result['性质']=='多换')&(result['现手']>=big_order)]['现手'])/total_volume
kon_huan = sum(result[(result['性质']=='空换')&(result['现手']>=big_order)]['现手'])/total_volume
shuang_kai = sum(result[(result['性质']=='双开')&(result['现手']>=big_order)]['现手'])/total_volume
shuang_pin = sum(result[(result['性质']=='双平')&(result['现手']>=big_order)]['现手'])/total_volume
all_ratio = duo_kai+kon_pin+kon_kai+duo_pin+duo_huan+kon_huan+shuang_kai+shuang_pin
#多开-空开
duo_minus_kon_kai = duo_kai-kon_kai
#空平-多平
kon_minus_duo_pin = kon_pin-duo_pin
#多-空
duo_minus_kon = duo_minus_kon_kai+kon_minus_duo_pin
stat_result = pd.DataFrame([duo_kai,kon_pin,kon_kai,duo_pin,duo_huan,kon_huan,shuang_kai,shuang_pin,all_ratio,duo_minus_kon_kai,kon_minus_duo_pin,duo_minus_kon],\
index=['多开','空平','空开','多平','多换','空换','双开','双平','总计','多开-空开','空平-多平','多-空'],columns=['占比'])
return stat_result.T
def get_1day1ticker(ticker,date,big_order=0):
"""
获得某天一个合约的统计
"""
result = get_future_tick_stat(ticker,date)
temp = get_8stat(result,big_order=big_order)
return temp
def get_1day1ticker_wenhuaBigStat(ticker,date):
"""
获得某天一个合约的统计,文华大单(大于前一日单笔成交量的5倍定义为大单)
"""
#前一天成交量
pre_day = str(get_trade_days(start_date=None, end_date=date, count=2)[0])
pre_vol = get_price(ticker, start_date=pre_day, end_date=pre_day, frequency='daily', fields='volume', fq=None).iloc[0,0]
result = get_future_tick_stat(ticker,date)
big_order = pre_vol/len(result)*5
temp = get_8stat(result,big_order=big_order)
return temp
def get_1day1ticker_main(str1,date,big_order=0):
"""
获得某天一个合约的统计,只需要输入标的名称,如'RB'
"""
ticker = get_dominant_future(str1,date)
result = get_future_tick_stat(ticker,date)
temp = get_8stat(result,big_order=big_order)
return temp
def get_ticker(date):
"""
输入日期,返回当天主力合约代码ticker,及合约简称
持仓量大于1万手
"""
opid_th = 10000
#获得主力合约
a = get_all_securities(types=['futures'])
cond = ['主力合约' in x for x in a.display_name]
main = a[cond].index.tolist() #9999
main1 = [x[:-9] for x in main] #AU,仅含标的字母
main2 = [get_dominant_future(x,date) for x in main1]
main2_ = [x for x in main2 if x!='']
#持仓量
main2_opid = get_extras('futures_positions', main2_, start_date=date, end_date=date, df=True).T
need_ticker = main2_opid[main2_opid[date]>opid_th].index.tolist()
return need_ticker
#----------------------
def get_oneDay_stat(date,big_order=0):
"""
获得某天的八项统计结果
"""
ticker_data = get_ticker(date)
all_ticker_stats = pd.DataFrame()
for i in range(len(ticker_data)):
ticker = ticker_data[i]
result = get_future_tick_stat(ticker,date)
temp = get_8stat(result,big_order)
temp.index = [ticker]
all_ticker_stats = all_ticker_stats.append(temp)
all_ticker_stats = all_ticker_stats.sort_values(by='多开-空开',ascending=False)
return all_ticker_stats
def get_headtail(date,n=5,big_order=0):
"""
计算某天做多做空前N名
"""
data = get_oneDay_stat(date,big_order=big_order)
temp1 = data.head(n)
temp2 = data.tail(n)
result = temp1.append(temp2)
result.index = pd.MultiIndex.from_arrays([['做多']*n+['做空']*n,result.index.tolist()])
return result
def get_nDay_stas(ticker,startDate,endDate,big_order=0):
"""
返回某个合约-某段时间的统计结果
"""
tradeDay = get_trade_days(start_date=startDate, end_date=endDate)
tradeDay = [str(x) for x in tradeDay]
result = pd.DataFrame()
for date in tradeDay:
temp = get_1day1ticker(ticker,date,big_order=big_order)
temp.index = [date]
result = result.append(temp)
return result
if __name__ == '__main__':
from datetime import datetime
t0 = datetime.now()
date = '2019-05-20'
#all_data = get_oneDay_stat(date,big_order=0)
print('用时:{}'.format(datetime.now()-t0))
一:计算某一天所有主力合约的分笔统计结果¶
时间大约2分钟
from datetime import datetime
t0 = datetime.now()
all_data1 = get_oneDay_stat('2019-06-19',big_order=0)
print('用时:{}'.format(datetime.now()-t0))
all_data1
当然,你可以根据衍生的指标多开-空开来指导交易¶
get_headtail('2019-06-18',n=5,big_order=0)
二:某段时间某个品种的分笔统计数据¶
ticker = 'RB1910.XSGE'
startDate = '2019-06-01'
endDate = '2019-06-19'
result = get_nDay_stas(ticker,startDate,endDate,big_order=0)
result