Spaces:
Running
Running
import streamlit as st | |
import yfinance as yf | |
import pandas as pd | |
from datetime import datetime, timedelta, time | |
import requests | |
from requests.adapters import HTTPAdapter | |
from urllib3.util.retry import Retry | |
# Define the list of ticker symbols for user selection | |
TICKER_SYMBOLS = [ | |
"AADHARHFC", "AARTIIND", "AAVAS", "ABBOTINDIA", "ACE", "ADANIENSOL", "ADANIENT", "ADANIGREEN", "ADANIPORTS", | |
"ADANIPOWER", "ATGL", "AWL", "ABCAPITAL", "ABFRL", "ABREL", "ABSLAMC", "AEGISLOG", "AFFLE", "AJANTPHARM", | |
"AKUMS", "APLLTD", "ALKEM", "ALKYLAMINE", "ALOKINDS", "AMBER", "AMBUJACEM", "ANANDRATHI", "ANANTRAJ", | |
"ANGELONE", "APARINDS", "APOLLOHOSP", "APOLLOTYRE", "APTUS", "ACI", "ASAHIINDIA", "ASHOKLEY", "ASIANPAINT", | |
"ASTERDM", "ASTRAZEN", "ASTRAL", "ATUL", "AUROPHARMA", "AVANTIFEED", "DMART", "AXISBANK", "BASF", "BEML", | |
"BLS", "BSE", "BAJAJ-AUTO", "BAJFINANCE", "BAJAJFINSV", "BAJAJHLDNG", "BALAMINES", "BALKRISIND", "BALRAMCHIN", | |
"BANDHANBNK", "BANKBARODA", "BANKINDIA", "MAHABANK", "BATAINDIA", "BAYERCROP", "BERGEPAINT", "BDL", "BEL", | |
"BHARATFORG", "BHEL", "BPCL", "BHARTIARTL", "BHARTIHEXA", "BIKAJI", "BIOCON", "BIRLACORPN", "BSOFT", | |
"BLUEDART", "BLUESTARCO", "BBTC", "BOSCHLTD", "BRIGADE", "BRITANNIA", "MAPMYINDIA", "CCL", "CESC", "CGPOWER", | |
"CIEINDIA", "CRISIL", "CAMPUS", "CANFINHOME", "CANBK", "CAPLIPOINT", "CGCL", "CARBORUNIV", "CASTROLIND", | |
"CEATLTD", "CELLO", "CENTRALBK", "CDSL", "CENTURYPLY", "CERA", "CHALET", "CHAMBLFERT", "CHEMPLASTS", | |
"CHENNPETRO", "CHOLAHLDNG", "CHOLAFIN", "CIPLA", "CUB", "CLEAN", "COALINDIA", "COCHINSHIP", "COFORGE", | |
"COLPAL", "CAMS", "CONCORDBIO", "CONCOR", "COROMANDEL", "CRAFTSMAN", "CREDITACC", "CROMPTON", "CUMMINSIND", | |
"CYIENT", "DLF", "DABUR", "DALBHARAT", "DATAPATTNS", "DEEPAKFERT", "DEEPAKNTR", "DELHIVERY", "DEVYANI", | |
"DIVISLAB", "DIXON", "LALPATHLAB", "DRREDDY", "EIDPARRY", "EIHOTEL", "EASEMYTRIP", "EICHERMOT", "ELECON", | |
"ELGIEQUIP", "EMAMILTD", "EMCURE", "ENDURANCE", "ENGINERSIN", "EQUITASBNK", "ERIS", "ESCORTS", "EXIDEIND", | |
"NYKAA", "FEDERALBNK", "FACT", "FINEORG", "FINCABLES", "FINPIPE", "FSL", "FORTIS", "GRINFRA", "GAIL", | |
"GMRINFRA", "GRSE", "GICRE", "GILLETTE", "GLAND", "GLAXO", "GLENMARK", "MEDANTA", "GODFRYPHLP", "GODREJAGRO", | |
"GODREJCP", "GODREJIND", "GODREJPROP", "GRANULES", "GRAPHITE", "GRASIM", "GESHIP", "GUJGASLTD", "GMDCLTD", | |
"GNFC", "GPPL", "GSFC", "GSPL", "HEG", "HBLPOWER", "HCLTECH", "HDFCAMC", "HDFCBANK", "HDFCLIFE", "HFCL", | |
"HAPPSTMNDS", "HAVELLS", "HEROMOTOCO", "HSCL", "HINDALCO", "HAL", "HINDCOPPER", "HINDPETRO", "HINDUNILVR", | |
"HINDZINC", "POWERINDIA", "ICICIBANK", "ICICIGI", "ICICIPRULI", "ISEC", "IDBI", "IDFCFIRSTB", "IFCI", "IIFL", | |
"INOXINDIA", "ITC", "ITI", "INDIACEM", "INDIANB", "INFY", "IRCTC", "INDIGO", "JINDALSTEL", "JSWSTEEL", "JUBLFOOD", | |
"KEC", "KPITTECH", "KOTAKBANK", "LTIM", "LICHSGFIN", "LUPIN", "MRF", "MGL", "M&M", "MARICO", "MARUTI", "MFSL", | |
"NESTLEIND", "ONGC", "PAYTM", "PNB", "RELIANCE", "SBIN", "SUNPHARMA", "TATACHEM", "TATAMOTORS", "TCS", "TITAN", | |
"UPL", "VEDL", "WIPRO", "YESBANK", "ZEEL", "ZOMATO", "ZYDUSLIFE" | |
] | |
# Streamlit App Title | |
st.title("Pivot Point Calculator for Indian Share Market") | |
# Ticker Selection | |
selected_ticker = st.selectbox("Select a Ticker Symbol", TICKER_SYMBOLS) | |
# Date input | |
start_date = st.date_input("Select Start Date for Historical Data") | |
end_date = st.date_input("Select End Date for Historical Data") | |
# Function to check if the market is open | |
def is_market_open(): | |
now = datetime.now().time() | |
market_open_time = time(9, 15) # NSE opens at 9:15 AM | |
market_close_time = time(15, 30) # NSE closes at 3:30 PM | |
return market_open_time <= now <= market_close_time | |
# Function to calculate pivot point and support/resistance levels | |
def calculate_pivot_levels(stock_data): | |
try: | |
high = stock_data['High'].iloc[-1] | |
low = stock_data['Low'].iloc[-1] | |
close = stock_data['Close'].iloc[-1] | |
pivot = (high + low + close) / 3 | |
resistance1 = (2 * pivot) - low | |
support1 = (2 * pivot) - high | |
resistance2 = pivot + (high - low) | |
support2 = pivot - (high - low) | |
resistance3 = high + 2 * (pivot - low) | |
support3 = low - 2 * (high - pivot) | |
levels = { | |
'Pivot Point': pivot, | |
'Resistance 1': resistance1, | |
'Support 1': support1, | |
'Resistance 2': resistance2, | |
'Support 2': support2, | |
'Resistance 3': resistance3, | |
'Support 3': support3 | |
} | |
return levels | |
except Exception as e: | |
st.error(f"Error calculating pivot levels: {str(e)}") | |
return None | |
# Function to fetch stock data with retry logic and proper error handling | |
# Cache for 5 minutes | |
def get_stock_data(symbol): | |
try: | |
nse_symbol = f"{symbol}.NS" | |
today = datetime.today().date() | |
# Set up a retry session to handle intermittent connection issues | |
session = requests.Session() | |
retries = Retry(total=5, backoff_factor=0.5, status_forcelist=[500, 502, 503, 504]) | |
session.mount('https://', HTTPAdapter(max_retries=retries)) | |
# Use the session to download data | |
stock = yf.download( | |
nse_symbol, | |
start=today - timedelta(days=5), | |
end=today + timedelta(days=1), | |
interval='1d', | |
progress=False, | |
session=session | |
) | |
if not stock.empty: | |
return stock.tail(1) | |
else: | |
st.warning("No data available for the selected stock.") | |
return pd.DataFrame() | |
except Exception as e: | |
st.error(f"Error fetching data for {symbol}: {str(e)}") | |
return pd.DataFrame() | |
# Load Data | |
if st.button("Calculate Pivot Points"): | |
if selected_ticker: | |
# Download historical data using yfinance | |
try: | |
data = get_stock_data(selected_ticker) | |
if not data.empty: | |
# Display historical data | |
st.subheader("Historical Data") | |
st.dataframe(data.tail()) | |
# Calculate pivot points and support/resistance levels | |
levels = calculate_pivot_levels(data) | |
if levels: | |
st.subheader(f"Pivot Point Calculations for {selected_ticker}") | |
for level_name, value in levels.items(): | |
st.write(f"{level_name}: {float(value):.2f}") | |
else: | |
st.error("No data available for the selected ticker and date range. Please try again.") | |
except Exception as e: | |
st.error(f"An error occurred: {e}") | |
else: | |
st.error("Please select a valid ticker symbol.") | |