Saturday, December 19, 2020

Option Chain Analysis In Index for Intraday Trading

 In Futures and options trading Open Interest is considered to be a very important mertics to track as it represent the oustanding open contracts of the underlying security, for example for Nifty 13500 PE is having open interest as 25 means there are 25 contracts between PE buyer and seller. A new contract is open as soon as new Buyer has been introduced with new seller. If an existing contract has been exchanged between a buyer and seller it doesn't impact the open interest but it increases the volumne of instrument, let's say Person A is having a bought option contract for Nifty 13500 PE and Person B has sold the same contract, after some price action Person B wants to close his trade so he wants to buy the same contract from open market and if this is sold by person C it is just transfer of option contract from person B to person C. If person C wants to increase his traded lot size means he want to sell 1 more lot of Nifty 13500 PE and person D buys 1 lot that means a new contract has been opened on the exchange which increases the Open Interest of the instrument (Nifty 13500 PE).


Usually In Indian derivative market the trend is all big players sell the options and retailers or hedge funds buy, and during Intraday big players move the market as per their desire or positions, this is speculation not concreate but observed for a long time.


So, option interest numbers give an indication about the direction of intraday movement of index or underlying security. for this you need to consider 5-6 strikes on both side to the ATM(At the money, if nifty is trading at 13545 then nearest strike is 13550 which becomes ATM strike) and sum OI of both Puts and Calls which gives about which option is being sold aggresively. 


If put OI sum is greater than Call OI sum that means Puts are being sold by big players means Market is bullish as per OI analysis.


There are many other factors which decide market direction but option chain analysis helps in your trade taken. You should take help from Price action or candlestick pattern as well to support OI analysis.

Sheet is below: Enjoy

Best books for candlestick patterns

Candlestick chart is a chart with which is represented by candles, each candle is having Open, High, Low and Close(in short OHLC) prices for a particular timeframe.

If the chart is having these price points for a day then it is called daily timeframe chart, similarly trader use different time frame like for Intraday trading most traders use 3 min, 5 min or 15 min timeframe.

Fig: Candles representing Bullish as well as Bearish behavior.

Best Books to read about Candlestick chart pattern:

Steve Nilson has written many books on candlestick pattern but I recommend Japanese cadlestick charting techniques, it is a wonderful read and give in depth knowledge about candlestick patterns.

 

We recomment below books for indepth knowledge about candlestick charting: 

1. Japanese Candlestick Charting Techniques - Steve Nilson


Friday, November 27, 2020

सत्यनारायण लाल - किसान (Kisan - Satyanarayan Lal)

नहीं हुआ है अभी सवेरा
पूरब की लाली पहचान
चिड़ियों के जगने से पहले
खाट छोड़ उठ गया किसान ।

खिला-पिलाकर बैलों को ले
करने चला खेत पर काम
नहीं कोई त्योहार न छुट्टी
उसको नहीं काबी आराम।

गरम-गरम लू चलती सन-सन
धरती जलती तवा समान
तब भी करता काम खेत पर
बिना किए आराम किसान।

बादल गरज रहे गड़-गड़-गड़
बिजली चमक रही चम-चम
मुसलाधार बरसता पानी
ज़रा न रुकता लेता दम।

हाथ पांव ठिठुरते जाते हैं
घर से बाहर निकले कौन
फिर भी आग जला, खेतों की
रखवाली करता है वह मौन।

है किसान को चैन कहाँ, वह
करता रहता हरदम काम
सोचा नहीं कभी भी उसने
घर पर रह करना आराम।

- सत्यनारायण लाल

Wednesday, November 25, 2020

Read Option chain data from Nifty using Python

Read Option chain data from Nifty using Python


Option chain data is very crucial for Future and Options(FnO) trader analysis, many use it for positional while many use it to find day trend and it's strength as well as option strike selection for trading.


In this blog post we will try to figure out how to read options data from NSE APIs using Python.

Code:

   
  #!/usr/bin/env python3
 
import requests
import pandas as pd
from datetime import datetime
from dateutil.relativedelta import relativedelta, TH
 
# Find next thursday to figure out weekly expiry.
def next_thu_expiry_date():
    todayte = datetime.today()
 
    next_thursday_expiry = todayte + relativedelta(weekday=TH(1))
 
    str_next_thursday_expiry = str(next_thursday_expiry.strftime("%d")) + "-" + next_thursday_expiry.strftime(
        "%b") + "-" + next_thursday_expiry.strftime("%Y")
    print(str_next_thursday_expiry)
    return str_next_thursday_expiry
 
 
def find_ce_pe(spot_price, ce_values, pe_values):
    spot_price = round(spot_price, -2)
    otm_calls = []
    otm_puts = []
 
    ce_dt = pd.DataFrame(ce_values).sort_values(['strikePrice'])
    pe_dt = pd.DataFrame(pe_values).sort_values(['strikePrice'], ascending=False)
 
    for ce_value in ce_dt['strikePrice']:
        if ce_value >= spot_price:
            otm_calls.append(ce_value)
            if len(otm_calls) > 10:
                break
 
    for ce_value in pe_dt['strikePrice']:
        if ce_value <= spot_price:
            otm_puts.append(ce_value)
            if len(otm_puts) > 10:
                break
 
    return otm_calls, otm_puts
 
 
def read_oi(spot_price, ce_values, pe_values, symbol):
    sheet_name = str(datetime.today().strftime("%d-%m-%Y")) + symbol
 
    strike_oi_ce_pe = find_ce_pe(float(spot_price), ce_values, pe_values)
 
    ce_dt = pd.DataFrame(ce_values).sort_values(['strikePrice'])
    pe_dt = pd.DataFrame(pe_values).sort_values(['strikePrice'], ascending=False)
 
    drop_col = ['pchangeinOpenInterest', 'askQty', 'askPrice', 'underlyingValue', 'totalBuyQuantity',
                'totalSellQuantity', 'bidQty', 'bidprice', 'change', 'pChange', 'impliedVolatility',
                'totalTradedVolume']
    ce_dt.drop(drop_col, inplace=True, axis=1)
    pe_dt.drop(drop_col, inplace=True, axis=1)
 
    ce_dt = ce_dt.loc[ce_dt['strikePrice'].isin(strike_oi_ce_pe[0])]
    pe_dt = pe_dt.loc[pe_dt['strikePrice'].isin(strike_oi_ce_pe[1])]
 
    # print(ce_dt[['strikePrice', 'lastPrice']])
    # print(pe_dt[['strikePrice', 'changeinOpenInterest']])
 
    print(ce_dt.head(1))
    print(pe_dt.head(1))
 
    print(str([spot_price, (ce_dt['changeinOpenInterest'].sum()),
               (pe_dt['changeinOpenInterest'].sum())]))
 
 
def main():
    symbols = ["BANKNIFTY", "NIFTY"]
    base_url = 'https://www.nseindia.com/api/option-chain-indices?symbol='
    url_oc = "https://www.nseindia.com/option-chain"
 
    for symbol in symbols:
        headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, ''like Gecko) '
                                 'Chrome/80.0.3987.149 Safari/537.36',
                   'accept-language': 'en,gu;q=0.9,hi;q=0.8', 'accept-encoding': 'gzip, deflate, br'}
        session = requests.Session()
        request = session.get(url_oc, headers=headers, timeout=5)
        cookies = dict(request.cookies)
        response = session.get(base_url + symbol, headers=headers, timeout=5, cookies=cookies)
        print(response.status_code)
        dajs = response.json()
        expiry = next_thu_expiry_date()
 
        spot_price = dajs['records']['underlyingValue']
        ce_values = [data['CE'] for data in dajs['records']['data'] if "CE" in data and data['expiryDate']
                     == expiry]
        pe_values = [data['PE'] for data in dajs['records']['data'] if "PE" in data and data['expiryDate']
                     == expiry]
 
        read_oi(spot_price, ce_values, pe_values, symbol)
 
        print(len(dajs))
 
 
if __name__ == '__main__':
    main()
  
  


In case of any doubt leave a comment I will try to answer.

Note: This post is for educational purpose only.

Sunday, November 22, 2020

Automatic Login to Zerodha using Python and Selenium

Hello Readers,

 

Today we will try to learn browser automation using Python and Selenium automation tool.

 

We will write a code to automate login process of Zerodha trading platform using selenium and python in Google Chrome browser.

Place a file named zerodha-credentials.json at the same location as the actual python script with zerodha credentials as below:



Run the below script to automatically login, code is mostly self-explanatory leave a comment if any doubt, I will try to respond.

 

Note: Think before storing your credentials in plain text, potential risk of it being compromised. This post is for education purpose to learn how we can automate web surfing using Python.

Python Basic String opetations

Python is fast emerging as a programming language, so In this post I will try to explain few python String operations required for a novice learner.



Tuesday, July 28, 2020

हम दुनिया से जब तंग आया करते हैं - तैमूर हसन

हम दुनिया से जब तंग आया करते हैं

अपने साथ इक शाम मनाया करते हैं

सूरज के उस जानिब बसने वाले लोग

अक्सर हम को पास बुलाया करते हैं

यूँही ख़ुद से रूठा करते हैं पहले

देर तलक फिर ख़ुद को मनाया करते हैं

चुप रहते हैं उस के सामने जा कर हम

यूँ उस को चख याद दिलाया करते हैं

नींदों के वीरान जज़ीरे पर हर शब

ख़्वाबों का इक शहर बसाया करते हैं

इन ख़्वाबों की क़ीमत हम से पूछ कि हम

इन के सहारे उम्र बिताया करते हैं

अब तो कोई भी दूर नहीं तो फिर 'तैमूर'

हम ख़त किस के नाम लिखाया करते हैं



Hum Duniya se jab tang aaya karte hain - Taimur Hassan

फ़ैज़ अहमद फ़ैज़ की नज़्म - 'कुछ इश्क़ किया कुछ काम किया'


कुछ इश्क़ किया कुछ काम किया

वो लोग बहुत ख़ुश-क़िस्मत थे

जो इश्क़ को काम समझते थे

या काम से आशिक़ी करते थे

हम जीते-जी मसरूफ़ रहे

कुछ इश्क़ किया कुछ काम किया

काम इश्क़ के आड़े आता रहा

और इश्क़ से काम उलझता रहा

फिर आख़िर तंग आ कर हम ने

दोनों को अधूरा छोड़ दिया


Woh log bahut khush kishmat the,
Jo Ishq ko kaam samajhte the -- Faiz Ahmed faiz