File size: 5,807 Bytes
ae34fa6
 
 
a823289
 
ae34fa6
 
a823289
 
 
ae34fa6
a823289
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae34fa6
a823289
ae34fa6
a823289
 
ae34fa6
 
 
a823289
ae34fa6
 
a823289
ae34fa6
 
a823289
ae34fa6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a823289
ae34fa6
 
a823289
 
ae34fa6
a823289
 
 
 
 
 
 
 
 
ae34fa6
a823289
 
 
ae34fa6
a823289
 
ae34fa6
a823289
 
 
 
 
ae34fa6
a823289
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae34fa6
 
 
a823289
ae34fa6
 
 
 
 
 
 
 
 
 
 
 
 
a823289
ae34fa6
 
a823289
ae34fa6
 
a823289
 
 
ae34fa6
 
 
 
 
 
a823289
 
ae34fa6
 
a823289
 
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
import yfinance as yf
import pandas as pd
import streamlit as st
import requests
import json
from datetime import datetime, timedelta

# 🌟 Deepseek API Configuration
DEEPSEEK_API_KEY = "sk-d52b48c40d494fb88acee4e20e881240"
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/analyze"

# 🛠 Cache timeout set to 10 minutes (600 seconds) to reduce API calls
@st.cache_data(ttl=600)
def load_nifty50_symbols():
    """Load Nifty 50 and additional stocks categorized by sectors"""
    symbols = {
        "IT": ["TCS.NS", "INFY.NS", "HCLTECH.NS", "TECHM.NS", "WIPRO.NS", "MPHASIS.NS", "LTIM.NS"],
        "Banking & Finance": [
            "HDFCBANK.NS", "ICICIBANK.NS", "SBIN.NS", "AXISBANK.NS", "KOTAKBANK.NS",
            "BAJFINANCE.NS", "BAJAJFINSV.NS", "HDFC.NS", "INDUSINDBK.NS", "IDFCFIRSTB.NS", "PNB.NS"
        ],
        "Energy & Oil": ["RELIANCE.NS", "ONGC.NS", "POWERGRID.NS", "NTPC.NS", "BPCL.NS", "GAIL.NS", "IOC.NS"],
        "Automobile": ["TATAMOTORS.NS", "M&M.NS", "MARUTI.NS", "HEROMOTOCO.NS", "EICHERMOT.NS", "TVSMOTOR.NS"],
        "Consumer Goods": ["HINDUNILVR.NS", "ITC.NS", "NESTLEIND.NS", "BRITANNIA.NS", "TITAN.NS", "DABUR.NS"],
        "Metals & Mining": ["TATASTEEL.NS", "HINDALCO.NS", "JSWSTEEL.NS", "COALINDIA.NS", "NMDC.NS"],
        "Pharmaceuticals": ["SUNPHARMA.NS", "DRREDDY.NS", "CIPLA.NS", "DIVISLAB.NS", "LUPIN.NS"],
        "Infrastructure & Realty": ["LT.NS", "ADANIPORTS.NS", "ULTRACEMCO.NS", "SHREECEM.NS", "DLF.NS", "IRCTC.NS"],
        "Telecom": ["BHARTIARTL.NS", "IDEA.NS", "RELIANCE.NS"],
        "Others": ["ASIANPAINT.NS", "HDFCLIFE.NS", "SBILIFE.NS", "UPL.NS", "ADANIENT.NS", "DMART.NS"]
    }
    return symbols

@st.cache_data(ttl=600)
def fetch_stock_data(symbol, period='1y', interval="1d"):
    """Fetch stock data from Yahoo Finance"""
    try:
        stock = yf.Ticker(symbol)
        data = stock.history(period=period, interval=interval)
        return data
    except Exception as e:
        st.error(f"⚠️ Error fetching data for {symbol}: {str(e)}")
        return None

@st.cache_data(ttl=600)
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 analyze_with_deepseek(stock_symbol, data):
    """Send stock data to Deepseek AI for analysis and prediction"""
    try:
        if data is None or data.empty:
            return "⚠️ No data available for analysis."
        
        # Prepare payload
        payload = {
            "api_key": DEEPSEEK_API_KEY,
            "stock_symbol": stock_symbol,
            "historical_data": data.to_dict(orient="records"),
        }

        headers = {
            "Content-Type": "application/json"
        }

        response = requests.post(DEEPSEEK_API_URL, headers=headers, data=json.dumps(payload))
        response_data = response.json()

        if response.status_code == 200:
            return response_data.get("prediction", "No prediction available.")
        else:
            return f"⚠️ Error: {response_data.get('error', 'Unknown error occurred')}"
    
    except Exception as e:
        return f"⚠️ Deepseek API Error: {str(e)}"

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

def get_stock_suggestions(data):
    """Generate stock suggestions based on technical indicators and Deepseek AI"""
    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 a clear trend."

        deepseek_analysis = analyze_with_deepseek("Custom Data", data)

        return {
            'trend': trend,
            'suggestion': suggestion,
            'current_price': current_price,
            'sma20': sma20,
            'sma50': sma50,
            'deepseek_analysis': deepseek_analysis
        }
    except Exception as e:
        st.error(f"⚠️ Error generating suggestions: {str(e)}")
        return None