【50ETF期权】 3. 中国波指 iVIX

来源:https://uqer.io/community/share/560493f7f9f06c590c65ef21

在本文中,我们将通过量化实验室提供的数据,计算基于50ETF期权的中国波指 iVIX

波动率VIX指数是跟踪市场波动性的指数,一般通过标的期权的隐含波动率计算得来。当VIX越高,表示市场参与者预期后市波动程度会更加激烈,同时也反映其不安的心理状态;相反,VIX越低时,则反映市场参与者预期后市波动程度会趋于缓和。因此,VIX又被称为投资人恐慌指标(The Investor Fear Gauge)。

中国波指由上交所发布,用于衡量上证50ETF未来30日的预期波动。按照上交所网页描述:该指数是根据方差互换的原理,结合50ETF期权的实际运作特点,并通过对上证所交易的50ETF期权价格的计算编制而得。网址为: http://www.sse.com.cn/assortment/derivatives/options/volatility/ , 该网页中发布历史 iVIX 和当日日内 iVIX 数据

  1. from CAL.PyCAL import *
  2. import pandas as pd
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. from matplotlib import rc
  6. rc('mathtext', default='regular')
  7. import seaborn as sns
  8. sns.set_style('white')
  9. from matplotlib import dates
  10. from pandas import Series, DataFrame, concat
  11. from scipy import interpolate
  12. import math
  13. import time

上证50ETF收盘价,用来和iVIX对比走势

  1. # 华夏上证50ETF
  2. secID = '510050.XSHG'
  3. begin = Date(2015, 2, 9)
  4. end = Date.todaysDate()
  5. fields = ['tradeDate', 'closePrice']
  6. etf = DataAPI.MktFunddGet(secID, beginDate=begin.toISO().replace('-', ''), endDate=end.toISO().replace('-', ''), field=fields)
  7. etf['tradeDate'] = pd.to_datetime(etf['tradeDate'])
  8. etf = etf.set_index('tradeDate')
  9. etf.tail(2)
closePrice
tradeDate
2015-09-232.180
2015-09-242.187

上海银行间同业拆借利率 SHIBOR,用来作为无风险利率参考

  1. ## 银行间质押式回购利率
  2. def getHistDayInterestRateInterbankRepo(date):
  3. cal = Calendar('China.SSE')
  4. period = Period('-10B')
  5. begin = cal.advanceDate(date, period)
  6. begin_str = begin.toISO().replace('-', '')
  7. date_str = date.toISO().replace('-', '')
  8. # 以下的indicID分别对应的银行间质押式回购利率周期为:
  9. # 1D, 7D, 14D, 21D, 1M, 3M, 4M, 6M, 9M, 1Y
  10. indicID = [u"M120000067", u"M120000068", u"M120000069", u"M120000070", u"M120000071",
  11. u"M120000072", u"M120000073", u"M120000074", u"M120000075", u"M120000076"]
  12. period = np.asarray([1.0, 7.0, 14.0, 21.0, 30.0, 90.0, 120.0, 180.0, 270.0, 360.0]) / 360.0
  13. period_matrix = pd.DataFrame(index=indicID, data=period, columns=['period'])
  14. field = u"indicID,indicName,publishTime,periodDate,dataValue,unit"
  15. interbank_repo = DataAPI.ChinaDataInterestRateInterbankRepoGet(indicID=indicID,beginDate=begin_str,endDate=date_str,field=field,pandas="1")
  16. interbank_repo = interbank_repo.groupby('indicID').first()
  17. interbank_repo = concat([interbank_repo, period_matrix], axis=1, join='inner').sort_index()
  18. return interbank_repo
  19. ## 银行间同业拆借利率
  20. def getHistDaySHIBOR(date):
  21. date_str = date.toISO().replace('-', '')
  22. # 以下的indicID分别对应的SHIBOR周期为:
  23. # 1D, 7D, 14D, 1M, 3M, 6M, 9M, 1Y
  24. indicID = [u"M120000057", u"M120000058", u"M120000059", u"M120000060",
  25. u"M120000061", u"M120000062", u"M120000063", u"M120000064"]
  26. period = np.asarray([1.0, 7.0, 14.0, 30.0, 90.0, 180.0, 270.0, 360.0]) / 360.0
  27. period_matrix = pd.DataFrame(index=indicID, data=period, columns=['period'])
  28. field = u"indicID,indicName,publishTime,periodDate,dataValue,unit"
  29. interest_shibor = DataAPI.ChinaDataInterestRateSHIBORGet(indicID=indicID,beginDate=date_str,endDate=date_str,field=field,pandas="1")
  30. interest_shibor = interest_shibor.set_index('indicID')
  31. interest_shibor = concat([interest_shibor, period_matrix], axis=1, join='inner').sort_index()
  32. return interest_shibor
  33. ## 插值得到给定的周期的无风险利率
  34. def periodsSplineRiskFreeInterestRate(date, periods):
  35. # 此处使用SHIBOR来插值
  36. init_shibor = getHistDaySHIBOR(date)
  37. shibor = {}
  38. min_period = min(init_shibor.period.values)
  39. max_period = max(init_shibor.period.values)
  40. for p in periods.keys():
  41. tmp = periods[p]
  42. if periods[p] > max_period:
  43. tmp = max_period * 0.99999
  44. elif periods[p] < min_period:
  45. tmp = min_period * 1.00001
  46. sh = interpolate.spline(init_shibor.period.values, init_shibor.dataValue.values, [tmp], order=3)
  47. shibor[p] = sh[0]/100.0
  48. return shibor

50ETF历史波动率,用来和iVIX走势作对比

  1. ## 计算一段时间标的的历史波动率,返回值包括以下不同周期的波动率:
  2. # 一周,半月,一个月,两个月,三个月,四个月,五个月,半年,九个月,一年,两年
  3. def getHistVolatilityEWMA(secID, beginDate, endDate):
  4. cal = Calendar('China.SSE')
  5. spotBeginDate = cal.advanceDate(beginDate,'-520B',BizDayConvention.Preceding)
  6. spotBeginDate = Date(2006, 1, 1)
  7. begin = spotBeginDate.toISO().replace('-', '')
  8. end = endDate.toISO().replace('-', '')
  9. fields = ['tradeDate', 'preClosePrice', 'closePrice', 'settlePrice', 'preSettlePrice']
  10. security = DataAPI.MktFunddGet(secID, beginDate=begin, endDate=end, field=fields)
  11. security['dailyReturn'] = security['closePrice']/security['preClosePrice'] # 日回报率
  12. security['u2'] = (np.log(security['dailyReturn']))**2 # u2为复利形式的日回报率平方
  13. # security['u2'] = (security['dailyReturn'] - 1.0)**2 # u2为日价格变化百分比的平方
  14. security['tradeDate'] = pd.to_datetime(security['tradeDate'])
  15. periods = {'hv1W': 5, 'hv2W': 10, 'hv1M': 21, 'hv2M': 41, 'hv3M': 62, 'hv4M': 83,
  16. 'hv5M': 104, 'hv6M': 124, 'hv9M': 186, 'hv1Y': 249, 'hv2Y': 497}
  17. # 利用pandas中的ewma模型计算波动率
  18. for prd in periods.keys():
  19. # 此处的span实际上就是上面计算波动率公式中lambda表达式中的N
  20. security[prd] = np.round(np.sqrt(pd.ewma(security['u2'], span=periods[prd], adjust=False)), 5)*math.sqrt(252.0)
  21. security = security[security.tradeDate >= beginDate.toISO()]
  22. security = security.set_index('tradeDate')
  23. return security

1. 计算历史每日 iVIX

计算方法参考CBOE的手册:http://www.cboe.com/micro/vix/part2.aspx

  1. # 计算历史某一天的iVIX
  2. def calDayVIX(date, opt_info):
  3. var_sec = u"510050.XSHG"
  4. # 使用DataAPI.MktOptdGet,拿到历史上某一天的期权行情信息
  5. date_str = date.toISO().replace('-', '')
  6. fields_mkt = [u"optID", "tradeDate", "closePrice", 'settlPrice']
  7. opt_mkt = DataAPI.MktOptdGet(tradeDate=date_str, field=fields_mkt, pandas="1")
  8. opt_mkt = opt_mkt.set_index(u"optID")
  9. opt_mkt[u"price"] = opt_mkt['closePrice']
  10. # concat某一日行情和期权基本信息,得到所需数据
  11. opt = concat([opt_info, opt_mkt], axis=1, join='inner').sort_index()
  12. opt = opt[opt.varSecID==var_sec]
  13. exp_dates = map(Date.parseISO, np.sort(opt.expDate.unique()))
  14. trade_date = date
  15. exp_periods = {}
  16. for epd in exp_dates:
  17. exp_periods[epd] = (epd - date)*1.0/365.0
  18. risk_free = periodsSplineRiskFreeInterestRate(trade_date, exp_periods)
  19. sigma_square = {}
  20. for date in exp_dates:
  21. # 计算某一日的vix
  22. opt_date = opt[opt.expDate==date.toISO()]
  23. rf = risk_free[date]
  24. #rf = 0.05
  25. opt_call = opt_date[opt_date.contractType == 'CO'].set_index('strikePrice')
  26. opt_put = opt_date[opt_date.contractType == 'PO'].set_index('strikePrice')
  27. opt_call_price = opt_call[[u'price']].sort_index()
  28. opt_put_price = opt_put[[u'price']].sort_index()
  29. opt_call_price.columns = [u'callPrice']
  30. opt_put_price.columns = [u'putPrice']
  31. opt_call_put_price = concat([opt_call_price, opt_put_price], axis=1, join='inner').sort_index()
  32. opt_call_put_price['diffCallPut'] = opt_call_put_price.callPrice - opt_call_put_price.putPrice
  33. strike = abs(opt_call_put_price['diffCallPut']).idxmin()
  34. price_diff = opt_call_put_price['diffCallPut'][strike]
  35. ttm = exp_periods[date]
  36. fw = strike + np.exp(ttm*rf) * price_diff
  37. strikes = np.sort(opt_call_put_price.index.values)
  38. delta_K_tmp = np.concatenate((strikes, strikes[-1:], strikes[-1:]))
  39. delta_K_tmp = delta_K_tmp - np.concatenate((strikes[0:1], strikes[0:1], strikes))
  40. delta_K = np.concatenate((delta_K_tmp[1:2], delta_K_tmp[2:-2]/2, delta_K_tmp[-2:-1]))
  41. delta_K = pd.DataFrame(delta_K, index=strikes, columns=['deltaStrike'])
  42. # opt_otm = opt_out_of_money
  43. opt_otm = concat([opt_call[opt_call.index>fw], opt_put[opt_put.index<fw]], axis=0, join='inner')
  44. opt_otm = concat([opt_otm, delta_K], axis=1, join='inner').sort_index()
  45. # 计算VIX时,比forward price低的第一个行权价被设置为参考行权价,参考值以上
  46. # 的call和以下的put均为虚值期权,所有的虚值期权被用来计算VIX,然而计算中发
  47. # 现,有时候没有比forward price更低的行权价,例如2015-07-08,故有以下关于
  48. # 参考行权价的设置
  49. strike_ref = fw
  50. if len((strikes[strikes < fw])) > 0:
  51. strike_ref = max([k for k in strikes[strikes < fw]])
  52. opt_otm['price'][strike_ref] = (opt_call['price'][strike_ref] + opt_call['price'][strike_ref])/2.0
  53. exp_rt = np.exp(rf*ttm)
  54. opt_otm['sigmaTerm'] = opt_otm.deltaStrike*opt_otm.price/(opt_otm.index)**2
  55. sigma = opt_otm.sigmaTerm.sum()
  56. sigma = (sigma*2.0*exp_rt - (fw*1.0/strike_ref - 1.0)**2)/ttm
  57. sigma_square[date] = sigma
  58. # d_one, d_two 将被用来计算VIX(30):
  59. if exp_periods[exp_dates[0]] >= 1.0/365.0:
  60. d_one = exp_dates[0]
  61. d_two = exp_dates[1]
  62. else:
  63. d_one = exp_dates[1]
  64. d_two = exp_dates[2]
  65. w = (exp_periods[d_two] - 30.0/365.0)/(exp_periods[d_two] - exp_periods[d_one])
  66. vix30 = exp_periods[d_one]*w*sigma_square[d_one] + exp_periods[d_two]*(1 - w)*sigma_square[d_two]
  67. vix30 = 100*np.sqrt(vix30*365.0/30.0)
  68. # d_one, d_two 将被用来计算VIX(60):
  69. d_one = exp_dates[1]
  70. d_two = exp_dates[2]
  71. w = (exp_periods[d_two] - 60.0/365.0)/(exp_periods[d_two] - exp_periods[d_one])
  72. vix60 = exp_periods[d_one]*w*sigma_square[d_one] + exp_periods[d_two]*(1 - w)*sigma_square[d_two]
  73. vix60 = 100*np.sqrt(vix60*365.0/60.0)
  74. return vix30, vix60
  75. def getHistDailyVIX(beginDate, endDate):
  76. # 计算历史一段时间内的VIX指数并返回
  77. optionVarSecID = u"510050.XSHG"
  78. # 使用DataAPI.OptGet,一次拿取所有存在过的期权信息,以备后用
  79. fields_info = ["optID", u"varSecID", u'contractType', u'strikePrice', u'expDate']
  80. opt_info = DataAPI.OptGet(optID='', contractStatus=[u"DE", u"L"], field=fields_info, pandas="1")
  81. opt_info = opt_info.set_index(u"optID")
  82. cal = Calendar('China.SSE')
  83. cal.addHoliday(Date(2015,9,3))
  84. cal.addHoliday(Date(2015,9,4))
  85. dates = cal.bizDatesList(beginDate, endDate)
  86. histVIX = pd.DataFrame(0.0, index=map(Date.toDateTime, dates), columns=['VIX30','VIX60'])
  87. histVIX.index.name = 'tradeDate'
  88. for date in histVIX.index:
  89. try:
  90. vix30, vix60 = calDayVIX(Date.fromDateTime(date), opt_info)
  91. except:
  92. histVIX = histVIX.drop(date)
  93. continue
  94. histVIX['VIX30'][date] = vix30
  95. histVIX['VIX60'][date] = vix60
  96. return histVIX
  97. def getHistOneDayVIX(date):
  98. # 计算历史某天的VIX指数并返回
  99. optionVarSecID = u"510050.XSHG"
  100. # 使用DataAPI.OptGet,一次拿取所有存在过的期权信息,以备后用
  101. fields_info = ["optID", u"varSecID", u'contractType', u'strikePrice', u'expDate']
  102. opt_info = DataAPI.OptGet(optID='', contractStatus=[u"DE", u"L"], field=fields_info, pandas="1")
  103. opt_info = opt_info.set_index(u"optID")
  104. cal = Calendar('China.SSE')
  105. cal.addHoliday(Date(2015,9,3))
  106. cal.addHoliday(Date(2015,9,4))
  107. if cal.isBizDay(date):
  108. vix30, vix60 = 0.0, 0.0
  109. vix30, vix60 = calDayVIX(date, opt_info)
  110. return vix30, vix60
  111. else:
  112. print date, "不是工作日"

历史每日iVIX 数据

  1. begin = Date(2015, 2, 9) # 起始日
  2. end = Date.todaysDate() # 截至今天
  3. hist_VIX = getHistDailyVIX(begin, end)
  4. hist_VIX.tail()
VIX30VIX60
tradeDate
2015-09-1838.05764839.074643
2015-09-2137.61025938.559095
2015-09-2234.50745636.788384
2015-09-2336.41342637.837454
2015-09-2437.11434824.346747

iVIX、50ETF收盘价、50ETF波动率比较

  1. start = Date(2007, 1, 1)
  2. end = Date.todaysDate()
  3. secID = '510050.XSHG'
  4. hist_HV = getHistVolatilityEWMA(secID, start, end)
  5. ## ----- 50ETF VIX指数和历史波动率比较 -----
  6. fig = plt.figure(figsize=(10,6))
  7. ax = fig.add_subplot(111)
  8. font.set_size(16)
  9. hist_HV_plot = hist_HV[hist_HV.index >= Date(2015,2,9).toISO()]
  10. etf_plot = etf[etf.index >= Date(2015,2,9).toISO()]
  11. lns1 = ax.plot(hist_HV_plot.index, hist_HV_plot.hv1M, '-', label = u'HV(30)')
  12. lns2 = ax.plot(hist_VIX.index, hist_VIX.VIX30/100.0, '-r', label = u'VIX(30)')
  13. #lns3 = ax.plot(hist_VIX.index, hist_VIX.VIX60/100.0, '-g', label = u'VIX(60)')
  14. ax2 = ax.twinx()
  15. lns4 = ax2.plot(etf_plot.index, etf_plot.closePrice, 'grey', label = '50ETF closePrice')
  16. lns = lns1+lns2+lns4
  17. labs = [l.get_label() for l in lns]
  18. ax.legend(lns, labs, loc=2)
  19. ax.grid()
  20. ax.set_xlabel(u"tradeDate")
  21. ax.set_ylabel(r"VIX")
  22. ax2.set_ylabel(r"closePrice")
  23. #ax.set_ylim(0, 0.80)
  24. ax2.set_ylim(1.5, 4)
  25. plt.title('50ETF VIX')
  26. <matplotlib.text.Text at 0x5acec90>

【50ETF期权】 3. 中国波指 iVIX - 图1

2. 基于iVIX的择时策略

策略思路:

  • 计算 VIX 三日均线
  • 前一日 VIX 向上穿过三日均线一定比例,则卖出
  • 前一日 VIX 向下穿过三日均线一定比例,则买入
  • 只买卖50ETF
  1. start = datetime(2015, 2, 9) # 回测起始时间
  2. end = datetime(2015, 9, 24) # 回测结束时间
  3. hist_VIX = getHistDailyVIX(start, end)
  4. hist_VIX.tail(2)
VIX30VIX60
tradeDate
2015-09-2336.41342637.837454
2015-09-2437.11434824.346747
  1. start = datetime(2015, 2, 9) # 回测起始时间
  2. end = datetime(2015, 9, 24) # 回测结束时间
  3. benchmark = '510050.XSHG' # 策略参考标准
  4. universe = ['510050.XSHG'] # 股票池
  5. capital_base = 100000 # 起始资金
  6. commission = Commission(0.0,0.0)
  7. window_short = 1
  8. window_long = 3
  9. SD = 0.1
  10. hist_VIX['short_window'] = pd.rolling_mean(hist_VIX['VIX30'], window=window_short)
  11. hist_VIX['long_window'] = pd.rolling_mean(hist_VIX['VIX30'], window=window_long)
  12. def initialize(account): # 初始化虚拟账户状态
  13. account.fund = universe[0]
  14. def handle_data(account): # 每个交易日的买入卖出指令
  15. fund = account.fund
  16. # 获取回测当日的前一天日期
  17. dt = Date.fromDateTime(account.current_date)
  18. cal = Calendar('China.IB')
  19. cal.addHoliday(Date(2015,9,3))
  20. cal.addHoliday(Date(2015,9,4))
  21. last_day = cal.advanceDate(dt,'-1B',BizDayConvention.Preceding) #计算出倒数第一个交易日
  22. last_last_day = cal.advanceDate(last_day,'-1B',BizDayConvention.Preceding) #计算出倒数第二个交易日
  23. last_day_str = last_day.strftime("%Y-%m-%d")
  24. last_last_day_str = last_last_day.strftime("%Y-%m-%d")
  25. # 计算买入卖出信号
  26. try:
  27. short_mean = hist_VIX['short_window'].loc[last_day_str] # 短均线值
  28. long_mean = hist_VIX['long_window'].loc[last_day_str] # 长均线值
  29. long_flag = True if (short_mean - long_mean) < - SD * long_mean else False
  30. short_flag = True if (short_mean - long_mean) > SD * long_mean else False
  31. except:
  32. long_flag = True
  33. short_flag = True
  34. if long_flag:
  35. approximationAmount = int(account.cash / account.referencePrice[fund] / 100.0) * 100
  36. order(fund, approximationAmount)
  37. elif short_flag:
  38. # 卖出时,全仓清空
  39. order_to(fund, 0)

【50ETF期权】 3. 中国波指 iVIX - 图2

3. 日内跟踪计算 iVIX

计算方法和日间iVIX类似

  1. def calSnapshotVIX(date, opt_info):
  2. var_sec = u"510050.XSHG"
  3. # 使用DataAPI.MktOptdGet,拿到历史上某一天的期权行情信息
  4. date_str = date.toISO().replace('-', '')
  5. fields_mkt = [u'optionId', u'dataDate', u'highPrice', u'lastPrice', u'lowPrice', u'openPrice', u'preSettlePrice', u'bidBook_price1', u'bidBook_volume1', u'askBook_price1', u'askBook_volume1']
  6. # opt_mkt = DataAPI.MktOptdGet(tradeDate=date_str, field=fields_mkt, pandas="1")
  7. opt_mkt = DataAPI.MktOptionTickRTSnapshotGet(optionId=u"", field='', pandas="1")
  8. opt_mkt = opt_mkt[opt_mkt.dataDate == date.toISO()]
  9. opt_mkt['optID'] = map(int, opt_mkt['optionId'])
  10. opt_mkt = opt_mkt.set_index(u"optID")
  11. opt_mkt[u"price"] = (opt_mkt['bidBook_price1'] + opt_mkt['askBook_price1'])/2.0
  12. # concat某一日行情和期权基本信息,得到所需数据
  13. opt = concat([opt_info, opt_mkt], axis=1, join='inner').sort_index()
  14. #opt = opt[opt.varSecID==var_sec]
  15. exp_dates = map(Date.parseISO, np.sort(opt.expDate.unique()))
  16. trade_date = date
  17. exp_periods = {}
  18. for epd in exp_dates:
  19. exp_periods[epd] = (epd - date)*1.0/365.0
  20. risk_free = periodsSplineRiskFreeInterestRate(trade_date, exp_periods)
  21. sigma_square = {}
  22. for date in exp_dates:
  23. # 计算某一日的vix
  24. opt_date = opt[opt.expDate==date.toISO()]
  25. rf = risk_free[date]
  26. #rf = 0.05
  27. opt_call = opt_date[opt_date.contractType == 'CO'].set_index('strikePrice')
  28. opt_put = opt_date[opt_date.contractType == 'PO'].set_index('strikePrice')
  29. opt_call_price = opt_call[[u'price']].sort_index()
  30. opt_put_price = opt_put[[u'price']].sort_index()
  31. opt_call_price.columns = [u'callPrice']
  32. opt_put_price.columns = [u'putPrice']
  33. opt_call_put_price = concat([opt_call_price, opt_put_price], axis=1, join='inner').sort_index()
  34. opt_call_put_price['diffCallPut'] = opt_call_put_price.callPrice - opt_call_put_price.putPrice
  35. strike = abs(opt_call_put_price['diffCallPut']).idxmin()
  36. price_diff = opt_call_put_price['diffCallPut'][strike]
  37. ttm = exp_periods[date]
  38. fw = strike + np.exp(ttm*rf) * price_diff
  39. strikes = np.sort(opt_call_put_price.index.values)
  40. delta_K_tmp = np.concatenate((strikes, strikes[-1:], strikes[-1:]))
  41. delta_K_tmp = delta_K_tmp - np.concatenate((strikes[0:1], strikes[0:1], strikes))
  42. delta_K = np.concatenate((delta_K_tmp[1:2], delta_K_tmp[2:-2]/2, delta_K_tmp[-2:-1]))
  43. delta_K = pd.DataFrame(delta_K, index=strikes, columns=['deltaStrike'])
  44. # opt_otm = opt_out_of_money
  45. opt_otm = concat([opt_call[opt_call.index>fw], opt_put[opt_put.index<fw]], axis=0, join='inner')
  46. opt_otm = concat([opt_otm, delta_K], axis=1, join='inner').sort_index()
  47. # 计算VIX时,比forward price低的第一个行权价被设置为参考行权价,参考值以上
  48. # 的call和以下的put均为虚值期权,所有的虚值期权被用来计算VIX,然而计算中发
  49. # 现,有时候没有比forward price更低的行权价,例如2015-07-08,故有以下关于
  50. # 参考行权价的设置
  51. strike_ref = fw
  52. if len((strikes[strikes < fw])) > 0:
  53. strike_ref = max([k for k in strikes[strikes < fw]])
  54. opt_otm['price'][strike_ref] = (opt_call['price'][strike_ref] + opt_call['price'][strike_ref])/2.0
  55. exp_rt = np.exp(rf*ttm)
  56. opt_otm['sigmaTerm'] = opt_otm.deltaStrike*opt_otm.price/(opt_otm.index)**2
  57. sigma = opt_otm.sigmaTerm.sum()
  58. sigma = (sigma*2.0*exp_rt - (fw*1.0/strike_ref - 1.0)**2)/ttm
  59. sigma_square[date] = sigma
  60. # d_one, d_two 将被用来计算VIX(30):
  61. if exp_periods[exp_dates[0]] >= 1.0/365.0:
  62. d_one = exp_dates[0]
  63. d_two = exp_dates[1]
  64. else:
  65. d_one = exp_dates[1]
  66. d_two = exp_dates[2]
  67. w = (exp_periods[d_two] - 30.0/365.0)/(exp_periods[d_two] - exp_periods[d_one])
  68. vix30 = exp_periods[d_one]*w*sigma_square[d_one] + exp_periods[d_two]*(1 - w)*sigma_square[d_two]
  69. vix30 = 100*np.sqrt(vix30*365.0/30.0)
  70. # d_one, d_two 将被用来计算VIX(60):
  71. d_one = exp_dates[1]
  72. d_two = exp_dates[2]
  73. w = (exp_periods[d_two] - 60.0/365.0)/(exp_periods[d_two] - exp_periods[d_one])
  74. vix60 = exp_periods[d_one]*w*sigma_square[d_one] + exp_periods[d_two]*(1 - w)*sigma_square[d_two]
  75. vix60 = 100*np.sqrt(vix60*365.0/60.0)
  76. return vix30, vix60
  77. def getTodaySnapshotVIX():
  78. # 计算历史某天的VIX指数并返回
  79. optionVarSecID = u"510050.XSHG"
  80. date = Date.todaysDate()
  81. # 使用DataAPI.OptGet,一次拿取所有存在过的期权信息,以备后用
  82. fields_info = ["optID", u"varSecID", u'contractType', u'strikePrice', u'expDate']
  83. opt_info = DataAPI.OptGet(optID='', contractStatus=[u"DE", u"L"], field=fields_info, pandas="1")
  84. opt_info = opt_info.set_index(u"optID")
  85. cal = Calendar('China.SSE')
  86. cal.addHoliday(Date(2015,9,3))
  87. cal.addHoliday(Date(2015,9,4))
  88. if cal.isBizDay(date):
  89. now_long = datetime.now()
  90. now = now_long.time().isoformat()
  91. if (now > '09:25:00' and now < '11:30:00') or (now > '13:00:00' and now < '15:00:00'):
  92. vix30, vix60 = calSnapshotVIX(date, opt_info)
  93. vix = pd.DataFrame([[date, vix30, vix60]], index=[now_long], columns=['dataDate', 'VIX30', 'VIX60'])
  94. vix.index.name = 'time'
  95. else:
  96. vix = pd.DataFrame(0.0, index=[], columns=['dataDate', 'VIX30', 'VIX60'])
  97. vix.index.name = 'time'
  98. return vix
  99. else:
  100. print "今天: ", date, " 不是工作日"

计算即时的VIX

如果在工作日非交易时间运行计算函数,则得到一个空的dataframe

  1. getTodaySnapshotVIX()
dataDateVIX30VIX60
time

跟踪计算当日日内 VIX 走势

  1. ## 此函数跟踪计算并记录当日日内VIX走势,数据记录在:
  2. # 文件 'VIX_intraday_' + Date.todaysDate().toISO() + '.csv' 中
  3. # 该文件保存在登录uqer账号的 Data 空间中
  4. # seconds 为跟踪计算间隔秒数
  5. def trackTodayIntradayVIX(seconds):
  6. vix_file_str = 'VIX_intraday_' + Date.todaysDate().toISO() + '.csv'
  7. vix = pd.DataFrame(0.0, index=[], columns=['dataDate', 'VIX30', 'VIX60'])
  8. vix.index.name = 'time'
  9. vix.to_csv(vix_file_str)
  10. now = datetime.now().time()
  11. while now.isoformat() < '15:00:00':
  12. vix = pd.read_csv(vix_file_str).set_index('time')
  13. vix_now = getTodaySnapshotVIX()
  14. if vix_now.shape[0] > 0:
  15. vix = vix.append(vix_now)
  16. vix.to_csv(vix_file_str)
  17. # print vix_now.index[0], '\t', vix_now.VIX30[0], '\t', vix_now.VIX60[0]
  18. time.sleep(seconds)
  19. now = datetime.now().time()

注意:

trackTodayIntradayVIX 函数一经运行,便持续到当日收盘时,除非手动终止运行

  1. # 追踪当前iVIX走势,每隔60秒计算一次即时iVIX
  2. time_interval = 60
  3. trackTodayIntradayVIX(time_interval)
  4. ---------------------------------------------------------------------------
  5. KeyboardInterrupt Traceback (most recent call last)
  6. <mercury-input-20-3f8b5a5070f8> in <module>()
  7. 1 # 追踪当前iVIX走势,每隔60秒计算一次即时iVIX
  8. 2 time_interval = 60
  9. ----> 3 trackTodayIntradayVIX(time_interval)
  10. <mercury-input-19-d53f12cb0e4a> in trackTodayIntradayVIX(seconds)
  11. 17 vix.to_csv(vix_file_str)
  12. 18 # print vix_now.index[0], '\t', vix_now.VIX30[0], '\t', vix_now.VIX60[0]
  13. ---> 19 time.sleep(seconds)
  14. 20 now = datetime.now().time()
  15. KeyboardInterrupt:

将当日追踪到的iVIX日内走势作图,注意读取数据文件名和 trackTodayIntradayVIX 函数中的存储文件名一致

  1. vix_file_str = 'VIX_intraday_2015-09-23-backup.csv'
  2. vix = pd.read_csv(vix_file_str)
  3. vix['time'] = [x[11:19] for x in vix.time]
  4. vix = vix.set_index('time')
  5. ax = vix.plot(figsize=(10,5))
  6. ax.set_xlabel('time')
  7. ax.set_ylabel('VIX(%)')
  8. ax.set_ylim(35, 39)
  9. (35, 39)

【50ETF期权】 3. 中国波指 iVIX - 图3