KeyError##9500

from nsepy import get_history

import datetime

from datetime import date

import pandas as pd

import numpy as np



s= date(2017,3,31)



nifty_fut = get_history(symbol="NIFTY",

        start=s,

        end=s,

        index=True,

        futures=True,

        expiry_date=s)

niftydata= nifty_fut



nifty_opt=get_history(symbol="NIFTY",

        start=s,

        end=s,

        index=True,

        option_type='CE',

        strike_price=14000,

        expiry_date=s)



optiondata = nifty_opt



s= s + datetime.timedelta(days=1)



expiry= [date(2017,4,27), 

         date(2017,5,25),

         date(2017,6,29), 

         date(2017,7,27), 

         date(2017,8,31),

         date(2017,9,28), 

         date(2017,10,26), 

         date(2017,11,30), 

         date(2017,12,28)]



for x in expiry:

    expiry=x

    nifty_fut= get_history(symbol="NIFTY",

                          start=s,

                          end=x,

                          index=True,

                          futures=True,

                          expiry_date=x)

    

    niftydata= niftydata.append(nifty_fut)

    

    high= nifty_fut[['Close']].max()

    low= nifty_fut[['Close']].min()

    high= int((round(high/100)*100)+100)

    low= int((round(low/100)*100)-100)

    

   

    for z in range (low, high, 100):

        nifty_opt= get_history(symbol="NIFTY",

                              start=s,

                              end=expiry,

                              index=True,

                              option_type='CE',

                              strike_price=z,

                              expiry_date=x)

        optiondata= optiondata.append(nifty_opt)

        nifty_opt= get_history(symbol="NIFTY",

                              start=s,

                              end=expiry,

                              index=True,

                              option_type='PE',

                              strike_price=z,

                              expiry_date=x)

        optiondata= optiondata.append(nifty_opt)

                

s= x + datetime.timedelta(days=1)



NiftyCF = pd.DataFrame({"Nifty": niftydata["Close"]})

NiftyCO= pd.DataFrame ({"Expiry": optiondata['Expiry'],

                       "Type":optiondata['Option Type'],

                       "Strike":optiondata['Strike Price'],

                       "Last":optiondata['Last']})

NiftyCO=NiftyCO.join(NiftyCF)

Opttable = pd.pivot_table(NiftyCO, values= 'Last', index =['Date','Nifty','Type','Expiry'],columns= ['Strike'], aggfunc= np.sum)

Opttable.to_csv("April 2017 OptionsFinal.csv", index=True, encoding='utf8')



Table = pd.read_csv('April 2017 OptionsFinal.csv')

Table['month'] = pd.to_datetime(Table['Date']).dt.strftime('%m')

Table.head()



Table1 = Table.groupby('month').first()

Table1['M'] = pd.to_datetime(Table1['Date']).dt.strftime('%m')

Table1['ATM_Strike'] = round(Table1['Nifty']/100)*100



######Everything is ok till here

Table3 = pd.DataFrame({"Date":['0'], "Close":['0'], "Expiry":['0'], 

                       "Type":['0'], "month":['0'], "ATM":['0'], 

                       "OTM":['0'], "Ratio":['0'], "P&L":['0']})



Table4 = pd.DataFrame({"Date":['0'], "Close":['0'], "Expiry":['0'], 

                       "Type":['0'], "month":['0'], "ATM":['0'], 

                       "OTM":['0'], "Ratio":['0'], "P&L":[0]})

for x in range (0,9):

    e=Table1.M

    d=Table1.Expiry

    a= int((Table1.ATM_Strike))

    a=a+200

    b = a+200

    f1 = str(a)

    f2 = str(b)

    Table2 = pd.DataFrame({"Date": Table["Date"], "Close": Table["NIFTY"], 

                           "Expiry": Table["Expiry"], "Type": Table["Type"], 

                       "month": Table["month"], "ATM": Table[f1], "OTM": Table[f2]})

    Table2= Table2.where((Table2.month == e) & (Table2.Expiry == d) & (Table2.Type == "CE"))

    Table2 = Table2.dropna()

    Table2['Ratio']=Table2['ATM']-(Table2['OTM']*2)

    Table2['P&L']=Table2['Ratio'].diff().cumsum()

    Table3 = Table3.append(Table2)

    Table4= Table4.append(Table2.where((Table2.Date == d)))

    Table4 = Table4.dropna()

Table4.drop(["Date", "Close", "Expiry", "Type", "ATM", "OTM", "Ratio"], axis = 1, inplace = True)

Table4['Total_P&L']=Table4['P&L'].cumsum()

print (Table4)

 

KeyError: '9500'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-84-641e305894a7> in <module>
     11                            "Type": Table["Type"],
     12                            "month": Table["month"],
---> 13                            "ATM": Table[f1], "OTM": Table[f2]})


 

Hi Mukul, 



Kindly elaborate on what you are trying to do here.



As of now, what is happening here is variable a is in form of an integer. When you convert it to string, a is of the form 9500. However, the columns in the Table dataframe has the name 9500.0. Hence you can convert a into type float and then proceed. However, this will further result in an error when dealing with the maximum value. The maximum value of 'Table1.ATM_Strike' is 10500.0. While calculating a and b, you are further adding 200 to the max value, which will again result in the error for '10700.0'. To avoid this, you can consider creating a filter or a condition. 



Hope this would help you.