strike project django get nearest strike
import pandas as pd
from django.db import connection
from datetime import datetime, timedelta
import pytz
today_string=None
yesterday_string=None
tomorrow_string=None
def detect_day(today):
global today_string, yesterday_string, tomorrow_string
date_string = today
parsed_date = datetime.strptime(date_string, "%Y-%m-%d")
day_of_week = parsed_date.weekday()
day_of_week_string = parsed_date.strftime("%A")
# print(day_of_week)
# print(day_of_week_string)
date_string = today
parsed_date = datetime.strptime(date_string, "%Y-%m-%d")
yesterday = parsed_date - timedelta(days=1)
yesterday_string = yesterday.strftime("%Y-%m-%d")
# print("Yesterday's date:", yesterday_string)
if day_of_week == 0:
yesterday = parsed_date - timedelta(days=3)
yesterday_string = yesterday.strftime("%Y-%m-%d")
today_string = today
tomorrow_string = parsed_date + timedelta(days=1)
tomorrow_string = tomorrow_string.strftime("%Y-%m-%d")
if day_of_week == 1:
yesterday = parsed_date - timedelta(days=1)
yesterday_string = yesterday.strftime("%Y-%m-%d")
today_string = today
tomorrow_string = parsed_date + timedelta(days=1)
tomorrow_string = tomorrow_string.strftime("%Y-%m-%d")
if day_of_week == 2:
yesterday = parsed_date - timedelta(days=1)
yesterday_string = yesterday.strftime("%Y-%m-%d")
today_string = today
tomorrow_string = parsed_date + timedelta(days=1)
tomorrow_string = tomorrow_string.strftime("%Y-%m-%d")
if day_of_week == 3:
yesterday = parsed_date - timedelta(days=1)
yesterday_string = yesterday.strftime("%Y-%m-%d")
today_string = today
tomorrow_string = parsed_date + timedelta(days=1)
tomorrow_string = tomorrow_string.strftime("%Y-%m-%d")
if day_of_week == 4:
yesterday = parsed_date - timedelta(days=1)
yesterday_string = yesterday.strftime("%Y-%m-%d")
today_string = today
tomorrow_string = parsed_date + timedelta(days=1)
tomorrow_string = tomorrow_string.strftime("%Y-%m-%d")
if day_of_week == 5:
yesterday = parsed_date - timedelta(days=2)
yesterday_string = yesterday.strftime("%Y-%m-%d")
today_string = today
today_string = datetime.strptime(today_string, "%Y-%m-%d")
today_string = today_string - timedelta(days=1)
today_string = today_string.strftime("%Y-%m-%d")
tomorrow_string = parsed_date + timedelta(days=1)
tomorrow_string = tomorrow_string.strftime("%Y-%m-%d")
if day_of_week == 6:
yesterday = parsed_date - timedelta(days=3)
yesterday_string = yesterday.strftime("%Y-%m-%d")
today_string = today
today_string = datetime.strptime(today_string, "%Y-%m-%d")
today_string = today_string - timedelta(days=2)
today_string = today_string.strftime("%Y-%m-%d")
tomorrow_string = parsed_date + timedelta(days=1)
tomorrow_string = tomorrow_string.strftime("%Y-%m-%d")
class UserSelectedPrice:
def round_to_nearest_5_minutes(ist_time):
# Calculate the remainder of minutes when divided by 5
minutes_remainder = ist_time.minute % 5
# Subtract the remainder from the current minutes to round to the nearest 5 minutes
rounded_ist_time = ist_time - timedelta(minutes=minutes_remainder)
# Set seconds to 00
rounded_ist_time = rounded_ist_time.replace(second=0)
# Format the time with the desired format using str.format()
formatted_time = "{}-{:02d}-{:02d} {}:{}:{}".format(
rounded_ist_time.year,
rounded_ist_time.month,
rounded_ist_time.day,
rounded_ist_time.hour,
rounded_ist_time.minute,
rounded_ist_time.second,
)
return formatted_time
def convert_utc_to_ist(utc_time):
utc_time_str = utc_time.strftime("%Y-%m-%d %H:%M:%S")
utc_time = datetime.strptime(utc_time_str, "%Y-%m-%d %H:%M:%S")
utc_time = pytz.utc.localize(utc_time)
ist_time = utc_time.astimezone(pytz.timezone("Asia/Kolkata"))
return ist_time.strftime("%Y-%m-%d %H:%M:%S")
def custom_round(prices, symbol):
rounded_prices = []
for price in prices:
if symbol == "NIFTY":
last_two_digits = price % 100
if last_two_digits < 25:
rounded_price = (price // 100) * 100
elif last_two_digits < 75:
rounded_price = (price // 100) * 100 + 50
else:
rounded_price = (price // 100 + 1) * 100
elif symbol == "BANKNIFTY":
last_two_digits = price % 100
if last_two_digits < 50:
rounded_price = (price // 100) * 100
else:
rounded_price = (price // 100 + 1) * 100
else:
rounded_price = price # Handle the "else" case
rounded_prices.append(rounded_price)
return rounded_prices[0]
def combined_oi_calculation(
symbol,
instrument,
strikeprice,
option_type,
expiery,
today,
tomorrow,
):
engine = connection
df = pd.read_sql_query(
f"""
SELECT symbol, expiry_date, strike_price, created_at, ticker, instrument_name, option_type, open_interest FROM indiacharts.fno_prices fp
WHERE created_at > '{today}' AND created_at < '{tomorrow}'
AND symbol = '{symbol}' AND instrument_name = '{instrument}' AND strike_price = {strikeprice}
AND option_type = '{option_type}'
ORDER BY created_at ASC
""",
con=engine,
)
df["created_at_ist"] = df["created_at"].apply(UserSelectedPrice.convert_utc_to_ist)
df["created_at_ist"] = pd.to_datetime(df["created_at_ist"])
df["rounded_created_at_ist"] = df["created_at_ist"].apply(
UserSelectedPrice.round_to_nearest_5_minutes
)
# Group by rounded_created_at_ist and calculate the sum of open_interest
oi_sum_df = (
df.groupby("rounded_created_at_ist")["open_interest"].sum().reset_index()
)
df["rounded_created_at_ist"] = pd.to_datetime(df["rounded_created_at_ist"])
oi_sum_df["rounded_created_at_ist"] = pd.to_datetime(
oi_sum_df["rounded_created_at_ist"]
)
# Merge the DataFrames on 'rounded_created_at_ist'
merged_df = pd.merge(df, oi_sum_df, on="rounded_created_at_ist", how="left")
merged_df.rename(columns={"open_interest_y": "Combined OI"}, inplace=True)
merged_df["expiry_date"] = merged_df["expiry_date"].astype(str)
merged_df = merged_df[merged_df["expiry_date"] == expiery]
merged_df.to_csv(f'{symbol}_{strikeprice}_{option_type}_{expiery}.csv', index=False)
return merged_df
def get_historical_eod_data(
symbol, instrument, strikeprice, option_type, expiery, yesterday_string
):
engine = connection
df = pd.read_sql_query(
f"""select symbol,expiry_date,strike_price,created_at,ticker, instrument_name,option_type,open_interest from indiacharts.fno_price_eod fpe
WHERE created_at ='{yesterday_string}'
AND symbol = '{symbol}' AND instrument_name = '{instrument}' AND strike_price = {strikeprice}
AND option_type = '{option_type}'
ORDER BY created_at ASC
""",
con=engine,
)
# Calculate the sum of open_interest and add it as a new column
combined_oi_eod = df["open_interest"].sum()
df["Combined OI EOD"] = combined_oi_eod
df.to_csv(f'{symbol}_{strikeprice}_{option_type}_{expiery}_eod.csv', index=False)
return df
Comments
Post a Comment