Skip to content

Stock Market Trend

PyScript – programming for the 99%

Follow us on Twitter
# Import necessary libraries
import requests
import pandas as pd
import xlwings as xw
from datetime import datetime, timedelta
import time
import traceback

def fetch_and_update_data():
# Define the URL and headers
url = “”
headers = {
‘user-agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36 Edg/103.0.1264.37’,
‘accept-encoding’: ‘gzip, deflate, br’,
‘accept-language’: ‘en-GB,en;q=0.9,en-US;q=0.8’

# Create a session and get the response
session = requests.Session()
response = session.get(url, headers=headers)
cookies = response.cookies # Get cookies from the response

# Extract the data from the response
data = response.json()[“records”][“data”]
ocdata = []

# Calculate the upcoming thursday
current_date =
upcoming_thursday = current_date + timedelta((3 – current_date.weekday() + 7) % 7)
upcoming_thursday_str = upcoming_thursday.strftime(‘%d-%b-%Y’)

# Get the current market price of NIFTY
market_price = response.json()[“records”][“underlyingValue”]

# Round the market price to the nearest 50
market_price_rounded = round(market_price / 50) * 50

# Define the specific strike prices for CE and PE based on the rounded market price
ce_strikes = [market_price_rounded – i*50 for i in range(2, -6, -1)] # 2 ITM and 5 OTM for CE
pe_strikes = [market_price_rounded + i*50 for i in range(2, -6, -1)] # 2 ITM and 5 OTM for PE

# Extract the required data
for i in data:
for j, k in i.items():
if j == “CE” and k[‘expiryDate’] == upcoming_thursday_str and k[‘strikePrice’] in ce_strikes:
info = k
info[“instrumentType”] = j
elif j == “PE” and k[‘expiryDate’] == upcoming_thursday_str and k[‘strikePrice’] in pe_strikes:
info = k
info[“instrumentType”] = j

# Create a DataFrame from the data
df = pd.DataFrame(ocdata)

# Filter and sort the data
if ‘instrumentType’ in df.columns:
df_ce = df[(df[‘instrumentType’] == ‘CE’) & (df[‘strikePrice’] >= market_price)].sort_values(by=’strikePrice’)
df_ce2 = df[(df[‘instrumentType’] == ‘CE’) & (df[‘strikePrice’] <= market_price)].sort_values(by='strikePrice') df_pe = df[(df['instrumentType'] == 'PE') & (df['strikePrice'] <= market_price)].sort_values(by='strikePrice', ascending=False) df_pe2 = df[(df['instrumentType'] == 'PE') & (df['strikePrice'] >= market_price)].sort_values(by=’strikePrice’, ascending=False)

# Concatenate and sort the final DataFrame by instrument type and strike price
df_final = pd.concat([df_ce, df_ce2, df_pe, df_pe2])
df_final_ce = df_final[df_final[‘instrumentType’] == ‘CE’].sort_values(by=’strikePrice’, ascending=True)
df_final_pe = df_final[df_final[‘instrumentType’] == ‘PE’].sort_values(by=’strikePrice’, ascending=False)
df_final_sorted = pd.concat([df_final_ce, df_final_pe])
print(“No data found for the given conditions.”)
df_final_sorted = pd.DataFrame() # Create an empty DataFrame

# Open the workbook and update the data
wb = xw.Book(“oi1.xlsm”)
st = wb.sheets(“nifty”)
st.range(“A1″).value = df_final_sorted

# Save the workbook

# Pause the script

# Run the function in a loop
while True:
except Exception as e:
print(f”An error occurred: {e}”)
traceback.print_exc() # This will print the stack trace


Use of this website and/or services offered by us indicates your acceptance of our Disclaimer.

Disclaimer: Any action you choose to take in the markets is totally your own responsibility. will not be liable for any, direct or indirect, consequential or incidental damages or loss arising out of the use of this information. This information is neither an offer to sell nor a solicitation to buy any of the securities mentioned herein. Except as otherwise provided you may not reproduce, republish, post, copy, transfer, transmit, extract or otherwise distribute the contents in any manner. You may only view and print/copy of the contents for your own personal, non-commercial purpose.

Open chat
Scan the code
Can we help you?