import yfinance as yf import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import streamlit as st # Step 1: Define a function to fetch real-time market data def fetch_data(ticker_symbol): ticker = yf.Ticker(ticker_symbol) data = ticker.history(period="1y") # Fetches 1 year of historical data return data # Step 2: Define a function to calculate technical indicators def calculate_indicators(df): # Calculate Moving Averages df['MA20'] = df['Close'].rolling(window=20).mean() df['MA50'] = df['Close'].rolling(window=50).mean() # Calculate RSI delta = df['Close'].diff(1) gain = (delta.where(delta > 0, 0)).rolling(window=14).mean() loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean() rs = gain / loss df['RSI'] = 100 - (100 / (1 + rs)) # Calculate MACD df['EMA12'] = df['Close'].ewm(span=12, adjust=False).mean() df['EMA26'] = df['Close'].ewm(span=26, adjust=False).mean() df['MACD'] = df['EMA12'] - df['EMA26'] df['Signal'] = df['MACD'].ewm(span=9, adjust=False).mean() # Calculate OBV df['OBV'] = (df['Volume'] * ((df['Close'] - df['Close'].shift(1)) > 0).astype(int) - df['Volume'] * ((df['Close'] - df['Close'].shift(1)) < 0).astype(int)).cumsum() return df # Step 3: Streamlit UI Setup for Stock Selection st.title("Indian Share Market Analysis") # Add a stock selector input box st.sidebar.header("Select Stock Ticker") ticker_symbol = st.sidebar.text_input("Enter Stock Ticker (e.g., RELIANCE.NS, ^NSEI)", "^NSEI") # Step 4: Fetch Data and Calculate Indicators nifty_data = fetch_data(ticker_symbol) nifty_data = calculate_indicators(nifty_data) # Step 5: Display Stock Data st.subheader(f"Data Overview for {ticker_symbol}") st.write(nifty_data.head()) # Step 6: Visualizations st.subheader(f"Close Price for {ticker_symbol}") fig, ax = plt.subplots(figsize=(12, 6)) sns.lineplot(x=nifty_data.index, y=nifty_data['Close']) st.pyplot(fig) st.subheader(f"Moving Averages and RSI for {ticker_symbol}") fig, ax = plt.subplots(figsize=(12, 6)) sns.lineplot(x=nifty_data.index, y=nifty_data['MA20'], label='MA20') sns.lineplot(x=nifty_data.index, y=nifty_data['MA50'], label='MA50') sns.lineplot(x=nifty_data.index, y=nifty_data['RSI'], label='RSI') plt.axhline(y=70, color='red', linestyle='--', label='Overbought (70)') plt.axhline(y=30, color='green', linestyle='--', label='Oversold (30)') plt.legend() plt.title("Moving Averages and RSI") st.pyplot(fig) # Step 7: Interactive Timeframe Selection and Alerts st.sidebar.subheader("Select Timeframe:") timeframes = ['1d', '5d', '1mo', '3mo', '6mo', '1y', '2y', '5y', '10y', 'ytd', 'max'] selected_timeframe = st.sidebar.selectbox('Timeframe', timeframes) st.sidebar.subheader("Set Alerts:") alert_type = st.sidebar.selectbox('Alert Type', ['Price', 'RSI']) alert_value = st.sidebar.number_input('Enter Alert Value') # Step 8: Run the Streamlit App (Note: Do not use st.run()) # Save as `app.py` and run it using `streamlit run app.py`