File size: 5,508 Bytes
a5b6c6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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 = [
        # IT Sector
        "TCS.NS", "INFY.NS", "HCLTECH.NS", "TECHM.NS", "WIPRO.NS",

        # Banking & Finance
        "HDFCBANK.NS", "ICICIBANK.NS", "SBIN.NS", "AXISBANK.NS", "KOTAKBANK.NS",
        "BAJFINANCE.NS", "BAJAJFINSV.NS", "HDFC.NS", "INDUSINDBK.NS",

        # Energy & Oil
        "RELIANCE.NS", "ONGC.NS", "POWERGRID.NS", "NTPC.NS", "BPCL.NS",

        # Automobile
        "TATAMOTORS.NS", "M&M.NS", "MARUTI.NS", "HEROMOTOCO.NS", "EICHERMOT.NS",

        # Consumer Goods
        "HINDUNILVR.NS", "ITC.NS", "NESTLEIND.NS", "BRITANNIA.NS", "TITAN.NS",

        # Metals & Mining
        "TATASTEEL.NS", "HINDALCO.NS", "JSWSTEEL.NS", "COALINDIA.NS",

        # Pharmaceuticals
        "SUNPHARMA.NS", "DRREDDY.NS", "CIPLA.NS", "DIVISLAB.NS",

        # Infrastructure
        "LT.NS", "ADANIPORTS.NS", "ULTRACEMCO.NS", "SHREECEM.NS", "GRASIM.NS",

        # Telecommunications
        "BHARTIARTL.NS",

        # Others
        "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")

        # Ensure required columns exist
        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")

        # Convert Date column to datetime
        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:
        # Simple moving averages
        data['SMA20'] = data['Close'].rolling(window=20).mean()
        data['SMA50'] = data['Close'].rolling(window=50).mean()

        # Get latest values
        current_price = data['Close'].iloc[-1]
        sma20 = data['SMA20'].iloc[-1]
        sma50 = data['SMA50'].iloc[-1]

        # Generate suggestion
        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