<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # 【50ETF期權】 期權擇時指數 1.0 > 來源:https://uqer.io/community/share/561c883df9f06c4ca72fb5f7 本文中,我們使用期權的日行情數據,計算期權情緒指標,并用以指導實戰擇時 初步討論只包括兩個指標 + 成交量(成交額) PCR:看跌看漲期權的成交量(成交額)比率 + PCIVD:Put Call Implied Volatility Difference 看跌看漲期權隱含波動率差 ```py from CAL.PyCAL import * import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib import rc rc('mathtext', default='regular') import seaborn as sns sns.set_style('white') from matplotlib import dates from pandas import concat from scipy import interpolate import math ``` ## 1. 看跌看漲成交量(成交額)比率 PCR + 計算每日看跌看漲成交量或成交額的比率,即PCR + 我們考慮PCR每日變化量與現貨50ETF隔日收益率的關系 + 每日PCR變化量PCRD為:當日PCR減去前一日PCR得到的值,即對PCR做差分 ```py def histVolumeOpt50ETF(beginDate, endDate): ## 計算歷史一段時間內的50ETF期權持倉量交易量數據 optionVarSecID = u"510050.XSHG" cal = Calendar('China.SSE') dates = cal.bizDatesList(beginDate, endDate) dates = map(Date.toDateTime, dates) columns = ['callVol', 'putVol', 'callValue', 'putValue', 'callOpenInt', 'putOpenInt', 'nearCallVol', 'nearPutVol', 'nearCallValue', 'nearPutValue', 'nearCallOpenInt', 'nearPutOpenInt', 'netVol', 'netValue', 'netOpenInt', 'volPCR', 'valuePCR', 'openIntPCR', 'nearVolPCR', 'nearValuePCR', 'nearOpenIntPCR'] hist_opt = pd.DataFrame(0.0, index=dates, columns=columns) hist_opt.index.name = 'date' # 每一個交易日數據單獨計算 for date in hist_opt.index: date_str = Date.fromDateTime(date).toISO().replace('-', '') try: opt_data = DataAPI.MktOptdGet(secID=u"", tradeDate=date_str, field=u"", pandas="1") except: hist_opt = hist_opt.drop(date) continue opt_type = [] exp_date = [] for ticker in opt_data.secID.values: opt_type.append(ticker[6]) exp_date.append(ticker[7:11]) opt_data['optType'] = opt_type opt_data['expDate'] = exp_date near_exp = np.sort(opt_data.expDate.unique())[0] data = opt_data.groupby('optType') # 計算所有上市期權:看漲看跌交易量、看漲看跌交易額、看漲看跌持倉量 hist_opt['callVol'][date] = data.turnoverVol.sum()['C'] hist_opt['putVol'][date] = data.turnoverVol.sum()['P'] hist_opt['callValue'][date] = data.turnoverValue.sum()['C'] hist_opt['putValue'][date] = data.turnoverValue.sum()['P'] hist_opt['callOpenInt'][date] = data.openInt.sum()['C'] hist_opt['putOpenInt'][date] = data.openInt.sum()['P'] near_data = opt_data[opt_data.expDate == near_exp] near_data = near_data.groupby('optType') # 計算近月期權(主力合約): 看漲看跌交易量、看漲看跌交易額、看漲看跌持倉量 hist_opt['nearCallVol'][date] = near_data.turnoverVol.sum()['C'] hist_opt['nearPutVol'][date] = near_data.turnoverVol.sum()['P'] hist_opt['nearCallValue'][date] = near_data.turnoverValue.sum()['C'] hist_opt['nearPutValue'][date] = near_data.turnoverValue.sum()['P'] hist_opt['nearCallOpenInt'][date] = near_data.openInt.sum()['C'] hist_opt['nearPutOpenInt'][date] = near_data.openInt.sum()['P'] # 計算所有上市期權: 總交易量、總交易額、總持倉量 hist_opt['netVol'][date] = hist_opt['callVol'][date] + hist_opt['putVol'][date] hist_opt['netValue'][date] = hist_opt['callValue'][date] + hist_opt['putValue'][date] hist_opt['netOpenInt'][date] = hist_opt['callOpenInt'][date] + hist_opt['putOpenInt'][date] # 計算期權看跌看漲期權交易量(持倉量)的比率: # 交易量看跌看漲比率,交易額看跌看漲比率, 持倉量看跌看漲比率 # 近月期權交易量看跌看漲比率,近月期權交易額看跌看漲比率, 近月期權持倉量看跌看漲比率 # PCR = Put Call Ratio hist_opt['volPCR'][date] = round(hist_opt['putVol'][date]*1.0/hist_opt['callVol'][date], 4) hist_opt['valuePCR'][date] = round(hist_opt['putValue'][date]*1.0/hist_opt['callValue'][date], 4) hist_opt['openIntPCR'][date] = round(hist_opt['putOpenInt'][date]*1.0/hist_opt['callOpenInt'][date], 4) hist_opt['nearVolPCR'][date] = round(hist_opt['nearPutVol'][date]*1.0/hist_opt['nearCallVol'][date], 4) hist_opt['nearValuePCR'][date] = round(hist_opt['nearPutValue'][date]*1.0/hist_opt['nearCallValue'][date], 4) hist_opt['nearOpenIntPCR'][date] = round(hist_opt['nearPutOpenInt'][date]*1.0/hist_opt['nearCallOpenInt'][date], 4) return hist_opt def histPrice50ETF(beginDate, endDate): # 華夏上證50ETF收盤價數據 secID = '510050.XSHG' begin = Date.fromDateTime(beginDate).toISO().replace('-', '') end = Date.fromDateTime(endDate).toISO().replace('-', '') fields = ['tradeDate', 'closePrice', 'preClosePrice'] etf = DataAPI.MktFunddGet(secID, beginDate=begin, endDate=end, field=fields) etf['tradeDate'] = pd.to_datetime(etf['tradeDate']) etf['dailyReturn'] = etf['closePrice'] / etf['preClosePrice'] - 1.0 etf = etf.set_index('tradeDate') return etf def histPCR50ETF(beginDate, endDate): # PCRD: Put Call Ratio Diff # 計算每日PCR變化量:當日PCR減去前一日PCR得到的值,即對PCR做差分 # 專注于某一項PCR,例如:成交額PCR --- valuePCR pcr_names = ['volPCR', 'valuePCR', 'openIntPCR', 'nearVolPCR', 'nearValuePCR', 'nearOpenIntPCR'] pcr_diff_names = [pcr + 'Diff' for pcr in pcr_names] pcr = histVolumeOpt50ETF(beginDate, endDate) for pcr_name in pcr_names: pcr[pcr_name + 'Diff'] = pcr[pcr_name].diff() return pcr[pcr_names + pcr_diff_names] ``` 計算PCR + 期權自15年2月9號上市 + 此處計算得到的數據可以用在后面幾條策略中 ```py ## PCRD計算示例 start = datetime(2015,2, 9) # 回測起始時間 end = datetime(2015, 10, 13) # 回測結束時間 hist_pcrd = histPCR50ETF(start, end) # 計算PCRD hist_pcrd.tail() ``` | | volPCR | valuePCR | openIntPCR | nearVolPCR | nearValuePCR | nearOpenIntPCR | volPCRDiff | valuePCRDiff | openIntPCRDiff | nearVolPCRDiff | nearValuePCRDiff | nearOpenIntPCRDiff | | --- | --- | | date | | | | | | | | | | | | | | 2015-09-29 | 1.0863 | 1.5860 | 0.6680 | 1.2372 | 1.6552 | 0.7632 | 0.0255 | 0.4779 | -0.0058 | 0.0801 | 0.6352 | -0.0193 | | 2015-09-30 | 0.9664 | 1.1366 | 0.6709 | 1.1153 | 1.1460 | 0.7579 | -0.1199 | -0.4494 | 0.0029 | -0.1219 | -0.5092 | -0.0053 | | 2015-10-08 | 0.8997 | 0.5940 | 0.6726 | 0.9244 | 0.4646 | 0.7480 | -0.0667 | -0.5426 | 0.0017 | -0.1909 | -0.6814 | -0.0099 | | 2015-10-09 | 1.0979 | 0.7708 | 0.7068 | 1.1542 | 0.6672 | 0.8121 | 0.1982 | 0.1768 | 0.0342 | 0.2298 | 0.2026 | 0.0641 | | 2015-10-12 | 0.6494 | 0.2432 | 0.7713 | 0.6604 | 0.2002 | 1.0197 | -0.4485 | -0.5276 | 0.0645 | -0.4938 | -0.4670 | 0.2076 | ### 1.1 使用基于成交量 PCR 日變化量的擇時策略 策略思路:考慮成交量 PCR 日變化量 PCRD(volume) + 前一日PCRD(volume)小于0,則今天全倉50ETF + 否則,清倉觀望 + 簡單來說,就是PCR上升,空倉;PCR下降,買入 ```py start = datetime(2015, 2, 9) # 回測起始時間 end = datetime(2015, 10, 7) # 回測結束時間 benchmark = '510050.XSHG' # 策略參考標準 universe = ['510050.XSHG'] # 股票池 capital_base = 100000 # 起始資金 commission = Commission(0.0,0.0) refresh_rate = 1 # hist_pcrd = histPCR50ETF(start, end) # 計算PCRD def initialize(account): # 初始化虛擬賬戶狀態 account.fund = universe[0] def handle_data(account): # 每個交易日的買入賣出指令 fund = account.fund # 獲取回測當日的前一天日期 dt = Date.fromDateTime(account.current_date) cal = Calendar('China.IB') last_day = cal.advanceDate(dt,'-1B',BizDayConvention.Preceding) #計算出倒數第一個交易日 last_day_str = last_day.strftime("%Y-%m-%d") # 計算買入賣出信號 try: # 拿取PCRD數據 pcrd_last_vol = hist_pcrd.volPCRDiff.loc[last_day_str] # PCRD(volumn) long_flag = True if pcrd_last_vol < 0 else False # 調倉條件 except: long_flag = False if long_flag: # 買入時,全倉殺入 try: approximationAmount = int(account.cash / account.referencePrice[fund] / 100.0) * 100 order(fund, approximationAmount) except: return else: # 賣出時,全倉清空 order_to(fund, 0) ``` ![](https://box.kancloud.cn/2016-07-30_579cbdbc8457f.jpg) ### 1.2 使用基于成交額 PCR 日變化量的擇時策略 策略思路:考慮成交額 PCR 日變化量 PCRD(value) + 前一日PCRD(value)小于0,則今天全倉50ETF + 否則,清倉觀望 + 簡單來說,就是PCR上升,空倉;PCR下降,買入 ```py start = datetime(2015, 2, 9) # 回測起始時間 end = datetime(2015, 10, 7) # 回測結束時間 benchmark = '510050.XSHG' # 策略參考標準 universe = ['510050.XSHG'] # 股票池 capital_base = 100000 # 起始資金 commission = Commission(0.0,0.0) refresh_rate = 1 # hist_pcrd = histPCR50ETF(start, end) # 計算PCRD def initialize(account): # 初始化虛擬賬戶狀態 account.fund = universe[0] def handle_data(account): # 每個交易日的買入賣出指令 fund = account.fund # 獲取回測當日的前一天日期 dt = Date.fromDateTime(account.current_date) cal = Calendar('China.IB') last_day = cal.advanceDate(dt,'-1B',BizDayConvention.Preceding) #計算出倒數第一個交易日 last_day_str = last_day.strftime("%Y-%m-%d") # 計算買入賣出信號 try: # 拿取PCRD數據 pcrd_last_value = hist_pcrd.valuePCRDiff.loc[last_day_str] # PCRD(value) long_flag = True if pcrd_last_value < 0 else False # 調倉條件 except: long_flag = False if long_flag: # 買入時,全倉殺入 try: approximationAmount = int(account.cash / account.referencePrice[fund] / 100.0) * 100 order(fund, approximationAmount) except: return else: # 賣出時,全倉清空 order_to(fund, 0) ``` ![](https://box.kancloud.cn/2016-07-30_579cbdbc9cceb.jpg) ### 1.3 結合使用成交量、成交額 PCR 日變化量的擇時策略 策略思路:考慮成交量PCRD(volume) 和成交額PCRD(value) + 前一日PCRD(volume)和PCRD(value)同時小于0,則今天全倉50ETF + 否則,清倉觀望 ```py start = datetime(2015, 2, 9) # 回測起始時間 end = datetime(2015, 10, 7) # 回測結束時間 benchmark = '510050.XSHG' # 策略參考標準 universe = ['510050.XSHG'] # 股票池 capital_base = 100000 # 起始資金 commission = Commission(0.0,0.0) refresh_rate = 1 hist_pcrd = histPCR50ETF(start, end) # 計算PCRD def initialize(account): # 初始化虛擬賬戶狀態 account.fund = universe[0] def handle_data(account): # 每個交易日的買入賣出指令 fund = account.fund # 獲取回測當日的前一天日期 dt = Date.fromDateTime(account.current_date) cal = Calendar('China.IB') last_day = cal.advanceDate(dt,'-1B',BizDayConvention.Preceding) #計算出倒數第一個交易日 last_day_str = last_day.strftime("%Y-%m-%d") # 計算買入賣出信號 try: # 拿取PCRD數據 pcrd_last_value = hist_pcrd.valuePCRDiff.loc[last_day_str] # PCRD(value) pcrd_last_vol = hist_pcrd.volPCRDiff.loc[last_day_str] # PCRD(volumn) long_flag = True if pcrd_last_value < 0.0 and pcrd_last_vol < 0.0 else False # 調倉條件 except: long_flag = False if long_flag: # 買入時,全倉殺入 try: approximationAmount = int(account.cash / account.referencePrice[fund] / 100.0) * 100 order(fund, approximationAmount) except: return else: # 賣出時,全倉清空 order_to(fund, 0) ``` ![](https://box.kancloud.cn/2016-07-30_579cbdbcb34cb.jpg) ## 2. 看跌看漲隱含波動率價差 PCIVD + 相同到期日、行權價的看跌看漲期權,其隱含波動率會有差異 + 由于套保需要,一般看跌期權隱含波動率高于看漲期權 + 看跌、看漲期權隱含波動率之差 PCIVD 的每日變化可以用來指導實際操作 + 在計算中,我們使用平值附近的期權計算 PCIVD ```py ## 銀行間質押式回購利率 def histDayInterestRateInterbankRepo(date): cal = Calendar('China.SSE') period = Period('-10B') begin = cal.advanceDate(date, period) begin_str = begin.toISO().replace('-', '') date_str = date.toISO().replace('-', '') # 以下的indicID分別對應的銀行間質押式回購利率周期為: # 1D, 7D, 14D, 21D, 1M, 3M, 4M, 6M, 9M, 1Y indicID = [u"M120000067", u"M120000068", u"M120000069", u"M120000070", u"M120000071", u"M120000072", u"M120000073", u"M120000074", u"M120000075", u"M120000076"] 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 period_matrix = pd.DataFrame(index=indicID, data=period, columns=['period']) field = u"indicID,indicName,publishTime,periodDate,dataValue,unit" interbank_repo = DataAPI.ChinaDataInterestRateInterbankRepoGet(indicID=indicID,beginDate=begin_str,endDate=date_str,field=field,pandas="1") interbank_repo = interbank_repo.groupby('indicID').first() interbank_repo = concat([interbank_repo, period_matrix], axis=1, join='inner').sort_index() return interbank_repo ## 銀行間同業拆借利率 def histDaySHIBOR(date): cal = Calendar('China.SSE') period = Period('-10B') begin = cal.advanceDate(date, period) begin_str = begin.toISO().replace('-', '') date_str = date.toISO().replace('-', '') # 以下的indicID分別對應的SHIBOR周期為: # 1D, 7D, 14D, 1M, 3M, 6M, 9M, 1Y indicID = [u"M120000057", u"M120000058", u"M120000059", u"M120000060", u"M120000061", u"M120000062", u"M120000063", u"M120000064"] period = np.asarray([1.0, 7.0, 14.0, 30.0, 90.0, 180.0, 270.0, 360.0]) / 360.0 period_matrix = pd.DataFrame(index=indicID, data=period, columns=['period']) field = u"indicID,indicName,publishTime,periodDate,dataValue,unit" interest_shibor = DataAPI.ChinaDataInterestRateSHIBORGet(indicID=indicID,beginDate=begin_str,endDate=date_str,field=field,pandas="1") interest_shibor = interest_shibor.groupby('indicID').first() interest_shibor = concat([interest_shibor, period_matrix], axis=1, join='inner').sort_index() return interest_shibor ## 插值得到給定的周期的無風險利率 def periodsSplineRiskFreeInterestRate(date, periods): # 此處使用SHIBOR來插值 init_shibor = histDaySHIBOR(date) shibor = {} min_period = min(init_shibor.period.values) min_period = 25.0/360.0 max_period = max(init_shibor.period.values) for p in periods.keys(): tmp = periods[p] if periods[p] > max_period: tmp = max_period * 0.99999 elif periods[p] < min_period: tmp = min_period * 1.00001 sh = interpolate.spline(init_shibor.period.values, init_shibor.dataValue.values, [tmp], order=3) shibor[p] = sh[0]/100.0 return shibor ## 使用DataAPI.OptGet, DataAPI.MktOptdGet拿到計算所需數據 def histDayDataOpt50ETF(date): date_str = date.toISO().replace('-', '') #使用DataAPI.OptGet,拿到已退市和上市的所有期權的基本信息 info_fields = [u'optID', u'varSecID', u'varShortName', u'varTicker', u'varExchangeCD', u'varType', u'contractType', u'strikePrice', u'contMultNum', u'contractStatus', u'listDate', u'expYear', u'expMonth', u'expDate', u'lastTradeDate', u'exerDate', u'deliDate', u'delistDate'] opt_info = DataAPI.OptGet(optID='', contractStatus=[u"DE",u"L"], field=info_fields, pandas="1") #使用DataAPI.MktOptdGet,拿到歷史上某一天的期權成交信息 mkt_fields = [u'ticker', u'optID', u'secShortName', u'exchangeCD', u'tradeDate', u'preSettlePrice', u'preClosePrice', u'openPrice', u'highestPrice', u'lowestPrice', u'closePrice', u'settlPrice', u'turnoverVol', u'turnoverValue', u'openInt'] opt_mkt = DataAPI.MktOptdGet(tradeDate=date_str, field=mkt_fields, pandas = "1") opt_info = opt_info.set_index(u"optID") opt_mkt = opt_mkt.set_index(u"optID") opt = concat([opt_info, opt_mkt], axis=1, join='inner').sort_index() return opt # 舊版forward計算稍有差別 def histDayMktForwardPriceOpt50ETF(opt, risk_free): exp_dates_str = np.sort(opt.expDate.unique()) trade_date = Date.parseISO(opt.tradeDate.values[0]) forward = {} for date_str in exp_dates_str: opt_date = opt[opt.expDate == date_str] opt_call_date = opt_date[opt_date.contractType == 'CO'] opt_put_date = opt_date[opt_date.contractType == 'PO'] opt_call_date = opt_call_date[[u'strikePrice', u'price']].set_index('strikePrice').sort_index() opt_put_date = opt_put_date[[u'strikePrice', u'price']].set_index('strikePrice').sort_index() opt_call_date.columns = [u'callPrice'] opt_put_date.columns = [u'putPrice'] opt_date = concat([opt_call_date, opt_put_date], axis=1, join='inner').sort_index() opt_date['diffCallPut'] = opt_date.callPrice - opt_date.putPrice strike = abs(opt_date['diffCallPut']).idxmin() priceDiff = opt_date['diffCallPut'][strike] date = Date.parseISO(date_str) ttm = abs(float(date - trade_date + 1.0)/365.0) rf = risk_free[date] fw = strike + np.exp(ttm*rf) * priceDiff forward[date] = fw return forward ## 分析歷史某一日的期權收盤價信息,得到隱含波動率微笑和期權風險指標 def histDayAnalysisOpt50ETF(date): opt_var_sec = u"510050.XSHG" # 期權標的 opt = histDayDataOpt50ETF(date) #使用DataAPI.MktFunddGet拿到期權標的的日行情 date_str = date.toISO().replace('-', '') opt_var_mkt = DataAPI.MktFunddGet(secID=opt_var_sec,tradeDate=date_str,beginDate=u"",endDate=u"",field=u"",pandas="1") #opt_var_mkt = DataAPI.MktFunddAdjGet(secID=opt_var_sec,beginDate=date_str,endDate=date_str,field=u"",pandas="1") # 計算shibor exp_dates_str = opt.expDate.unique() periods = {} for date_str in exp_dates_str: exp_date = Date.parseISO(date_str) periods[exp_date] = (exp_date - date)/360.0 shibor = periodsSplineRiskFreeInterestRate(date, periods) # 計算forward price opt_tmp = opt[[u'contractType', u'tradeDate', u'strikePrice', u'expDate', u'settlPrice']] opt_tmp.columns = [[u'contractType', u'tradeDate', u'strikePrice', u'expDate', u'price']] forward_price = histDayMktForwardPriceOpt50ETF(opt_tmp, shibor) settle = opt.settlPrice.values # 期權 settle price close = opt.closePrice.values # 期權 close price strike = opt.strikePrice.values # 期權 strike price option_type = opt.contractType.values # 期權類型 exp_date_str = opt.expDate.values # 期權行權日期 eval_date_str = opt.tradeDate.values # 期權交易日期 mat_dates = [] eval_dates = [] spot = [] for epd, evd in zip(exp_date_str, eval_date_str): mat_dates.append(Date.parseISO(epd)) eval_dates.append(Date.parseISO(evd)) spot.append(opt_var_mkt.closePrice[0]) time_to_maturity = [float(mat - eva + 1.0)/365.0 for (mat, eva) in zip(mat_dates, eval_dates)] risk_free = [] # 無風險利率 forward = [] # 市場遠期 for s, mat, time in zip(spot, mat_dates, time_to_maturity): #rf = math.log(forward_price[mat] / s) / time rf = shibor[mat] risk_free.append(rf) forward.append(forward_price[mat]) opt_types = [] # 期權類型 for t in option_type: if t == 'CO': opt_types.append(1) else: opt_types.append(-1) # 使用通聯CAL包中 BSMImpliedVolatity 計算隱含波動率 calculated_vol = BSMImpliedVolatity(opt_types, strike, spot, risk_free, 0.0, time_to_maturity, settle) calculated_vol = calculated_vol.fillna(0.0) # 使用通聯CAL包中 BSMPrice 計算期權風險指標 greeks = BSMPrice(opt_types, strike, spot, risk_free, 0.0, calculated_vol.vol.values, time_to_maturity) # vega、rho、theta 的計量單位參照上交所的數據,以求統一對比 greeks.vega = greeks.vega #/ 100.0 greeks.rho = greeks.rho #/ 100.0 greeks.theta = greeks.theta #* 365.0 / 252.0 #/ 365.0 opt['strike'] = strike opt['forward'] = np.around(forward, decimals=3) opt['optType'] = option_type opt['expDate'] = exp_date_str opt['spotPrice'] = spot opt['riskFree'] = risk_free opt['timeToMaturity'] = np.around(time_to_maturity, decimals=4) opt['settle'] = np.around(greeks.price.values.astype(np.double), decimals=4) opt['iv'] = np.around(calculated_vol.vol.values.astype(np.double), decimals=4) opt['delta'] = np.around(greeks.delta.values.astype(np.double), decimals=4) opt['vega'] = np.around(greeks.vega.values.astype(np.double), decimals=4) opt['gamma'] = np.around(greeks.gamma.values.astype(np.double), decimals=4) opt['theta'] = np.around(greeks.theta.values.astype(np.double), decimals=4) opt['rho'] = np.around(greeks.rho.values.astype(np.double), decimals=4) fields = [u'ticker', u'contractType', u'strikePrice', 'forward', u'expDate', u'tradeDate', u'closePrice', u'settlPrice', 'spotPrice', u'iv', u'delta', u'vega', u'gamma', u'theta', u'rho'] opt = opt[fields].reset_index().set_index('ticker').sort_index() #opt['iv'] = opt.iv.replace(to_replace=0.0, value=np.nan) return opt # 每日期權分析數據整理 def histDayGreeksIVOpt50ETF(date): # Uqer 計算期權的風險數據 opt = histDayAnalysisOpt50ETF(date) # 整理數據部分 opt.index = [index[-10:] for index in opt.index] opt = opt[['contractType','strikePrice','spotPrice','forward','expDate','closePrice','iv','delta','theta','gamma','vega','rho']] opt.columns = [['contractType','strike','spot','forward','expDate','close','iv','delta','theta','gamma','vega','rho']] opt_call = opt[opt.contractType=='CO'] opt_put = opt[opt.contractType=='PO'] opt_call.columns = pd.MultiIndex.from_tuples([('Call', c) for c in opt_call.columns]) opt_call[('Call-Put', 'strike')] = opt_call[('Call', 'strike')] opt_call[('Call-Put', 'spot')] = opt_call[('Call', 'spot')] opt_call[('Call-Put', 'forward')] = opt_call[('Call', 'forward')] opt_put.columns = pd.MultiIndex.from_tuples([('Put', c) for c in opt_put.columns]) opt = concat([opt_call, opt_put], axis=1, join='inner').sort_index() opt = opt.set_index(('Call','expDate')).sort_index() opt = opt.drop([('Call','contractType'), ('Call','strike'), ('Call','forward'), ('Call','spot')], axis=1) opt = opt.drop([('Put','expDate'), ('Put','contractType'), ('Put','strike'), ('Put','forward'), ('Put','spot')], axis=1) opt.index.name = 'expDate' ## 以上得到完整的歷史某日數據,格式簡潔明了 return opt # 做圖展示某一天的隱含波動率微笑 def histDayPlotSmileVolatilityOpt50ETF(date): cal = Calendar('China.SSE') if not cal.isBizDay(date): print date, ' is not a trading day!' return # Uqer 計算期權的風險數據 opt = histDayGreeksIVOpt50ETF(date) spot = opt[('Call-Put', 'spot')].values[0] # 下面展示波動率微笑 exp_dates = np.sort(opt.index.unique()) ## ---------------------------------------------- fig = plt.figure(figsize=(10,8)) fig.set_tight_layout(True) for i in range(exp_dates.shape[0]): date = exp_dates[i] ax = fig.add_subplot(2,2,i+1) opt_date = opt[opt.index==date].set_index(('Call-Put', 'strike')) opt_date.index.name = 'strike' ax.plot(opt_date.index, opt_date[('Call', 'iv')], '-o') ax.plot(opt_date.index, opt_date[('Put', 'iv')], '-s') (y_min, y_max) = ax.get_ylim() ax.plot([spot, spot], [y_min, y_max], '--') ax.set_ylim(y_min, y_max) ax.legend(['call', 'put'], loc=0) ax.grid() ax.set_xlabel(u"strike") ax.set_ylabel(r"Implied Volatility") plt.title(exp_dates[i]) ``` ```py
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看