| import yfinance as yf |
| import pandas as pd |
| import streamlit as st |
| from datetime import datetime, timedelta |
| import io |
|
|
| @st.cache_data(ttl=3600) |
| def load_nifty50_symbols(): |
| """Load Nifty 50 symbols""" |
| symbols = [ |
| |
| "TCS.NS", "INFY.NS", "HCLTECH.NS", "TECHM.NS", "WIPRO.NS", |
|
|
| |
| "HDFCBANK.NS", "ICICIBANK.NS", "SBIN.NS", "AXISBANK.NS", "KOTAKBANK.NS", |
| "BAJFINANCE.NS", "BAJAJFINSV.NS", "HDFC.NS", "INDUSINDBK.NS", |
|
|
| |
| "RELIANCE.NS", "ONGC.NS", "POWERGRID.NS", "NTPC.NS", "BPCL.NS", |
|
|
| |
| "TATAMOTORS.NS", "M&M.NS", "MARUTI.NS", "HEROMOTOCO.NS", "EICHERMOT.NS", |
|
|
| |
| "HINDUNILVR.NS", "ITC.NS", "NESTLEIND.NS", "BRITANNIA.NS", "TITAN.NS", |
|
|
| |
| "TATASTEEL.NS", "HINDALCO.NS", "JSWSTEEL.NS", "COALINDIA.NS", |
|
|
| |
| "SUNPHARMA.NS", "DRREDDY.NS", "CIPLA.NS", "DIVISLAB.NS", |
|
|
| |
| "LT.NS", "ADANIPORTS.NS", "ULTRACEMCO.NS", "SHREECEM.NS", "GRASIM.NS", |
|
|
| |
| "BHARTIARTL.NS", |
|
|
| |
| "ASIANPAINT.NS", "HDFCLIFE.NS", "SBILIFE.NS", "UPL.NS", "ADANIENT.NS", |
| "BAJAJ-AUTO.NS", "APOLLOHOSP.NS", "DMART.NS", "PIDILITIND.NS" |
| ] |
| return symbols |
|
|
| @st.cache_data(ttl=3600) |
| def load_market_indices(): |
| """Load major Indian market indices""" |
| indices = { |
| "NIFTY 50": "^NSEI", |
| "SENSEX": "^BSESN", |
| "BANK NIFTY": "^NSEBANK", |
| "NIFTY IT": "NIFTYIT.NS", |
| "NIFTY PHARMA": "NIFTYPHARMA.NS", |
| "NIFTY AUTO": "NIFTYAUTO.NS", |
| "NIFTY FMCG": "NIFTYFMCG.NS", |
| "NIFTY METAL": "NIFTYMETAL.NS", |
| "BSE 500": "^BSEFTY", |
| "NSE 500": "NIFTY500.NS" |
| } |
| return indices |
|
|
| def process_uploaded_file(uploaded_file): |
| """Process uploaded CSV/Excel file""" |
| try: |
| if uploaded_file.name.endswith('.csv'): |
| df = pd.read_csv(uploaded_file) |
| elif uploaded_file.name.endswith(('.xls', '.xlsx')): |
| df = pd.read_excel(uploaded_file) |
| else: |
| raise ValueError("Unsupported file format") |
|
|
| |
| required_columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume'] |
| if not all(col in df.columns for col in required_columns): |
| raise ValueError("Missing required columns") |
|
|
| |
| df['Date'] = pd.to_datetime(df['Date']) |
| return df |
| except Exception as e: |
| st.error(f"Error processing file: {str(e)}") |
| return None |
|
|
| @st.cache_data(ttl=3600) |
| def fetch_stock_data(symbol, period='1y'): |
| """Fetch stock data from Yahoo Finance""" |
| try: |
| stock = yf.Ticker(symbol) |
| data = stock.history(period=period) |
| return data |
| except Exception as e: |
| st.error(f"Error fetching data for {symbol}: {str(e)}") |
| return None |
|
|
| @st.cache_data(ttl=3600) |
| def get_stock_info(symbol): |
| """Get stock information""" |
| try: |
| stock = yf.Ticker(symbol) |
| info = stock.info |
| return { |
| 'name': info.get('longName', symbol), |
| 'sector': info.get('sector', 'N/A'), |
| 'market_cap': info.get('marketCap', 0), |
| 'pe_ratio': info.get('trailingPE', 0), |
| 'volume': info.get('volume', 0), |
| 'recommendation': info.get('recommendationKey', 'N/A'), |
| 'target_price': info.get('targetMeanPrice', 0) |
| } |
| except Exception as e: |
| st.error(f"Error fetching info for {symbol}: {str(e)}") |
| return None |
|
|
| def get_market_summary(): |
| """Get market summary for indices""" |
| try: |
| indices = load_market_indices() |
| summaries = {} |
|
|
| for name, symbol in indices.items(): |
| ticker = yf.Ticker(symbol) |
| data = ticker.history(period='1d') |
|
|
| if not data.empty: |
| summaries[name] = { |
| 'index_value': data['Close'].iloc[-1], |
| 'change': data['Close'].iloc[-1] - data['Open'].iloc[0], |
| 'change_percent': ((data['Close'].iloc[-1] - data['Open'].iloc[0]) / data['Open'].iloc[0]) * 100 |
| } |
|
|
| return summaries |
| except Exception as e: |
| st.error(f"Error fetching market summary: {str(e)}") |
| return None |
|
|
| def get_stock_suggestions(data): |
| """Generate stock suggestions based on technical indicators""" |
| try: |
| |
| data['SMA20'] = data['Close'].rolling(window=20).mean() |
| data['SMA50'] = data['Close'].rolling(window=50).mean() |
|
|
| |
| current_price = data['Close'].iloc[-1] |
| sma20 = data['SMA20'].iloc[-1] |
| sma50 = data['SMA50'].iloc[-1] |
|
|
| |
| if sma20 > sma50: |
| trend = "BULLISH" |
| suggestion = "Consider buying. Price is above moving averages." |
| elif sma20 < sma50: |
| trend = "BEARISH" |
| suggestion = "Consider selling. Price is below moving averages." |
| else: |
| trend = "NEUTRAL" |
| suggestion = "Market is sideways. Wait for clear trend." |
|
|
| return { |
| 'trend': trend, |
| 'suggestion': suggestion, |
| 'current_price': current_price, |
| 'sma20': sma20, |
| 'sma50': sma50 |
| } |
| except Exception as e: |
| st.error(f"Error generating suggestions: {str(e)}") |
| return None |