DagonGod / utils /data_loader.py
ratulsur's picture
Update utils/data_loader.py
a823289 verified
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