Spaces:
Sleeping
Sleeping
import streamlit as st | |
import yfinance as yf | |
import pandas as pd | |
from datetime import datetime, timedelta, time | |
# Load ticker symbols from the CSV file | |
# Updated from st.cache to remove deprecation warning | |
def load_ticker_list(file_path): | |
try: | |
stock_df = pd.read_csv(file_path) | |
return stock_df['Symbol'].tolist() | |
except Exception as e: | |
st.error(f"Error loading ticker list: {str(e)}") | |
return [] | |
# 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: | |
# Fixed the float() deprecation warnings by using .iloc[0] | |
high = stock_data['High'].iloc[-1] | |
low = stock_data['Low'].iloc[-1] | |
close = stock_data['Close'].iloc[-1] | |
# Calculate pivot point | |
pivot = (high + low + close) / 3 | |
# Calculate support and resistance levels | |
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 proper error handling | |
# Cache for 5 minutes | |
def get_stock_data(symbol): | |
try: | |
# Add .NS suffix for NSE stocks | |
nse_symbol = f"{symbol}.NS" | |
# Try to get today's data | |
today = datetime.today().date() | |
stock = yf.download( | |
nse_symbol, | |
start=today - timedelta(days=5), # Get more days of data | |
end=today + timedelta(days=1), | |
interval='1d', | |
progress=False # Disable progress bar | |
) | |
if not stock.empty: | |
return stock.tail(1) # Return only the latest day's data | |
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() | |
# Streamlit UI | |
def main(): | |
st.title("Support and Resistance Level Calculator for NIFTY 500 Stocks") | |
# Load ticker symbols | |
file_path = "G:/RSI/ind_nifty500list (1) (1).csv" | |
ticker_list = load_ticker_list(file_path) | |
if not ticker_list: | |
st.error("Failed to load ticker list. Please check the file path.") | |
return | |
# Select a ticker from the list | |
symbol = st.selectbox("Select a Stock Symbol", ticker_list) | |
# Check market status | |
if is_market_open(): | |
st.warning("Market is currently open. Data might not be finalized until after 3:30 PM.") | |
if symbol: | |
# Add a refresh button | |
col1, col2 = st.columns([1, 4]) | |
with col1: | |
refresh = st.button("🔄 Refresh") | |
# Display loading spinner | |
with st.spinner('Fetching stock data...'): | |
if refresh: | |
# Clear cache for this stock | |
get_stock_data.clear() | |
stock_data = get_stock_data(symbol) | |
if not stock_data.empty: | |
# Calculate and display levels | |
levels = calculate_pivot_levels(stock_data) | |
if levels: | |
# Fixed: Get current price as a scalar value | |
current_price = float(stock_data['Close'].iloc[-1]) | |
st.metric("Current Price", f"₹{current_price:.2f}") | |
# Create three columns for better organization | |
st.subheader(f"Support and Resistance Levels for {symbol}") | |
col1, col2, col3 = st.columns(3) | |
# Display resistance levels | |
with col1: | |
st.write("### Resistance Levels") | |
for i in range(3, 0, -1): | |
value = float(levels[f'Resistance {i}']) # Convert to float | |
st.write(f"R{i}: ₹{value:.2f}") | |
# Display pivot point | |
with col2: | |
st.write("### Pivot Point") | |
value = float(levels['Pivot Point']) # Convert to float | |
st.write(f"PP: ₹{value:.2f}") | |
# Display support levels | |
with col3: | |
st.write("### Support Levels") | |
for i in range(1, 4): | |
value = float(levels[f'Support {i}']) # Convert to float | |
st.write(f"S{i}: ₹{value:.2f}") | |
else: | |
st.error("Failed to fetch stock data. Please try again later.") | |
if __name__ == "__main__": | |
main() |