PCR(美元加权看跌期权比率)计算问题

时间:2016-04-22 15:10:05

标签: python pandas numpy

我正在尝试为自己的目的生成一个看跌/看涨比率计算程序。这是代码:问题是我被困在某些地方。

  1. 我需要生成所有罢工量的总和*所有罢工价格
  2. 并且最后一个产生比率即总和(所有罢工PUT量*全部罢工PUT价格)/总和(所有罢工通话量*所有罢工通话价格)。
  3. 到目前为止,我尝试了很多并最终得到了错误的程序。但是我现在提供的代码是进一步的,以便我可以完成剩下的部分正确获取OutPut。 (nse 不提供PCR,因为CBO确实提供了解决方案。)

    from nsepy import get_history
    from datetime import date
    import pandas as pd
    import requests
    from io import BytesIO 
    import certifi
    from scipy import stats
    from dateutil.relativedelta import relativedelta
    import numpy as np
    #import matplotlib.pyplot as plt
    import datetime
    import numpy as np
    import matplotlib.colors as colors
    import matplotlib.finance as finance
    import matplotlib.dates as mdates
    import matplotlib.ticker as mticker
    import matplotlib.mlab as mlab
    import matplotlib.pyplot as plt
    import matplotlib.font_manager as font_manager
    import talib as ta
    from talib import MA_Type
    import statsmodels as sm
    
    
    
    nf_calls=[]
    nf_puts=[]
    
    
    #nf_calls[['VolumeCalls']]=np.nan
    #nf_puts[['VolumeCalls']]=np.nan
    i=min_avalable_strikes=4850
    max_avalable_strike=9400
    wPCR=nf_opt_CE=nf_opt_PE=pd.DataFrame()
    
    while i in range(min_avalable_strikes,max_avalable_strike):
        temp_CE = get_history(symbol="NIFTY",
                             start=date(2016,2,1), 
                             end=date(2016,4,24),
                             index=True,
                             option_type="CE",
                             strike_price=i,
                             expiry_date=date(2016,4,28))
    
        #print(nf_opt_CE.head())
        #if nf_opt_CE['Number of Contracts'].values >0 :
        '''if nf_opt_CE.empty :
            nf_opt_CE.append(0)
        '''
    
        temp_PE = get_history(symbol="NIFTY",
                             start=date(2016,2,1), 
                             end=date(2016,4,22),
                             index=True,
                             option_type="PE",
                             strike_price=i,
                             expiry_date=date(2016,4,28))
        #nf_opt_PE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True)
        #nf_opt_CE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True)
    
        #temp_CE=temp_CE.drop(temp_CE[temp_CE['Number of Contracts']>0.0].index)
        #temp_PE=temp_PE.drop(temp_CE[temp_CE['Number of Contracts']>0.0].index)
        nf_opt_CE=pd.concat([nf_opt_CE,temp_CE]).drop_duplicates()
        nf_opt_PE=pd.concat([nf_opt_PE,temp_PE]).drop_duplicates()
        nf_opt_CE.index=pd.to_datetime(nf_opt_CE.index)
        nf_opt_PE.index=pd.to_datetime(nf_opt_PE.index)
        i=i+50
        #print(i)
    
    #print(nf_opt_PE.head())
    nf_opt_PE.drop_duplicates(inplace=True)
    nf_opt_CE.drop_duplicates(inplace=True)
    #print(nf_opt_PE.head(100))
    
    nf_opt_PE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True)
    nf_opt_CE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True)
    
    nf_opt_PE.drop(['Symbol','Expiry','Open','High' ,'Low','Last','Settle Price','Turnover','Premium Turnover','Open Interest'  ,'Change in OI','Underlying'],axis=1,inplace=True)
    
    nf_opt_CE.drop(['Symbol','Expiry','Open','High' ,'Low','Last','Settle Price','Turnover','Open Interest','Premium Turnover' ,'Change in OI','Underlying'],axis=1,inplace=True)
    
    nf_opt_PE = nf_opt_PE[nf_opt_PE.Volume > 0]
    nf_opt_CE = nf_opt_CE[nf_opt_CE.Volume > 0]
    #print(nf_opt_PE.tail())
    
    ##priceCrossVolume###
    nf_opt_PE['VolCrossPrice']=nf_opt_PE.apply(lambda x: (x['Volume']*x['Close']),axis=1)
    nf_opt_CE['VolCrossPrice']=nf_opt_CE.apply(lambda x: (x['Volume']*x['Close']),axis=1)
    
    #nf_puts= nf_opt_CE['Number of Contracts']*nf_opt_CE['Close']
    #print(nf_calls.head())
    
    
    nf_opt_PE.drop(['Volume','Close'],axis=1,inplace=True)
    nf_opt_CE.drop(['Volume','Close'],axis=1,inplace=True)
    #print(nf_opt_PE.index.Date)
    #nf_opt_PE['Summation']=nf_opt_PE.groupby(nf_opt_PE.columns[[0]])['VolCrossPrice'].sum()
    wPCR=pd.concat([nf_opt_PE,nf_opt_CE])
    #wPCR.drop(['Volume','Close'],axis=1,inplace=True)
    #wPCR['Summation']=wPCR.groupby(wPCR.columns[[0,1]]).sum()
    wPCR['Summation']=wPCR[['Option Type'] == wPCR['Option Type']].groupby(level=0).sum()
    
    print(nf_opt_PE.head(500))
    print(wPCR.tail(500))
    

    遇到错误:

    Traceback (most recent call last):
      File "PCRForNF.py", line 101, in <module>
        wPCR['Summation']=wPCR[['Option Type'] == wPCR['Option Type']].groupby(level=0).sum()
      File "/usr/local/lib/python2.7/dist-packages/pandas/core/ops.py", line 761, in wrapper
        res = na_op(values, other)
      File "/usr/local/lib/python2.7/dist-packages/pandas/core/ops.py", line 677, in na_op
        result = lib.vec_compare(x, y.astype(np.object_), op)
      File "pandas/lib.pyx", line 828, in pandas.lib.vec_compare (pandas/lib.c:14760)
    ValueError: Arrays were different lengths: 3030 vs 1
    

    我假设错误在:

    wPCR['Summation']=wPCR[['Option Type'] == wPCR['Option Type']].groupby(level=0).sum()
    

    有人能建议一种简单的方法从这里找到合适的加权PCR吗?

1 个答案:

答案 0 :(得分:-1)

    from nsepy import get_history
from datetime import date
import pandas as pd
import requests
from io import BytesIO 
import certifi
from scipy import stats
from dateutil.relativedelta import relativedelta
import numpy as np
#import matplotlib.pyplot as plt
import datetime
import numpy as np
import matplotlib.colors as colors
import matplotlib.finance as finance
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import talib as ta
from talib import MA_Type
import statsmodels as sm



nf_calls=[]
nf_puts=[]


#nf_calls[['VolumeCalls']]=np.nan
#nf_puts[['VolumeCalls']]=np.nan
i=min_avalable_strikes=4850
max_avalable_strike=9400
nf_opt_CE=nf_opt_PE=pd.DataFrame()

while i in range(min_avalable_strikes,max_avalable_strike):
    temp_CE = get_history(symbol="NIFTY",
                         start=date(2016,2,1), 
                         end=date(2016,4,24),
                         index=True,
                         option_type="CE",
                         strike_price=i,
                         expiry_date=date(2016,4,28))

    #print(nf_opt_CE.head())
    #if nf_opt_CE['Number of Contracts'].values >0 :
    '''if nf_opt_CE.empty :
        nf_opt_CE.append(0)
    '''

    temp_PE = get_history(symbol="NIFTY",
                         start=date(2016,2,1), 
                         end=date(2016,4,22),
                         index=True,
                         option_type="PE",
                         strike_price=i,
                         expiry_date=date(2016,4,28))
    #nf_opt_PE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True)
    #nf_opt_CE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True)

    #temp_CE=temp_CE.drop(temp_CE[temp_CE['Number of Contracts']>0.0].index)
    #temp_PE=temp_PE.drop(temp_CE[temp_CE['Number of Contracts']>0.0].index)
    nf_opt_CE=pd.concat([nf_opt_CE,temp_CE]).drop_duplicates()
    nf_opt_PE=pd.concat([nf_opt_PE,temp_PE]).drop_duplicates()
    nf_opt_CE.index=pd.to_datetime(nf_opt_CE.index)
    nf_opt_PE.index=pd.to_datetime(nf_opt_PE.index)
    i=i+50
    #print(i)

#print(nf_opt_PE.head())
nf_opt_PE.drop_duplicates(inplace=True)
nf_opt_CE.drop_duplicates(inplace=True)
#print(nf_opt_PE.head(100))

nf_opt_PE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True)
nf_opt_CE.rename(columns = {'Number of Contracts':'Volume'}, inplace = True)

nf_opt_PE.drop(['Symbol','Expiry','Open','High' ,'Low','Last','Settle Price','Turnover','Open Interest'  ,'Change in OI','Underlying'],axis=1,inplace=True)

nf_opt_CE.drop(['Symbol','Expiry','Open','High' ,'Low','Last','Settle Price','Turnover','Open Interest','Change in OI','Underlying'],axis=1,inplace=True)

nf_opt_PE = nf_opt_PE[nf_opt_PE.Volume > 0]
nf_opt_CE = nf_opt_CE[nf_opt_CE.Volume > 0]
#print(nf_opt_PE.tail())

##priceCrossVolume###
nf_opt_PE['PESum']=nf_opt_PE.groupby(level=0)['Premium Turnover'].sum()
nf_opt_CE['CESum']=nf_opt_CE.groupby(level=0)['Premium Turnover'].sum()

#nf_puts= nf_opt_CE['Number of Contracts']*nf_opt_CE['Close']
#print(nf_calls.head())


nf_opt_PE.drop(['Volume','Close'],axis=1,inplace=True)
nf_opt_CE.drop(['Volume','Close'],axis=1,inplace=True)
#print(nf_opt_PE.index.Date)
#nf_opt_PE['Summation']=

wPCR= (nf_opt_PE['PESum']/nf_opt_CE['CESum'])
#wPCR.rename(columns = {'0':'wPCR'}, inplace = True)
wPCR.plot()
plt.show()

#print(wPCR.head(500))
#print(nf_opt_PE.tail(500))