# 【前方高能!】Gifts from Santa Claus——股指期貨趨勢交易研究
> 來源:https://uqer.io/community/share/567ca9b1228e5b3444688438

## 股指期貨的前世今生
股指期貨,名曰期指,乃期貨界的明珠,現貨對應的是股票指數,其逼格比之大豆棉油不知道甩幾條巷子。期指的上市為股票市場提供了很好的風險管理和做策略的工具,礦工們也覺得自己終于能吃上一碗帶肉的康師傅牛肉面。正所謂俠之大者,為國背鍋,這一年股指期貨經歷了不平凡的跌宕起伏。上半年市場一片開朗,10000點不是夢,期指也由原來的 'IF(滬深300)'一個品種增加到了‘IH(上證50)’,‘IF(滬深300)’,‘IC(中證500)’三個品種。“放開讓孩兒們玩吧”,不愿透露姓名的領導心里想著,順勢掐滅了手上的煙頭。不幸的是,市場下半年被玩壞了,從去杠桿到查做空、從基金經理被約談到公安部出動、從券商砸獎金到救市基金強勢入場,轟轟烈烈的市場拯救活動持續了一兩個月,終于把市場給摁了下來。比較不幸的是,量化交易和衍生品受到了比較嚴重的打擊和監管。股指期貨的交易方式、保證金比例、交易頻率都受到了嚴厲的限制,并成為眾矢之的。
雖不知股指期貨的未來何去何從,但效率的提升才能代表未來的發展方向,投資管理變得更為理性化、程序化、智能化對于專業的投資機構來講是大勢所趨。我們相信期指的嚴冬期總會過去,我們有理想,我們有愿望,宣誓完畢!
## 股指期貨的才藝
一個品種的股指期貨有四份合約,分為當月合約、次月合約、第一季月合約和第二季月合約。作為衍生品,它為二級市場投資帶來了豐富的投資方式,并在投資策略中擔當著各種各樣的角色。基于股指期貨可做的事情例如:
+ 1、構建alpha市場中性策略;
+ 2、期限套利;
+ 3、期指間跨期跨品種套利;
+ 4、趨勢交易;
+ 5、高頻交易(現在估計比較難)。
這次我們主要研究一種單品種的股指期貨趨勢交易策略,提供了一種基于市場情緒的擇時指標,稱之為ITS(Informed Trader Sentiment),參考文獻為。
## ITS——基于市場情緒的擇時指標
中金所每日收盤后會公布股指期貨的成交持倉量表,表單中會有三個項目的排名:成交量、持買單量和持賣單量,表單會列出前20名的會員單位。這些會員單位代表了期貨市場上最大的機構投資者。我們將同時出現在三個表單排名中的單位視作VIP單位,他們是這個市場的中流砥柱,他們的投資情緒會影響到市場未來的走勢,我們需要做的就是找到對的大佬,跟著大佬的情緒飛。那如何才能跟到對的大佬?我們基于這樣一個邏輯:如果某位大佬更有預知市場的能力,那么他會在交易中更為堅定的選擇某一個買賣方向,它由于買賣帶來的成交量就會相對較小,進而(持倉量/成交量)數值相對會大,我們認定他是知情者(對的大佬);若某個大佬的持倉量與前一位大佬相當但成交量明顯偏大,說明這位大佬的交易有更多的不確定性,我們也就認定他不是一個知情者(沒有緣分的大佬)。找到對的大佬之后,便開始估測一下大佬的情緒。我們用“對的大佬”們的(持買單量-持賣單量)/(持買單量+持賣單量)(此處的持買單和賣單量都是對的大佬們求和的總量)作為歸一化的指標,根據指標是否大于某個閾值Thres來判定大佬對于市場是看多還是看空。那么我們的信號提取過程為:
+ step1. 表單中篩選VIP單位(三個排名均上榜)→ 備選大佬;
+ step2. 備選大佬中找到(持倉量/成交量)大于Avg的VIP單位 → 對的大佬;
+ step3. ITS = (持買單量-持賣單量)/(持買單量+持賣單量)
## ITS信號生成器
```py
from CAL.PyCAL import *
import copy as cp
import numpy as np
###########################################################################################################
# generate the its signal
###########################################################################################################
class itsFutSignal:
def __init__(self,secID,currentDate):
####input
self.secID = secID
self.currentDate = currentDate
####output
self.sigDate = self.lastDateGet()
self.contract = self.currContractGet()
self.posTable = self.posTableGet()
self.vipDict = self.vipDictGet()
self.sentiSig = self.sentiSigGet()
self.inforedInvestor = self.inforedInvestorGet()
self.itsSig = self.itsSigGet()
def lastDateGet(self):
calendar = Calendar('China.SSE')
date = calendar.advanceDate(self.currentDate,'-'+str(1)+'B').toDateTime()
return date
def currContractGet(self):
future = DataAPI.MktMFutdGet(mainCon=u"1",contractMark=u"",contractObject=u"",tradeDate=self.sigDate,startDate=u"",endDate=u"",field=u"",pandas="1")
for index in future.ticker:
if index[:2] == self.secID:
return future[future.ticker==index].ticker.tolist()[0]
def posTableGet(self):
try:
pos = DataAPI.MktFutMLRGet(secID=u"",ticker=self.contract,beginDate=self.sigDate,endDate=self.sigDate,field=u"",pandas="1")
neg = DataAPI.MktFutMSRGet(secID=u"",ticker=self.contract,beginDate=self.sigDate,endDate=self.sigDate,field=u"",pandas="1")
vol = DataAPI.MktFutMTRGet(secID=u"",ticker=self.contract,beginDate=self.sigDate,endDate=self.sigDate,field=u"",pandas="1")
return {'pos':pos,'neg':neg,'vol':vol}
except:
calendar = Calendar('China.SSE')
self.sigDate = calendar.advanceDate(self.sigDate,'-'+str(1)+'B').toDateTime()
self.contract = self.currContractGet()
return self.posTableGet()
def list2Dict(self,list):
keys = list[0]
values = list[1]
resultDict = {}
for index in range(len(keys)):
resultDict[keys[index]] = values[index]
return resultDict
def vipDictGet(self):
####get data
longDict = self.list2Dict([self.posTable['pos'].partyShortName.tolist(),self.posTable['pos'].longVol])
shortDict = self.list2Dict([self.posTable['neg'].partyShortName.tolist(),self.posTable['neg'].shortVol])
volDict = self.list2Dict([self.posTable['vol'].partyShortName.tolist(),self.posTable['vol'].turnoverVol])
####get vip list
vipList = []
for index in longDict.keys():
if index in shortDict.keys():
if index in volDict.keys():
vipList.append(index)
####get vip dict
vipDict = {}
for index in vipList:
vipDict[index] = [longDict[index],shortDict[index],volDict[index]]
return vipDict
def sentiSigGet(self):
sentiSig = {}
for index in self.vipDict:
sentiSig[index] = sum(self.vipDict[index][:2])*1.0/self.vipDict[index][-1]
return sentiSig
def inforedInvestorGet(self):
if len(self.sentiSig) != 0:
sentiAvg = sum(self.sentiSig.values())/len(self.sentiSig)
inforedInvestor = [index for index in self.sentiSig if self.sentiSig[index] > sentiAvg]
return inforedInvestor
else:
sentiAvg = 0
return []
def itsSigGet(self):
totalBuy = 0
totalSell = 0
if len(self.inforedInvestor) != 0:
for index in self.inforedInvestor:
totalBuy += self.vipDict[index][0]
totalSell += self.vipDict[index][1]
if totalBuy + totalSell != 0:
return 1.0*(totalBuy - totalSell)/(totalBuy + totalSell)
else:
return 'null'
else:
return 'null'
```
## ITS趨勢交易信號
ITS信號代表了對的大佬們的情緒,那么如何利用它給出每日的交易信號呢?我們利用最為直觀有效的閾值策略,設定某閾值`Thres`:
1)`ITS > Thres`: 大佬看多,買買買,交易信號為1;
2)`ITS < Thres`: 大佬看空,賣賣賣,交易信號為-1;
3)`ITS = Thres & DataErr`: 形勢不明朗或找不到大佬,停止交易觀望,交易信號為0
此處我們取 `Thres = -0.12`? Why?其實是這樣的,由于期現套利交易的存在,因此期指本身有一部分的空單是由于期限套利造成的,由于這部分資金通常會留存較久,因此通常情況下期指的持倉總量應該是空單偏多,而我們判斷市場情緒的時候要把這部分期貨市場上的“裸空單”給剔除掉,因此Thres應該設置為負。
## IF趨勢交易測試
由于目前Strategy部分還不好支持期指的交易回測,因此用腳本生成了測試數據。
1)交易標的:滬深300主力合約。用IF來測試的原因很簡單,樣本數多呀!
2)每日的交易信號:根據前一日收盤后的持倉量表單計算ITS后根據閾值產生;
3)每日收益率:我們假定在獲取當日的信號后,在開盤的一段時間內以某個價格買入期指,持有至臨近收盤后以某個價格賣出,做日內交易。那么買賣價如何界定?有三種方式來計算:①昨收-今收; ②今開-今收; ③昨結算-今結算。 ①和②都是時點價格,而③是均價。①必然不合理因為無法在昨日收盤前得到今日的交易信號,不具有可操作性;②是時點價格,可操作性也不強;對③來講,由于結算價是一段時間的均價,我們認為拿這個均價作為買賣的期望價格是合理的。所以每日收益率的計算方式是③;
```py
startDate = '20110101'
endDate = '20150801'
future = DataAPI.MktMFutdGet(mainCon=u"1",contractMark=u"",contractObject=u"",tradeDate=u'',startDate=startDate,endDate=endDate,field=u"",pandas="1")
# print future
closePrice = []
openPrice = []
preClosePrice = []
settlePrice = []
preSettlePrice = []
tradeDate = []
ticker = []
for index in future.ticker.tolist():
if index[:2] == 'IF':
if index not in ticker:
ticker.append(index)
for index in ticker:
closePrice += future[future.ticker==index]['closePrice'].tolist()
openPrice += future[future.ticker==index]['openPrice'].tolist()
preClosePrice += future[future.ticker==index]['preClosePrice'].tolist()
settlePrice += future[future.ticker==index]['settlePrice'].tolist()
preSettlePrice += future[future.ticker==index]['preSettlePrice'].tolist()
tradeDate += future[future.ticker==index]['tradeDate'].tolist()
closePrice = np.array(closePrice)
openPrice = np.array(openPrice)
preClosePrice = np.array(preClosePrice)
settlePrice = np.array(settlePrice)
preSettlePrice = np.array(preSettlePrice)
closeRetRate = (closePrice - preClosePrice)/preClosePrice
settleRetRate = (settlePrice - preSettlePrice)/preSettlePrice
clopenRetRate = (closePrice - openPrice)/openPrice
tradeDate = tradeDate
itsValue = [itsFutSignal('IF',index).itsSig for index in tradeDate]
itsSignal = []
thres = -0.12
for index in itsValue:
if index != 'null':
if index > thres:
itsSignal.append(1)
else:
itsSignal.append(-1)
else:
itsSignal.append(0)
itsSignal = np.array(itsSignal)
benchMark = DataAPI.MktIdxdGet(tradeDate=u"",indexID=u"",ticker=u"000300",beginDate=startDate,endDate=endDate,field=u"closeIndex",pandas="1")['closeIndex'].tolist()
benchMark = benchMark/benchMark[0]
```
## 回測展示
下面為回測結果展示,測算細節如下:
1) 每日收益率根據結算價來計算,前結算價作為買入的參考均價,結算價作為賣出的參考均價;
2)收益率曲線計算采用單利計算;
3)無風險利率取5%;
4)最后一小段曲線為平是由于股指期貨受到限制導致交易停止
```py
import matplotlib.pyplot as plt
####calculate the daily return
dailyRet = settleRetRate*itsSignal
####calculate the winRate
count = 0
denom = 0
for index in dailyRet:
if index > 0:
count += 1
if index != 0:
denom += 1
print '策略勝率 : ' + str(round((count*1.0/denom)*100,2)) + '%'
####calculate the curve
curve = [1]
position = 0.8
for index in dailyRet:
curve.append(curve[-1] + index*position)
####calculate the location
print '策略倉位 : ' + str(position)
####calculate the max drawDown
maxDrawDown = []
for index in range(len(curve)):
tmp = [ele/curve[index] for ele in curve[index:]]
maxDrawDown.append(min(tmp))
print '最大回撤 : ' + str(round((1-min(maxDrawDown))*100,2)) + '%'
####calculate the sharpRatio
stDate = Date(int(startDate[:4]),int(startDate[4:6]),int(startDate[6:8]))
edDate = Date(int(endDate[:4]),int(endDate[4:6]),int(endDate[6:8]))
duration = round((edDate-stDate)/365.0,1)
retYearly = curve[-1]/duration
interest = 0.05
fluctuation = np.std(curve)/np.sqrt(duration)
print '年化收益 : ' + str(round(retYearly,2)*100.0) + '%'
print '夏普比率 : ' + str(round((retYearly-interest)/fluctuation,2))
####plot the figure
print '\n'
plt.plot(curve)
plt.plot(benchMark)
plt.legend(['Strategy','BenchMark'],0)
策略勝率 : 55.03%
策略倉位 : 0.8
最大回撤 : 10.06%
年化收益 : 49.0%
夏普比率 : 2.44
<matplotlib.legend.Legend at 0xed4cc50>
```

被曲線美哭了,不叨叨了,Merry Xmas!

- Python 量化交易教程
- 第一部分 新手入門
- 一 量化投資視頻學習課程
- 二 Python 手把手教學
- 量化分析師的Python日記【第1天:誰來給我講講Python?】
- 量化分析師的Python日記【第2天:再接著介紹一下Python唄】
- 量化分析師的Python日記【第3天:一大波金融Library來襲之numpy篇】
- 量化分析師的Python日記【第4天:一大波金融Library來襲之scipy篇】
- 量化分析師的Python日記【第5天:數據處理的瑞士軍刀pandas】
- 量化分析師的Python日記【第6天:數據處理的瑞士軍刀pandas下篇
- 量化分析師的Python日記【第7天:Q Quant 之初出江湖】
- 量化分析師的Python日記【第8天 Q Quant兵器譜之函數插值】
- 量化分析師的Python日記【第9天 Q Quant兵器譜之二叉樹】
- 量化分析師的Python日記【第10天 Q Quant兵器譜 -之偏微分方程1】
- 量化分析師的Python日記【第11天 Q Quant兵器譜之偏微分方程2】
- 量化分析師的Python日記【第12天:量化入門進階之葵花寶典:因子如何產生和回測】
- 量化分析師的Python日記【第13天 Q Quant兵器譜之偏微分方程3】
- 量化分析師的Python日記【第14天:如何在優礦上做Alpha對沖模型】
- 量化分析師的Python日記【第15天:如何在優礦上搞一個wealthfront出來】
- 第二部分 股票量化相關
- 一 基本面分析
- 1.1 alpha 多因子模型
- 破解Alpha對沖策略——觀《量化分析師Python日記第14天》有感
- 熔斷不要怕, alpha model 為你保駕護航!
- 尋找 alpha 之: alpha 設計
- 1.2 基本面因子選股
- Porfolio(現金比率+負債現金+現金保障倍數)+市盈率
- ROE選股指標
- 成交量因子
- ROIC&cashROIC
- 【國信金工】資產周轉率選股模型
- 【基本面指標】Cash Cow
- 量化因子選股——凈利潤/營業總收入
- 營業收入增長率+市盈率
- 1.3 財報閱讀 ? [米缸量化讀財報] 資產負債表-投資相關資產
- 1.4 股東分析
- 技術分析入門 【2】 —— 大家搶籌碼(06年至12年版)
- 技術分析入門 【2】 —— 大家搶籌碼(06年至12年版)— 更新版
- 誰是中國A股最有錢的自然人
- 1.5 宏觀研究
- 【干貨包郵】手把手教你做宏觀擇時
- 宏觀研究:從估值角度看當前市場
- 追尋“國家隊”的足跡
- 二 套利
- 2.1 配對交易
- HS300ETF套利(上)
- 【統計套利】配對交易
- 相似公司股票搬磚
- Paired trading
- 2.2 期現套利 ? 通過股指期貨的期現差與 ETF 對沖套利
- 三 事件驅動
- 3.1 盈利預增
- 盈利預增事件
- 事件驅動策略示例——盈利預增
- 3.2 分析師推薦 ? 分析師的金手指?
- 3.3 牛熊轉換
- 歷史總是相似 牛市還在延續
- 歷史總是相似 牛市已經見頂?
- 3.4 熔斷機制 ? 股海拾貝之 [熔斷錯殺股]
- 3.5 暴漲暴跌 ? [實盤感悟] 遇上暴跌我該怎么做?
- 3.6 兼并重組、舉牌收購 ? 寶萬戰-大戲開幕
- 四 技術分析
- 4.1 布林帶
- 布林帶交易策略
- 布林帶回調系統-日內
- Conservative Bollinger Bands
- Even More Conservative Bollinger Bands
- Simple Bollinger Bands
- 4.2 均線系統
- 技術分析入門 —— 雙均線策略
- 5日線10日線交易策略
- 用5日均線和10日均線進行判斷 --- 改進版
- macross
- 4.3 MACD
- Simple MACD
- MACD quantization trade
- MACD平滑異同移動平均線方法
- 4.4 阿隆指標 ? 技術指標阿隆( Aroon )全解析
- 4.5 CCI ? CCI 順勢指標探索
- 4.6 RSI
- 重寫 rsi
- RSI指標策略
- 4.7 DMI ? DMI 指標體系的構建及簡單應用
- 4.8 EMV ? EMV 技術指標的構建及應用
- 4.9 KDJ ? KDJ 策略
- 4.10 CMO
- CMO 策略模仿練習 1
- CMO策略模仿練習2
- [技術指標] CMO
- 4.11 FPC ? FPC 指標選股
- 4.12 Chaikin Volatility
- 嘉慶離散指標測試
- 4.13 委比 ? 實時計算委比
- 4.14 封單量
- 按照封單跟流通股本比例排序,剔除6月上市新股,前50
- 漲停股票封單統計
- 實時計算漲停板股票的封單資金與總流通市值的比例
- 4.15 成交量 ? 決戰之地, IF1507 !
- 4.16 K 線分析 ? 尋找夜空中最亮的星
- 五 量化模型
- 5.1 動量模型
- Momentum策略
- 【小散學量化】-2-動量模型的簡單實踐
- 一個追漲的策略(修正版)
- 動量策略(momentum driven)
- 動量策略(momentum driven)——修正版
- 最經典的Momentum和Contrarian在中國市場的測試
- 最經典的Momentum和Contrarian在中國市場的測試-yanheven改進
- [策略]基于勝率的趨勢交易策略
- 策略探討(更新):價量結合+動量反轉
- 反向動量策略(reverse momentum driven)
- 輕松跑贏大盤 - 主題Momentum策略
- Contrarian strategy
- 5.2 Joseph Piotroski 9 F-Score Value Investing Model · 基本面選股系統:Piotroski F-Score ranking system
- 5.3 SVR · 使用SVR預測股票開盤價 v1.0
- 5.4 決策樹、隨機樹
- 決策樹模型(固定模型)
- 基于Random Forest的決策策略
- 5.5 鐘擺理論 · 鐘擺理論的簡單實現——完美躲過股災和精準抄底
- 5.6 海龜模型
- simple turtle
- 俠之大者 一起賺錢
- 5.7 5217 策略 · 白龍馬的新手策略
- 5.8 SMIA · 基于歷史狀態空間相似性匹配的行業配置 SMIA 模型—取交集
- 5.9 神經網絡
- 神經網絡交易的訓練部分
- 通過神經網絡進行交易
- 5.10 PAMR · PAMR : 基于均值反轉的投資組合選擇策略 - 修改版
- 5.11 Fisher Transform · Using Fisher Transform Indicator
- 5.12 分型假說, Hurst 指數 · 分形市場假說,一個聽起來很美的假說
- 5.13 變點理論 · 變點策略初步
- 5.14 Z-score Model
- Zscore Model Tutorial
- 信用債風險模型初探之:Z-Score Model
- user-defined package
- 5.15 機器學習 · Machine Learning 學習筆記(一) by OTreeWEN
- 5.16 DualTrust 策略和布林強盜策略
- 5.17 卡爾曼濾波
- 5.18 LPPL anti-bubble model
- 今天大盤熔斷大跌,后市如何—— based on LPPL anti-bubble model
- 破解股市泡沫之謎——對數周期冪率(LPPL)模型
- 六 大數據模型
- 6.1 市場情緒分析
- 通聯情緒指標策略
- 互聯網+量化投資 大數據指數手把手
- 6.2 新聞熱點
- 如何使用優礦之“新聞熱點”?
- 技術分析【3】—— 眾星拱月,眾口鑠金?
- 七 排名選股系統
- 7.1 小市值投資法
- 學習筆記:可模擬(小市值+便宜 的修改版)
- 市值最小300指數
- 流通市值最小股票(新篩選器版)
- 持有市值最小的10只股票
- 10% smallest cap stock
- 7.2 羊駝策略
- 羊駝策略
- 羊駝反轉策略(修改版)
- 羊駝反轉策略
- 我的羊駝策略,選5只股無腦輪替
- 7.3 低價策略
- 專撿便宜貨(新版quartz)
- 策略原理
- 便宜就是 alpha
- 八 輪動模型
- 8.1 大小盤輪動 · 新手上路 -- 二八ETF擇時輪動策略2.0
- 8.2 季節性策略
- Halloween Cycle
- Halloween cycle 2
- 夏買電,東買煤?
- 歷史的十一月板塊漲幅
- 8.3 行業輪動
- 銀行股輪動
- 申萬二級行業在最近1年、3個月、5個交易日的漲幅統計
- 8.4 主題輪動
- 快速研究主題神器
- recommendation based on subject
- strategy7: recommendation based on theme
- 板塊異動類
- 風險因子(離散類)
- 8.5 龍頭輪動
- Competitive Securities
- Market Competitiveness
- 主題龍頭類
- 九 組合投資
- 9.1 指數跟蹤 · [策略] 指數跟蹤低成本建倉策略
- 9.2 GMVP · Global Minimum Variance Portfolio (GMVP)
- 9.3 凸優化 · 如何在 Python 中利用 CVXOPT 求解二次規劃問題
- 十 波動率
- 10.1 波動率選股 · 風平浪靜 風起豬飛
- 10.2 波動率擇時
- 基于 VIX 指數的擇時策略
- 簡單低波動率指數
- 10.3 Arch/Garch 模型 · 如何使用優礦進行 GARCH 模型分析
- 十一 算法交易
- 11.1 VWAP · Value-Weighted Average Price (VWAP)
- 十二 中高頻交易
- 12.1 order book 分析 · 基于高頻 limit order book 數據的短程價格方向預測—— via multi-class SVM
- 12.2 日內交易 · 大盤日內走勢 (for 擇時)
- 十三 Alternative Strategy
- 13.1 易經、傳統文化 · 老黃歷診股
- 第三部分 基金、利率互換、固定收益類
- 一 分級基金
- “優礦”集思錄——分級基金專題
- 基于期權定價的分級基金交易策略
- 基于期權定價的興全合潤基金交易策略
- 二 基金分析
- Alpha 基金“黑天鵝事件” -- 思考以及原因
- 三 債券
- 債券報價中的小陷阱
- 四 利率互換
- Swap Curve Construction
- 中國 Repo 7D 互換的例子
- 第四部分 衍生品相關
- 一 期權數據
- 如何獲取期權市場數據快照
- 期權高頻數據準備
- 二 期權系列
- [ 50ETF 期權] 1. 歷史成交持倉和 PCR 數據
- 【50ETF期權】 2. 歷史波動率
- 【50ETF期權】 3. 中國波指 iVIX
- 【50ETF期權】 4. Greeks 和隱含波動率微笑
- 【50ETF期權】 5. 日內即時監控 Greeks 和隱含波動率微笑
- 【50ETF期權】 5. 日內即時監控 Greeks 和隱含波動率微笑
- 三 期權分析
- 【50ETF期權】 期權擇時指數 1.0
- 每日期權風險數據整理
- 期權頭寸計算
- 期權探秘1
- 期權探秘2
- 期權市場一周縱覽
- 基于期權PCR指數的擇時策略
- 期權每日成交額PC比例計算
- 四 期貨分析
- 【前方高能!】Gifts from Santa Claus——股指期貨趨勢交易研究