【50ETF期权】 期权择时指数 1.0

来源:https://uqer.io/community/share/561c883df9f06c4ca72fb5f7

本文中,我们使用期权的日行情数据,计算期权情绪指标,并用以指导实战择时

初步讨论只包括两个指标

  • 成交量(成交额) PCR:看跌看涨期权的成交量(成交额)比率
  • PCIVD:Put Call Implied Volatility Difference 看跌看涨期权隐含波动率差
  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 concat
  11. from scipy import interpolate
  12. import math

1. 看跌看涨成交量(成交额)比率 PCR

  • 计算每日看跌看涨成交量或成交额的比率,即PCR
  • 我们考虑PCR每日变化量与现货50ETF隔日收益率的关系
  • 每日PCR变化量PCRD为:当日PCR减去前一日PCR得到的值,即对PCR做差分
  1. def histVolumeOpt50ETF(beginDate, endDate):
  2. ## 计算历史一段时间内的50ETF期权持仓量交易量数据
  3. optionVarSecID = u"510050.XSHG"
  4. cal = Calendar('China.SSE')
  5. dates = cal.bizDatesList(beginDate, endDate)
  6. dates = map(Date.toDateTime, dates)
  7. columns = ['callVol', 'putVol', 'callValue',
  8. 'putValue', 'callOpenInt', 'putOpenInt',
  9. 'nearCallVol', 'nearPutVol', 'nearCallValue',
  10. 'nearPutValue', 'nearCallOpenInt', 'nearPutOpenInt',
  11. 'netVol', 'netValue', 'netOpenInt',
  12. 'volPCR', 'valuePCR', 'openIntPCR',
  13. 'nearVolPCR', 'nearValuePCR', 'nearOpenIntPCR']
  14. hist_opt = pd.DataFrame(0.0, index=dates, columns=columns)
  15. hist_opt.index.name = 'date'
  16. # 每一个交易日数据单独计算
  17. for date in hist_opt.index:
  18. date_str = Date.fromDateTime(date).toISO().replace('-', '')
  19. try:
  20. opt_data = DataAPI.MktOptdGet(secID=u"", tradeDate=date_str, field=u"", pandas="1")
  21. except:
  22. hist_opt = hist_opt.drop(date)
  23. continue
  24. opt_type = []
  25. exp_date = []
  26. for ticker in opt_data.secID.values:
  27. opt_type.append(ticker[6])
  28. exp_date.append(ticker[7:11])
  29. opt_data['optType'] = opt_type
  30. opt_data['expDate'] = exp_date
  31. near_exp = np.sort(opt_data.expDate.unique())[0]
  32. data = opt_data.groupby('optType')
  33. # 计算所有上市期权:看涨看跌交易量、看涨看跌交易额、看涨看跌持仓量
  34. hist_opt['callVol'][date] = data.turnoverVol.sum()['C']
  35. hist_opt['putVol'][date] = data.turnoverVol.sum()['P']
  36. hist_opt['callValue'][date] = data.turnoverValue.sum()['C']
  37. hist_opt['putValue'][date] = data.turnoverValue.sum()['P']
  38. hist_opt['callOpenInt'][date] = data.openInt.sum()['C']
  39. hist_opt['putOpenInt'][date] = data.openInt.sum()['P']
  40. near_data = opt_data[opt_data.expDate == near_exp]
  41. near_data = near_data.groupby('optType')
  42. # 计算近月期权(主力合约): 看涨看跌交易量、看涨看跌交易额、看涨看跌持仓量
  43. hist_opt['nearCallVol'][date] = near_data.turnoverVol.sum()['C']
  44. hist_opt['nearPutVol'][date] = near_data.turnoverVol.sum()['P']
  45. hist_opt['nearCallValue'][date] = near_data.turnoverValue.sum()['C']
  46. hist_opt['nearPutValue'][date] = near_data.turnoverValue.sum()['P']
  47. hist_opt['nearCallOpenInt'][date] = near_data.openInt.sum()['C']
  48. hist_opt['nearPutOpenInt'][date] = near_data.openInt.sum()['P']
  49. # 计算所有上市期权: 总交易量、总交易额、总持仓量
  50. hist_opt['netVol'][date] = hist_opt['callVol'][date] + hist_opt['putVol'][date]
  51. hist_opt['netValue'][date] = hist_opt['callValue'][date] + hist_opt['putValue'][date]
  52. hist_opt['netOpenInt'][date] = hist_opt['callOpenInt'][date] + hist_opt['putOpenInt'][date]
  53. # 计算期权看跌看涨期权交易量(持仓量)的比率:
  54. # 交易量看跌看涨比率,交易额看跌看涨比率, 持仓量看跌看涨比率
  55. # 近月期权交易量看跌看涨比率,近月期权交易额看跌看涨比率, 近月期权持仓量看跌看涨比率
  56. # PCR = Put Call Ratio
  57. hist_opt['volPCR'][date] = round(hist_opt['putVol'][date]*1.0/hist_opt['callVol'][date], 4)
  58. hist_opt['valuePCR'][date] = round(hist_opt['putValue'][date]*1.0/hist_opt['callValue'][date], 4)
  59. hist_opt['openIntPCR'][date] = round(hist_opt['putOpenInt'][date]*1.0/hist_opt['callOpenInt'][date], 4)
  60. hist_opt['nearVolPCR'][date] = round(hist_opt['nearPutVol'][date]*1.0/hist_opt['nearCallVol'][date], 4)
  61. hist_opt['nearValuePCR'][date] = round(hist_opt['nearPutValue'][date]*1.0/hist_opt['nearCallValue'][date], 4)
  62. hist_opt['nearOpenIntPCR'][date] = round(hist_opt['nearPutOpenInt'][date]*1.0/hist_opt['nearCallOpenInt'][date], 4)
  63. return hist_opt
  64. def histPrice50ETF(beginDate, endDate):
  65. # 华夏上证50ETF收盘价数据
  66. secID = '510050.XSHG'
  67. begin = Date.fromDateTime(beginDate).toISO().replace('-', '')
  68. end = Date.fromDateTime(endDate).toISO().replace('-', '')
  69. fields = ['tradeDate', 'closePrice', 'preClosePrice']
  70. etf = DataAPI.MktFunddGet(secID, beginDate=begin, endDate=end, field=fields)
  71. etf['tradeDate'] = pd.to_datetime(etf['tradeDate'])
  72. etf['dailyReturn'] = etf['closePrice'] / etf['preClosePrice'] - 1.0
  73. etf = etf.set_index('tradeDate')
  74. return etf
  75. def histPCR50ETF(beginDate, endDate):
  76. # PCRD: Put Call Ratio Diff
  77. # 计算每日PCR变化量:当日PCR减去前一日PCR得到的值,即对PCR做差分
  78. # 专注于某一项PCR,例如:成交额PCR --- valuePCR
  79. pcr_names = ['volPCR', 'valuePCR', 'openIntPCR',
  80. 'nearVolPCR', 'nearValuePCR', 'nearOpenIntPCR']
  81. pcr_diff_names = [pcr + 'Diff' for pcr in pcr_names]
  82. pcr = histVolumeOpt50ETF(beginDate, endDate)
  83. for pcr_name in pcr_names:
  84. pcr[pcr_name + 'Diff'] = pcr[pcr_name].diff()
  85. return pcr[pcr_names + pcr_diff_names]

计算PCR

  • 期权自15年2月9号上市
  • 此处计算得到的数据可以用在后面几条策略中
  1. ## PCRD计算示例
  2. start = datetime(2015,2, 9) # 回测起始时间
  3. end = datetime(2015, 10, 13) # 回测结束时间
  4. hist_pcrd = histPCR50ETF(start, end) # 计算PCRD
  5. hist_pcrd.tail()
volPCRvaluePCRopenIntPCRnearVolPCRnearValuePCRnearOpenIntPCRvolPCRDiffvaluePCRDiffopenIntPCRDiffnearVolPCRDiffnearValuePCRDiffnearOpenIntPCRDiff
date
2015-09-291.08631.58600.66801.23721.65520.76320.02550.4779-0.00580.08010.6352-0.0193
2015-09-300.96641.13660.67091.11531.14600.7579-0.1199-0.44940.0029-0.1219-0.5092-0.0053
2015-10-080.89970.59400.67260.92440.46460.7480-0.0667-0.54260.0017-0.1909-0.6814-0.0099
2015-10-091.09790.77080.70681.15420.66720.81210.19820.17680.03420.22980.20260.0641
2015-10-120.64940.24320.77130.66040.20021.0197-0.4485-0.52760.0645-0.4938-0.46700.2076

1.1 使用基于成交量 PCR 日变化量的择时策略

策略思路:考虑成交量 PCR 日变化量 PCRD(volume)

  • 前一日PCRD(volume)小于0,则今天全仓50ETF
  • 否则,清仓观望
  • 简单来说,就是PCR上升,空仓;PCR下降,买入
  1. start = datetime(2015, 2, 9) # 回测起始时间
  2. end = datetime(2015, 10, 7) # 回测结束时间
  3. benchmark = '510050.XSHG' # 策略参考标准
  4. universe = ['510050.XSHG'] # 股票池
  5. capital_base = 100000 # 起始资金
  6. commission = Commission(0.0,0.0)
  7. refresh_rate = 1
  8. # hist_pcrd = histPCR50ETF(start, end) # 计算PCRD
  9. def initialize(account): # 初始化虚拟账户状态
  10. account.fund = universe[0]
  11. def handle_data(account): # 每个交易日的买入卖出指令
  12. fund = account.fund
  13. # 获取回测当日的前一天日期
  14. dt = Date.fromDateTime(account.current_date)
  15. cal = Calendar('China.IB')
  16. last_day = cal.advanceDate(dt,'-1B',BizDayConvention.Preceding) #计算出倒数第一个交易日
  17. last_day_str = last_day.strftime("%Y-%m-%d")
  18. # 计算买入卖出信号
  19. try:
  20. # 拿取PCRD数据
  21. pcrd_last_vol = hist_pcrd.volPCRDiff.loc[last_day_str] # PCRD(volumn)
  22. long_flag = True if pcrd_last_vol < 0 else False # 调仓条件
  23. except:
  24. long_flag = False
  25. if long_flag:
  26. # 买入时,全仓杀入
  27. try:
  28. approximationAmount = int(account.cash / account.referencePrice[fund] / 100.0) * 100
  29. order(fund, approximationAmount)
  30. except:
  31. return
  32. else:
  33. # 卖出时,全仓清空
  34. order_to(fund, 0)

【50ETF期权】 期权择时指数 1.0 - 图1

1.2 使用基于成交额 PCR 日变化量的择时策略

策略思路:考虑成交额 PCR 日变化量 PCRD(value)

  • 前一日PCRD(value)小于0,则今天全仓50ETF
  • 否则,清仓观望
  • 简单来说,就是PCR上升,空仓;PCR下降,买入
  1. start = datetime(2015, 2, 9) # 回测起始时间
  2. end = datetime(2015, 10, 7) # 回测结束时间
  3. benchmark = '510050.XSHG' # 策略参考标准
  4. universe = ['510050.XSHG'] # 股票池
  5. capital_base = 100000 # 起始资金
  6. commission = Commission(0.0,0.0)
  7. refresh_rate = 1
  8. # hist_pcrd = histPCR50ETF(start, end) # 计算PCRD
  9. def initialize(account): # 初始化虚拟账户状态
  10. account.fund = universe[0]
  11. def handle_data(account): # 每个交易日的买入卖出指令
  12. fund = account.fund
  13. # 获取回测当日的前一天日期
  14. dt = Date.fromDateTime(account.current_date)
  15. cal = Calendar('China.IB')
  16. last_day = cal.advanceDate(dt,'-1B',BizDayConvention.Preceding) #计算出倒数第一个交易日
  17. last_day_str = last_day.strftime("%Y-%m-%d")
  18. # 计算买入卖出信号
  19. try:
  20. # 拿取PCRD数据
  21. pcrd_last_value = hist_pcrd.valuePCRDiff.loc[last_day_str] # PCRD(value)
  22. long_flag = True if pcrd_last_value < 0 else False # 调仓条件
  23. except:
  24. long_flag = False
  25. if long_flag:
  26. # 买入时,全仓杀入
  27. try:
  28. approximationAmount = int(account.cash / account.referencePrice[fund] / 100.0) * 100
  29. order(fund, approximationAmount)
  30. except:
  31. return
  32. else:
  33. # 卖出时,全仓清空
  34. order_to(fund, 0)

【50ETF期权】 期权择时指数 1.0 - 图2

1.3 结合使用成交量、成交额 PCR 日变化量的择时策略

策略思路:考虑成交量PCRD(volume) 和成交额PCRD(value)

  • 前一日PCRD(volume)和PCRD(value)同时小于0,则今天全仓50ETF
  • 否则,清仓观望
  1. start = datetime(2015, 2, 9) # 回测起始时间
  2. end = datetime(2015, 10, 7) # 回测结束时间
  3. benchmark = '510050.XSHG' # 策略参考标准
  4. universe = ['510050.XSHG'] # 股票池
  5. capital_base = 100000 # 起始资金
  6. commission = Commission(0.0,0.0)
  7. refresh_rate = 1
  8. hist_pcrd = histPCR50ETF(start, end) # 计算PCRD
  9. def initialize(account): # 初始化虚拟账户状态
  10. account.fund = universe[0]
  11. def handle_data(account): # 每个交易日的买入卖出指令
  12. fund = account.fund
  13. # 获取回测当日的前一天日期
  14. dt = Date.fromDateTime(account.current_date)
  15. cal = Calendar('China.IB')
  16. last_day = cal.advanceDate(dt,'-1B',BizDayConvention.Preceding) #计算出倒数第一个交易日
  17. last_day_str = last_day.strftime("%Y-%m-%d")
  18. # 计算买入卖出信号
  19. try:
  20. # 拿取PCRD数据
  21. pcrd_last_value = hist_pcrd.valuePCRDiff.loc[last_day_str] # PCRD(value)
  22. pcrd_last_vol = hist_pcrd.volPCRDiff.loc[last_day_str] # PCRD(volumn)
  23. long_flag = True if pcrd_last_value < 0.0 and pcrd_last_vol < 0.0 else False # 调仓条件
  24. except:
  25. long_flag = False
  26. if long_flag:
  27. # 买入时,全仓杀入
  28. try:
  29. approximationAmount = int(account.cash / account.referencePrice[fund] / 100.0) * 100
  30. order(fund, approximationAmount)
  31. except:
  32. return
  33. else:
  34. # 卖出时,全仓清空
  35. order_to(fund, 0)

【50ETF期权】 期权择时指数 1.0 - 图3

2. 看跌看涨隐含波动率价差 PCIVD

  • 相同到期日、行权价的看跌看涨期权,其隐含波动率会有差异
  • 由于套保需要,一般看跌期权隐含波动率高于看涨期权
  • 看跌、看涨期权隐含波动率之差 PCIVD 的每日变化可以用来指导实际操作
  • 在计算中,我们使用平值附近的期权计算 PCIVD
  1. ## 银行间质押式回购利率
  2. def histDayInterestRateInterbankRepo(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 histDaySHIBOR(date):
  21. cal = Calendar('China.SSE')
  22. period = Period('-10B')
  23. begin = cal.advanceDate(date, period)
  24. begin_str = begin.toISO().replace('-', '')
  25. date_str = date.toISO().replace('-', '')
  26. # 以下的indicID分别对应的SHIBOR周期为:
  27. # 1D, 7D, 14D, 1M, 3M, 6M, 9M, 1Y
  28. indicID = [u"M120000057", u"M120000058", u"M120000059", u"M120000060",
  29. u"M120000061", u"M120000062", u"M120000063", u"M120000064"]
  30. period = np.asarray([1.0, 7.0, 14.0, 30.0, 90.0, 180.0, 270.0, 360.0]) / 360.0
  31. period_matrix = pd.DataFrame(index=indicID, data=period, columns=['period'])
  32. field = u"indicID,indicName,publishTime,periodDate,dataValue,unit"
  33. interest_shibor = DataAPI.ChinaDataInterestRateSHIBORGet(indicID=indicID,beginDate=begin_str,endDate=date_str,field=field,pandas="1")
  34. interest_shibor = interest_shibor.groupby('indicID').first()
  35. interest_shibor = concat([interest_shibor, period_matrix], axis=1, join='inner').sort_index()
  36. return interest_shibor
  37. ## 插值得到给定的周期的无风险利率
  38. def periodsSplineRiskFreeInterestRate(date, periods):
  39. # 此处使用SHIBOR来插值
  40. init_shibor = histDaySHIBOR(date)
  41. shibor = {}
  42. min_period = min(init_shibor.period.values)
  43. min_period = 25.0/360.0
  44. max_period = max(init_shibor.period.values)
  45. for p in periods.keys():
  46. tmp = periods[p]
  47. if periods[p] > max_period:
  48. tmp = max_period * 0.99999
  49. elif periods[p] < min_period:
  50. tmp = min_period * 1.00001
  51. sh = interpolate.spline(init_shibor.period.values, init_shibor.dataValue.values, [tmp], order=3)
  52. shibor[p] = sh[0]/100.0
  53. return shibor
  54. ## 使用DataAPI.OptGet, DataAPI.MktOptdGet拿到计算所需数据
  55. def histDayDataOpt50ETF(date):
  56. date_str = date.toISO().replace('-', '')
  57. #使用DataAPI.OptGet,拿到已退市和上市的所有期权的基本信息
  58. info_fields = [u'optID', u'varSecID', u'varShortName', u'varTicker', u'varExchangeCD', u'varType',
  59. u'contractType', u'strikePrice', u'contMultNum', u'contractStatus', u'listDate',
  60. u'expYear', u'expMonth', u'expDate', u'lastTradeDate', u'exerDate', u'deliDate',
  61. u'delistDate']
  62. opt_info = DataAPI.OptGet(optID='', contractStatus=[u"DE",u"L"], field=info_fields, pandas="1")
  63. #使用DataAPI.MktOptdGet,拿到历史上某一天的期权成交信息
  64. mkt_fields = [u'ticker', u'optID', u'secShortName', u'exchangeCD', u'tradeDate', u'preSettlePrice',
  65. u'preClosePrice', u'openPrice', u'highestPrice', u'lowestPrice', u'closePrice',
  66. u'settlPrice', u'turnoverVol', u'turnoverValue', u'openInt']
  67. opt_mkt = DataAPI.MktOptdGet(tradeDate=date_str, field=mkt_fields, pandas = "1")
  68. opt_info = opt_info.set_index(u"optID")
  69. opt_mkt = opt_mkt.set_index(u"optID")
  70. opt = concat([opt_info, opt_mkt], axis=1, join='inner').sort_index()
  71. return opt
  72. # 旧版forward计算稍有差别
  73. def histDayMktForwardPriceOpt50ETF(opt, risk_free):
  74. exp_dates_str = np.sort(opt.expDate.unique())
  75. trade_date = Date.parseISO(opt.tradeDate.values[0])
  76. forward = {}
  77. for date_str in exp_dates_str:
  78. opt_date = opt[opt.expDate == date_str]
  79. opt_call_date = opt_date[opt_date.contractType == 'CO']
  80. opt_put_date = opt_date[opt_date.contractType == 'PO']
  81. opt_call_date = opt_call_date[[u'strikePrice', u'price']].set_index('strikePrice').sort_index()
  82. opt_put_date = opt_put_date[[u'strikePrice', u'price']].set_index('strikePrice').sort_index()
  83. opt_call_date.columns = [u'callPrice']
  84. opt_put_date.columns = [u'putPrice']
  85. opt_date = concat([opt_call_date, opt_put_date], axis=1, join='inner').sort_index()
  86. opt_date['diffCallPut'] = opt_date.callPrice - opt_date.putPrice
  87. strike = abs(opt_date['diffCallPut']).idxmin()
  88. priceDiff = opt_date['diffCallPut'][strike]
  89. date = Date.parseISO(date_str)
  90. ttm = abs(float(date - trade_date + 1.0)/365.0)
  91. rf = risk_free[date]
  92. fw = strike + np.exp(ttm*rf) * priceDiff
  93. forward[date] = fw
  94. return forward
  95. ## 分析历史某一日的期权收盘价信息,得到隐含波动率微笑和期权风险指标
  96. def histDayAnalysisOpt50ETF(date):
  97. opt_var_sec = u"510050.XSHG" # 期权标的
  98. opt = histDayDataOpt50ETF(date)
  99. #使用DataAPI.MktFunddGet拿到期权标的的日行情
  100. date_str = date.toISO().replace('-', '')
  101. opt_var_mkt = DataAPI.MktFunddGet(secID=opt_var_sec,tradeDate=date_str,beginDate=u"",endDate=u"",field=u"",pandas="1")
  102. #opt_var_mkt = DataAPI.MktFunddAdjGet(secID=opt_var_sec,beginDate=date_str,endDate=date_str,field=u"",pandas="1")
  103. # 计算shibor
  104. exp_dates_str = opt.expDate.unique()
  105. periods = {}
  106. for date_str in exp_dates_str:
  107. exp_date = Date.parseISO(date_str)
  108. periods[exp_date] = (exp_date - date)/360.0
  109. shibor = periodsSplineRiskFreeInterestRate(date, periods)
  110. # 计算forward price
  111. opt_tmp = opt[[u'contractType', u'tradeDate', u'strikePrice', u'expDate', u'settlPrice']]
  112. opt_tmp.columns = [[u'contractType', u'tradeDate', u'strikePrice', u'expDate', u'price']]
  113. forward_price = histDayMktForwardPriceOpt50ETF(opt_tmp, shibor)
  114. settle = opt.settlPrice.values # 期权 settle price
  115. close = opt.closePrice.values # 期权 close price
  116. strike = opt.strikePrice.values # 期权 strike price
  117. option_type = opt.contractType.values # 期权类型
  118. exp_date_str = opt.expDate.values # 期权行权日期
  119. eval_date_str = opt.tradeDate.values # 期权交易日期
  120. mat_dates = []
  121. eval_dates = []
  122. spot = []
  123. for epd, evd in zip(exp_date_str, eval_date_str):
  124. mat_dates.append(Date.parseISO(epd))
  125. eval_dates.append(Date.parseISO(evd))
  126. spot.append(opt_var_mkt.closePrice[0])
  127. time_to_maturity = [float(mat - eva + 1.0)/365.0 for (mat, eva) in zip(mat_dates, eval_dates)]
  128. risk_free = [] # 无风险利率
  129. forward = [] # 市场远期
  130. for s, mat, time in zip(spot, mat_dates, time_to_maturity):
  131. #rf = math.log(forward_price[mat] / s) / time
  132. rf = shibor[mat]
  133. risk_free.append(rf)
  134. forward.append(forward_price[mat])
  135. opt_types = [] # 期权类型
  136. for t in option_type:
  137. if t == 'CO':
  138. opt_types.append(1)
  139. else:
  140. opt_types.append(-1)
  141. # 使用通联CAL包中 BSMImpliedVolatity 计算隐含波动率
  142. calculated_vol = BSMImpliedVolatity(opt_types, strike, spot, risk_free, 0.0, time_to_maturity, settle)
  143. calculated_vol = calculated_vol.fillna(0.0)
  144. # 使用通联CAL包中 BSMPrice 计算期权风险指标
  145. greeks = BSMPrice(opt_types, strike, spot, risk_free, 0.0, calculated_vol.vol.values, time_to_maturity)
  146. # vega、rho、theta 的计量单位参照上交所的数据,以求统一对比
  147. greeks.vega = greeks.vega #/ 100.0
  148. greeks.rho = greeks.rho #/ 100.0
  149. greeks.theta = greeks.theta #* 365.0 / 252.0 #/ 365.0
  150. opt['strike'] = strike
  151. opt['forward'] = np.around(forward, decimals=3)
  152. opt['optType'] = option_type
  153. opt['expDate'] = exp_date_str
  154. opt['spotPrice'] = spot
  155. opt['riskFree'] = risk_free
  156. opt['timeToMaturity'] = np.around(time_to_maturity, decimals=4)
  157. opt['settle'] = np.around(greeks.price.values.astype(np.double), decimals=4)
  158. opt['iv'] = np.around(calculated_vol.vol.values.astype(np.double), decimals=4)
  159. opt['delta'] = np.around(greeks.delta.values.astype(np.double), decimals=4)
  160. opt['vega'] = np.around(greeks.vega.values.astype(np.double), decimals=4)
  161. opt['gamma'] = np.around(greeks.gamma.values.astype(np.double), decimals=4)
  162. opt['theta'] = np.around(greeks.theta.values.astype(np.double), decimals=4)
  163. opt['rho'] = np.around(greeks.rho.values.astype(np.double), decimals=4)
  164. fields = [u'ticker', u'contractType', u'strikePrice', 'forward', u'expDate', u'tradeDate',
  165. u'closePrice', u'settlPrice', 'spotPrice', u'iv',
  166. u'delta', u'vega', u'gamma', u'theta', u'rho']
  167. opt = opt[fields].reset_index().set_index('ticker').sort_index()
  168. #opt['iv'] = opt.iv.replace(to_replace=0.0, value=np.nan)
  169. return opt
  170. # 每日期权分析数据整理
  171. def histDayGreeksIVOpt50ETF(date):
  172. # Uqer 计算期权的风险数据
  173. opt = histDayAnalysisOpt50ETF(date)
  174. # 整理数据部分
  175. opt.index = [index[-10:] for index in opt.index]
  176. opt = opt[['contractType','strikePrice','spotPrice','forward','expDate','closePrice','iv','delta','theta','gamma','vega','rho']]
  177. opt.columns = [['contractType','strike','spot','forward','expDate','close','iv','delta','theta','gamma','vega','rho']]
  178. opt_call = opt[opt.contractType=='CO']
  179. opt_put = opt[opt.contractType=='PO']
  180. opt_call.columns = pd.MultiIndex.from_tuples([('Call', c) for c in opt_call.columns])
  181. opt_call[('Call-Put', 'strike')] = opt_call[('Call', 'strike')]
  182. opt_call[('Call-Put', 'spot')] = opt_call[('Call', 'spot')]
  183. opt_call[('Call-Put', 'forward')] = opt_call[('Call', 'forward')]
  184. opt_put.columns = pd.MultiIndex.from_tuples([('Put', c) for c in opt_put.columns])
  185. opt = concat([opt_call, opt_put], axis=1, join='inner').sort_index()
  186. opt = opt.set_index(('Call','expDate')).sort_index()
  187. opt = opt.drop([('Call','contractType'), ('Call','strike'), ('Call','forward'), ('Call','spot')], axis=1)
  188. opt = opt.drop([('Put','expDate'), ('Put','contractType'), ('Put','strike'), ('Put','forward'), ('Put','spot')], axis=1)
  189. opt.index.name = 'expDate'
  190. ## 以上得到完整的历史某日数据,格式简洁明了
  191. return opt
  192. # 做图展示某一天的隐含波动率微笑
  193. def histDayPlotSmileVolatilityOpt50ETF(date):
  194. cal = Calendar('China.SSE')
  195. if not cal.isBizDay(date):
  196. print date, ' is not a trading day!'
  197. return
  198. # Uqer 计算期权的风险数据
  199. opt = histDayGreeksIVOpt50ETF(date)
  200. spot = opt[('Call-Put', 'spot')].values[0]
  201. # 下面展示波动率微笑
  202. exp_dates = np.sort(opt.index.unique())
  203. ## ----------------------------------------------
  204. fig = plt.figure(figsize=(10,8))
  205. fig.set_tight_layout(True)
  206. for i in range(exp_dates.shape[0]):
  207. date = exp_dates[i]
  208. ax = fig.add_subplot(2,2,i+1)
  209. opt_date = opt[opt.index==date].set_index(('Call-Put', 'strike'))
  210. opt_date.index.name = 'strike'
  211. ax.plot(opt_date.index, opt_date[('Call', 'iv')], '-o')
  212. ax.plot(opt_date.index, opt_date[('Put', 'iv')], '-s')
  213. (y_min, y_max) = ax.get_ylim()
  214. ax.plot([spot, spot], [y_min, y_max], '--')
  215. ax.set_ylim(y_min, y_max)
  216. ax.legend(['call', 'put'], loc=0)
  217. ax.grid()
  218. ax.set_xlabel(u"strike")
  219. ax.set_ylabel(r"Implied Volatility")
  220. plt.title(exp_dates[i])