import streamlit as st import yfinance as yf import pandas as pd from datetime import datetime, timedelta import plotly.graph_objects as go # --------------------------- # Configuration and Constants # --------------------------- # Define Indian sectors and their corresponding prominent stocks SECTORS = { 'Information Technology': ['TCS.NS', 'INFY.NS', 'WIPRO.NS', 'HCLTECH.NS', 'TECHM.NS'], 'Pharmaceuticals': ['SUNPHARMA.NS', 'DRREDDY.NS', 'CIPLA.NS', 'BIOCON.NS', 'DIVISLAB.NS'], 'Banking': ['HDFCBANK.NS', 'ICICIBANK.NS', 'KOTAKBANK.NS', 'AXISBANK.NS', 'SBIN.NS'], 'Energy': ['RELIANCE.NS', 'ONGC.NS', 'IOC.NS', 'BPCL.NS', 'TATAMOTORS.NS'], 'Automobiles': ['MARUTI.NS', 'TATAMOTORS.NS', 'BAJAJ-AUTO.NS', 'M&M.NS', 'HEROMOTOCO.NS'], 'Consumer Goods': ['HINDUNILVR.NS', 'ITC.NS', 'NESTLEIND.NS', 'TATACONSUM.NS', 'DABUR.NS'], 'Financial Services': ['BAJAJFINSV.NS', 'HDFC.NS', 'AXISBANK.NS', 'ICICIPRULI.NS', 'INDUSINDBK.NS'], 'Metals': ['TATASTEEL.NS', 'JSWSTEEL.NS', 'HINDALCO.NS', 'SAIL.NS', 'JINDALSTEL.NS'], 'Telecommunication Services': ['BHARTIARTL.NS', 'RELIANCE.NS', 'TATACOMM.NS', 'VODAFONE-I.NS', 'IDEA.NS'], 'Real Estate': ['DLF.NS', 'PROPTIA.NS', 'OIL.NS', 'BRIGADE.NS', 'ANSALHSG.NS'] } COLORS = [ '#2E7D32', '#1976D2', '#C62828', '#F57C00', '#6A1B9A', '#283593', '#00838F', '#558B2F', '#D84315', '#4527A0', '#00695C' ] # --------------------------- # Utility Functions # --------------------------- def get_high_performing_stocks(sector, top_n=5, period='1mo'): """ Fetches and returns the top N high performing stocks in the specified sector over a given period. Parameters: sector (str): The sector name. top_n (int): Number of top performers to return. period (str): Time period for performance calculation (e.g., '1mo'). Returns: pd.DataFrame: DataFrame containing top N performing stocks. """ if sector not in SECTORS: st.error(f"No data available for sector: {sector}") return pd.DataFrame() tickers = SECTORS[sector] data = {} company_names = [] for ticker in tickers: stock = yf.Ticker(ticker) hist = stock.history(period=period) if not hist.empty and len(hist['Close']) >= 2: hist = hist.sort_index() latest_close = hist['Close'][-1] oldest_close = hist['Close'][0] performance = ((latest_close - oldest_close) / oldest_close) * 100 data[ticker] = performance info = stock.info company_names.append(info.get('shortName', 'N/A')) else: data[ticker] = 0.0 # Assign 0.0% if insufficient data company_names.append('N/A') # Create DataFrame df = pd.DataFrame(list(data.items()), columns=['Ticker', 'Performance (%)']) df['Company'] = company_names # Sort by performance descending df = df.sort_values(by='Performance (%)', ascending=False) # Return top N return df.head(top_n) # --------------------------- # Streamlit UI # --------------------------- def main(): st.title("📈 High Performing Shares by Sector") # Sector selection sector = st.selectbox("Select a Sector", list(SECTORS.keys())) # Performance period selection period = st.selectbox("Select Performance Period", ['1mo', '3mo', '6mo', '1y'], index=0) if st.button("Get Top Performers"): if sector: with st.spinner(f'Fetching top performers for {sector} sector over {period}...'): top_stocks = get_high_performing_stocks(sector, top_n=5, period=period) if not top_stocks.empty: st.subheader(f"Top 5 High Performing Stocks in {sector} Sector over {period}") st.dataframe(top_stocks[['Ticker', 'Company', 'Performance (%)']]) # Bar Chart fig = go.Figure(data=[ go.Bar( x=top_stocks['Ticker'], y=top_stocks['Performance (%)'], marker_color=COLORS[:len(top_stocks)] ) ]) fig.update_layout(title="Top Performing Stocks", xaxis_title="Ticker", yaxis_title="Performance (%)") st.plotly_chart(fig) else: st.warning("No high performing stocks found.") st.markdown("---") st.markdown("**Note:** This is a demonstration. In a production application, consider integrating a dynamic data source for sector stocks.") if __name__ == "__main__": main()