Call & Put Options: ITM-ATM-OTM Concepts in Python with Processing out WebSocket RTD

from kiteconnect import KiteTicker
from kiteconnect import KiteConnect
import numpy as np
import pandas as pd
import time

api_key='your_api_key'
api_secret='your_api_secret'
access_token='your_access_token'
kite=KiteConnect(api_key,api_secret)
kite.set_access_token(access_token)
kws=KiteTicker(api_key,access_token)
exchange='NFO'
last_price_exchange='NSE'
last_price_tradingsymbol='NIFTY BANK'
tradingsymbol='BANKNIFTY'
expiry='22NOV18'
last_price=kite.ltp('%s:%s'%(last_price_exchange,last_price_tradingsymbol))['%s:%s'%(last_price_exchange,last_price_tradingsymbol)]['last_price']
instruments=kite.instruments('NFO')
instruments=pd.DataFrame(instruments)
segment_str_match=instruments[instruments['tradingsymbol'].str.match(tradingsymbol+expiry)]
strike=segment_str_match['strike']
ITMCE=[i for i in strike if(np.round(last_price)>i)]
ITMPE=[i for i in strike if(np.round(last_price)IDXITMCE=np.abs(ITMCE-np.round(last_price)).argmin()
IDXITMPE=np.abs(ITMPE-np.round(last_price)).argmin()
PE='PE'
CE='CE'
str_int_CE=tradingsymbol+expiry+str(int(ITMCE[IDXITMCE]))+PE
str_int_PE=tradingsymbol+expiry+str(int(ITMPE[IDXITMPE]))+CE
time.sleep(1)
instrument_token_CE=kite.ltp('%s:%s'%(exchange,str_int_CE))['%s:%s'%(exchange,str_int_CE)]['instrument_token']
time.sleep(1)
instrument_token_PE=kite.ltp('%s:%s'%(exchange,str_int_PE))['%s:%s'%(exchange,str_int_PE)]['instrument_token']
tokens=[instrument_token_CE,instrument_token_PE]
dict={instrument_token_CE:str_int_CE,instrument_token_PE:str_int_PE}
def on_ticks(ws,ticks):
    print(dict[ticks[0]['instrument_token']],ticks[0]['timestamp'],ticks[0]['last_price'])
def on_connect(ws,response):
    ws.subscribe(tokens)
kws.on_ticks=on_ticks
kws.on_connect=on_connect
kws.connect(threaded=True)
count=0
while True:
    count+=1
    if(count%2==0):
        
        if(kws.is_connected):
            
            kws.set_mode(kws.MODE_FULL,tokens)
        else:
            if(kws.is_connected):
                
                kws.set_mode(kws.MODE_FULL,tokens)
    time.sleep(0.500)
            

NSEpy Library to Extract Historical Data from NSE’s Website

Hello Everyone, as we know from previous video tutorial of NSEPY mentioned below where we are able to fetch historical data so now i'm here to guide the updated and simpler version of it which will fetch our data as required here we mention a start as from date and end as to date.First we fetch an equity stock then we move towards spot price and then further future and options can be fetched as mentioned with fewer input details.Mostly we see historical data in the form of EOD candle of that particular day.The historical data always combined with realtime data to perform programmatic trading or algorithmic trading or it serves the data analysis purpose.To get the realtime data and perform the programmatic trading you can open an alice blue account and you can get Free API through our refferal link as follows Alice Blue Free API Register Here



from nsepy import get_history
from datetime import datetime
import dateutil.relativedelta
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
to_date=datetime.now()
to_date=datetime.strftime(to_date,'%Y,%m,%d')
to_date=datetime.strptime(to_date,'%Y,%m,%d')
from_date=to_date-dateutil.relativedelta.relativedelta(month=1)
data=get_history(symbol='RELIANCE',start=from_date,end=to_date)
print(data)
data['Close'].plot()
plt.show()


Updated and Simpler Version:



from nsepy import get_history as gh
import datetime as dt
import dateutil.relativedelta as dr
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
tradingsymbol='NIFTY BANK'
end=dt.date.today()
start=end-dr.relativedelta(days=30)
data=gh(tradingsymbol,start,end,index=True)
data['Close'].plot()
plt.show()

Backtest Strategy Using Backtrader Framework

Generating CSV/TXT Data:


import pandas as pd
from upstox_api.api import*
from datetime import datetime

api_key=open('api_key.txt','r').read()
access_token=open('access_token.txt','r').read().strip()
u=Upstox(api_key,access_token)
master_contract=u.get_master_contract('nse_eq')
master_contract=pd.DataFrame(master_contract)
exchange='nse_eq'
tradingsymbol='reliance'
from_date='01/09/2018'
now=datetime.now()
to_date=datetime.strftime(now,'%d/%m/%Y')

data=u.get_ohlc(u.get_instrument_by_symbol(exchange,tradingsymbol),OHLCInterval.Minute_1,
datetime.strptime('%s'%(from_date),'%d/%m/%Y').date(),datetime.strptime('%s'%(to_date),'%d/%m/%Y').date())
data=pd.DataFrame(data)
data['timestamp']=pd.to_datetime(data['timestamp'],unit='ms')
data['timestamp']=data['timestamp'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
data.set_index('timestamp',inplace=True)
data.to_csv('RELIANCE_'+str(datetime.now().strftime('%Y_%m_%d')),date_format='%Y-%m-%d %H:%M:%S')
print(data)

For backtesting use Backtrader just pip install backtrader in cmd then go for the code:


import backtrader as bt
import backtrader.feeds as btfeeds
import os
import datetime


class TestStrategy(bt.Strategy):

    def log(self, txt, dt=None):
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        self.dataclose = self.datas[0].close
        self.order = None
        self.buyprice = None
        self.buycomm = None

        bt.indicators.ExponentialMovingAverage(self.datas[0], period=25)

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return

        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))

                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            else:
                self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                         (order.executed.price,
                          order.executed.value,
                          order.executed.comm))

            self.bar_executed = len(self)

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')

        self.order = None

    def notify_trade(self, trade):
        if not trade.isclosed:
            return

        self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                 (trade.pnl, trade.pnlcomm))

    def next(self):
        self.log('Close, %.2f' % self.dataclose[0])

        if self.order:
            return

        if not self.position:

            if self.dataclose[0] - self.dataclose[-1] > 3:

                self.log('BUY CREATE, %.2f' % self.dataclose[0])
                self.order = self.buy()

        else:

            if self.dataclose[0] - self.dataclose[-1] < -3:
                self.log('SELL CREATE, %.2f' % self.dataclose[0])
                self.order = self.sell()


if __name__ == '__main__':
    cerebro = bt.Cerebro()
    cerebro.addstrategy(TestStrategy)
    datapath = os.path.abspath(os.getcwd() + '/RELIANCE_' + str(datetime.datetime.now().strftime("%Y_%m_%d")))

    # Create a Data Feed
    data = btfeeds.GenericCSVData(
        dataname=datapath,
        fromdate=datetime.datetime(2018,9,1),
        dtformat=('%Y-%m-%d %H:%M:%S'),
        timestamp=0,
        high=3,
        low=4,
        open=5,
        close=1,
        volume=6,
        timeframe= bt.TimeFrame.Minutes,
        compression= 1
    )

    cerebro.adddata(data)

    cerebro.broker.setcash(1000.0)

    cerebro.addsizer(bt.sizers.FixedSize, stake=0.05)

    cerebro.broker.setcommission(commission=0.01)

    print('Starting Balance: %.2f' % cerebro.broker.getvalue())

    cerebro.run()

    print('Final Balance: %.2f' % cerebro.broker.getvalue())

    cerebro.plot()

ZEEL

\

YESBANK

\

WIPRO

\

VEDL

\

UPL

\

ULTRACEMCO

\

TECHM

\

TATASTEEL

\

TATAMOTORS

\

TCS

\