swapniljariwala / nsepy

Python Library to get publicly available data on NSE website ie. stock quotes, historical data, live indices
https://nsepy-xyz.web.app
Other
754 stars 376 forks source link

option market data #7

Closed csayantan closed 8 years ago

csayantan commented 8 years ago

hi any chance of getting option data for nifty stocks etc.?

swapniljariwala commented 8 years ago

Hi, Yes you can fetch option data as well. I'll verify if this is not documented.

Thanks Swapnil On 19-Apr-2016 11:33 AM, "csayantan" notifications@github.com wrote:

hi any chance of getting option data for nifty stocks etc.?

— You are receiving this because you are subscribed to this thread. Reply to this email directly or view it on GitHub https://github.com/swapniljariwala/nsepy/issues/7

csayantan commented 8 years ago

hi

please revert me with code example and documentation links if any.

csayantan commented 8 years ago
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

nf_opt = get_history(symbol="NIFTY",
                        start=date(2016,4,1), 
                        end=date(2016,4,18),
                        index=True,
                        option_type="CE",
                        strike_price=7900,
                        expiry_date=date(2016,4,28))
print(nf_opt.head())

thanks I got it.

csayantan commented 8 years ago

I was little more eager to get wPCR ie. well known as doller weighted PCR so i tried to wrote a code ended up having an error if you can help little more helpful iMO it can be done i am little new to python jargon :

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=[]
wPCR=[]

#nf_calls[['VolumeCalls']]=np.nan
#nf_puts[['VolumeCalls']]=np.nan
i=min_avalable_strikes=4850
max_avalable_strike=9400
while i in range(min_avalable_strikes,max_avalable_strike):
    nf_opt_CE = get_history(symbol="NIFTY",
                         start=date(2016,4,1), 
                         end=date(2016,4,22),
                         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)
    '''

    nf_opt_PE = get_history(symbol="NIFTY",
                         start=date(2016,1,1), 
                         end=date(2016,4,18),
                         index=True,
                         option_type="PE",
                         strike_price=i,
                         expiry_date=date(2016,4,28))
    print(nf_opt_PE.head())
    #print(nf_opt_PE.head())
    #print(i)
    #if nf_opt_PE['Number of Contracts'].values>0 :
    '''if nf_opt_CE.empty :
       nf_opt_PE.append(0)
    '''

    i=i+50

#print(wPCR)

'''def PCRForSym():
    return NULL
'''

nf_opt_PE['NewCols']=nf_opt_PE['Number of Contracts']* nf_opt_PE['Close']

nf_opt_CE['NewCols']= nf_opt_CE['Number of Contracts']*nf_opt_CE['Close']

#wPCR=nf_puts

print(nf_opt_PE.head())

i need have a ploter script which will calculate $wPCR just need summation of nf_puts/ summation of nf_calls. can you suggest anything?

swapniljariwala commented 8 years ago
  1. I'm referring to http://investment-and-finance.net/derivatives/w/weighted-put-call-ratio.html . So as far as I understand this should get you daily wpcr-
nf_opt_PE = get_history(symbol="NIFTY",
                     start=date(2016,4,1), 
                     end=date(2016,4,22),
                     index=True,
                     option_type="PE",
                     strike_price=7900,
                     expiry_date=date(2016,4,28))
nf_opt_CE = get_history(symbol="NIFTY",
                     start=date(2016,4,1), 
                     end=date(2016,4,22),
                     index=True,
                     option_type="CE",
                     strike_price=7900,
                     expiry_date=date(2016,4,28))
wpcr = pd.DataFrame(nf_opt_PE['Premium Turnover']/nf_opt_CE['Premium Turnover'])
wpcr.plot()
  1. There is a problem with this while i in range(min_avalable_strikes,max_avalable_strike): , You might want to try something like range(start, end, 50) in steps of 50, you'll get empty results for values like 4851 etc.
  2. Another problem, range of strike price chosen - (4850, 9400) is too large there will be lot of options which will not be traded at all. Refer NSE option chain See all the values of 7450CE
nf = get_history(symbol="NIFTY",
                     start=date(2016,4,1), 
                     end=date(2016,4,22),
                     index=True,
                     option_type="CE",
                     strike_price=7450,
                     expiry_date=date(2016,4,28))

There'll be some 0 values in "Premium Turnover" column. Which means, the options was not traded on that day at all. So the solution is to choose a strike price range of (current NIFTY value +- 400 or 500)

You are doing great. Keep it up. You might want to learn more about python and pandas. Are you writing any blog or something, do share your results of analysis.

csayantan commented 8 years ago

Hi

I was trying summation of volume * Close PE/summation of Volume * Close of CE. however after your advise things look pretty nice now.it is : But it is calculating near month only.But it could be enhanced for Far months calculations also.Please have look and check if it is correct or not.


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))

I do not maintain blog.

csayantan commented 8 years ago

Hi

Problem with PCR is it dznt concern about strike.so after a little search I am thinking of developing an IV from scartch.can you enhance little idea on that?

however: any chance of calculating IV from BSM?does BSM model works on NSE pricing? any chance of calculating the volatility from IV?please reply waiting for your response and advice.

thanks

swapniljariwala commented 8 years ago

I've not heard about BSM. I guess by by IV you mean implied volatility. for IV i've tried this library mibian

technosys99 commented 6 years ago

Hi, Is there a way to get Live data feed from nsepy? if not what other sources we have to get live nse data/ open interest numbers for different strike price / Nifty / bank Nifty? Thanks

tyabhi commented 3 years ago

Hi, is there a way to fetch premiums at different times ? I am successfully able to fetch OHLC at particular day but what about at particular time like 10:45 AM? Thanks