import yfinance as yf import pandas as pd import gradio as gr import plotly.graph_objects as go from datetime import datetime, timedelta import concurrent.futures import requests from bs4 import BeautifulSoup from transformers import pipeline # Initialize the GPT-2 pipeline for text generation gemma_pipeline = pipeline("text-generation", model="gpt2") # Function to load Nifty 500 symbols def load_nifty500_symbols(): try: df = pd.read_csv('ind_nifty500list.csv') return df['Symbol'].tolist() except FileNotFoundError: print("Nifty 500 list CSV file not found. Using a sample list of symbols.") return ['RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK', 'HINDUNILVR', 'SBIN', 'BHARTIARTL', 'ITC', 'KOTAKBANK'] # Function to get the latest stock data def get_latest_data(ticker_symbol): ticker_symbol_nse = ticker_symbol.upper() + ".NS" try: stock = yf.Ticker(ticker_symbol_nse) data = stock.history(period="1d") if data.empty: raise ValueError("No data available for this ticker.") return data.tail(1) except Exception as e: print(f"Error fetching data for {ticker_symbol_nse}: {e}") return pd.DataFrame() # Function to get stock information def get_stock_info(ticker_symbol): if not ticker_symbol: return "Please select a stock symbol." data = get_latest_data(ticker_symbol) if data.empty: return f"No data available for {ticker_symbol.upper()}.NS" current_price = data['Close'].iloc[0] previous_close = data['Open'].iloc[0] open_price = data['Open'].iloc[0] day_high = data['High'].iloc[0] day_low = data['Low'].iloc[0] volume = data['Volume'].iloc[0] return f""" Stock: {ticker_symbol.upper()}.NS Current Price: ₹{current_price:.2f} Previous Close: ₹{previous_close:.2f} Open: ₹{open_price:.2f} Day High: ₹{day_high:.2f} Day Low: ₹{day_low:.2f} Volume: {volume:,} """ # Function to get historical stock data with support for various intervals def get_historical_data(ticker_symbol, period='1mo', interval='1d'): if not ticker_symbol: return pd.DataFrame() ticker_symbol_nse = ticker_symbol.upper() + ".NS" try: if period == '1d': end_date = datetime.now() start_date = end_date - timedelta(days=1) data = yf.download(ticker_symbol_nse, start=start_date, end=end_date, interval='1m') else: data = yf.download(ticker_symbol_nse, period=period, interval=interval) if data.empty: raise ValueError("No historical data available for this ticker.") return data except Exception as e: print(f"Error fetching historical data for {ticker_symbol}: {e}") return pd.DataFrame() # Function to calculate technical indicators def calculate_technical_indicators(data): if data.empty: return data # Calculate RSI delta = data['Close'].diff() gain = (delta.where(delta > 0, 0)).rolling(window=14).mean() loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean() rs = gain / loss data['RSI'] = 100 - (100 / (1 + rs)) # Calculate MACD data['EMA12'] = data['Close'].ewm(span=12, adjust=False).mean() data['EMA26'] = data['Close'].ewm(span=26, adjust=False).mean() data['MACD'] = data['EMA12'] - data['EMA26'] data['Signal_Line'] = data['MACD'].ewm(span=9, adjust=False).mean() # Calculate Bollinger Bands data['MA20'] = data['Close'].rolling(window=20).mean() data['UpperBB'] = data['MA20'] + (data['Close'].rolling(window=20).std() * 2) data['LowerBB'] = data['MA20'] - (data['Close'].rolling(window=20).std() * 2) # Calculate Exponential Moving Averages data['EMA50'] = data['Close'].ewm(span=50, adjust=False).mean() data['EMA200'] = data['Close'].ewm(span=200, adjust=False).mean() # Calculate Stochastic Oscillator data['L14'] = data['Low'].rolling(window=14).min() data['H14'] = data['High'].rolling(window=14).max() data['%K'] = 100 * ((data['Close'] - data['L14']) / (data['H14'] - data['L14'])) data['%D'] = data['%K'].rolling(window=3).mean() return data # Function to plot stock chart with technical indicators def plot_stock_chart(ticker_symbol, period='1mo', interval='1d'): data = get_historical_data(ticker_symbol, period, interval) data = calculate_technical_indicators(data) if data.empty: return None fig = go.Figure() fig.add_trace(go.Candlestick( x=data.index, open=data['Open'], high=data['High'], low=data['Low'], close=data['Close'], name='Candlesticks' )) fig.add_trace(go.Scatter(x=data.index, y=data['MA20'], mode='lines', name='MA20')) fig.add_trace(go.Scatter(x=data.index, y=data['UpperBB'], mode='lines', name='Upper BB')) fig.add_trace(go.Scatter(x=data.index, y=data['LowerBB'], mode='lines', name='Lower BB')) fig.add_trace(go.Scatter(x=data.index, y=data['EMA50'], mode='lines', name='EMA50')) fig.add_trace(go.Scatter(x=data.index, y=data['EMA200'], mode='lines', name='EMA200')) fig.update_layout(title=f'{ticker_symbol.upper()}.NS Stock Price', xaxis_title='Date', yaxis_title='Price (₹)') return fig # Function to get news for a stock def get_stock_news(ticker_symbol): if not ticker_symbol: return "Please select a stock symbol." url = f"https://finance.yahoo.com/quote/{ticker_symbol}.NS/news" headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'} try: response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') news_items = soup.find_all('h3', class_='Mb(5px)') if not news_items: return f"No recent news found for {ticker_symbol.upper()}.NS" news_list = [] for item in news_items[:5]: # Get the top 5 news items news_list.append(item.text) return "\n\n".join(news_list) except Exception as e: print(f"Error fetching news for {ticker_symbol}: {e}") return f"Unable to fetch news for {ticker_symbol.upper()}.NS" # Function to generate trading suggestions def generate_trading_suggestion(data): if data.empty: return "No trading suggestion available.", 0, 0 current_price = data['Close'].iloc[-1] rsi = data['RSI'].iloc[-1] macd = data['MACD'].iloc[-1] signal_line = data['Signal_Line'].iloc[-1] upper_bb = data['UpperBB'].iloc[-1] lower_bb = data['LowerBB'].iloc[-1] suggestion = "Hold" target = current_price stop_loss = current_price if rsi > 70 or current_price > upper_bb or (macd < signal_line and macd > 0): suggestion = "Sell" target = current_price * 0.95 # 5% below current price stop_loss = current_price * 1.02 # 2% above current price elif rsi < 30 or current_price < lower_bb or (macd > signal_line and macd < 0): suggestion = "Buy" target = current_price * 1.05 # 5% above current price stop_loss = current_price * 0.98 # 2% below current price return suggestion, target, stop_loss # Function to get top 5 stocks recommendations def get_top_5_recommendations(): all_symbols = load_nifty500_symbols() recommendations = [] def analyze_stock(symbol): try: data = get_historical_data(symbol, period='1mo', interval='1d') if not data.empty: data = calculate_technical_indicators(data) current_price = data['Close'].iloc[-1] rsi = data['RSI'].iloc[-1] macd = data['MACD'].iloc[-1] signal_line = data['Signal_Line'].iloc[-1] ema50 = data['EMA50'].iloc[-1] ema200 = data['EMA200'].iloc[-1] score = 0 if rsi < 30: score += 1 elif rsi > 70: score -= 1 if macd > signal_line: score += 1 else: score -= 1 if ema50 > ema200: score += 1 else: score -= 1 return symbol, current_price, score except Exception as e: print(f"Error analyzing {symbol}: {e}") return None with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: results = list(executor.map(analyze_stock, all_symbols)) recommendations = [r for r in results if r is not None] recommendations.sort(key=lambda x: x[2], reverse=True) buy_recommendations = recommendations[:5] sell_recommendations = recommendations[-5:][::-1] return buy_recommendations, sell_recommendations # generate_summary function def generate_summary(info, news, trading_advice): try: prompt = f""" Summarize the following stock information and provide insights: Stock Information: {info} Recent News: {news} Trading Advice: {trading_advice} Summary: """ response = gemma_pipeline(prompt, max_length=300, num_return_sequences=1) summary = response[0]['generated_text'] return summary except Exception as e: return f"Error generating AI summary: {e}" # Function to analyze stock and provide recommendation def analyze_stock(ticker_symbol, period, interval): if not ticker_symbol: return "Please select a stock symbol.", None, "Please select a stock symbol.", "Please select a stock symbol.", "No recommendations available.", "No summary available." info = get_stock_info(ticker_symbol) historical_data = get_historical_data(ticker_symbol, period, interval) if historical_data.empty: return f"No historical data available for {ticker_symbol.upper()}.NS", None, None, None, "No recommendations available.", "No summary available." historical_data = calculate_technical_indicators(historical_data) chart = plot_stock_chart(ticker_symbol, period, interval) news = get_stock_news(ticker_symbol) suggestion, target, stop_loss = generate_trading_suggestion(historical_data) current_price = historical_data['Close'].iloc[-1] trading_advice = f""" Trading Suggestion: {suggestion} Current Price: ₹{current_price:.2f} Target Price: ₹{target:.2f} ({((target - current_price) / current_price * 100):.2f}% {'profit' if suggestion == 'Buy' else 'loss'}) Stop-Loss: ₹{stop_loss:.2f} ({((stop_loss - current_price) / current_price * 100):.2f}% {'loss' if suggestion == 'Buy' else 'profit'}) """ buy_recommendations, sell_recommendations = get_top_5_recommendations() recommendations = "Top 5 Buy Recommendations:\n" + "\n".join([f"{symbol}: ₹{price:.2f} (Score: {score})" for symbol, price, score in buy_recommendations]) recommendations += "\n\nTop 5 Sell Recommendations:\n" + "\n".join([f"{symbol}: ₹{price:.2f} (Score: {score})" for symbol, price, score in sell_recommendations]) # Generate summary using Gemma summary = generate_summary(info, news, trading_advice) return info, chart, news, trading_advice, recommendations, summary # Function to create the Gradio interface def create_interface(): with gr.Blocks() as iface: gr.Markdown("# Indian Stock Market Analysis Tool") gr.Markdown("Analyze NSE stocks with historical data, technical indicators, news, trading suggestions, and AI-generated summary.") with gr.Row(): ticker_input = gr.Dropdown(choices=[""] + load_nifty500_symbols(), label="Select NSE Stock Symbol", info="Example: RELIANCE, TCS") period_input = gr.Radio(["1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max"], label="Select Historical Data Period", value="1mo") with gr.Row(): interval_input = gr.Dropdown(choices=["1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d", "5d", "1wk", "1mo", "3mo"], label="Select Historical Data Interval", value="1d") analyze_button = gr.Button("Analyze Stock") with gr.Row(): info_output = gr.Textbox(label="Stock Information") chart_output = gr.Plot(label="Stock Chart") with gr.Row(): news_output = gr.Textbox(label="Recent News") advice_output = gr.Textbox(label="Trading Advice") recommendations_output = gr.Textbox(label="Top 5 Buy/Sell Recommendations") summary_output = gr.Textbox(label="AI-Generated Summary") # Dynamic update of interval options based on selected period def update_interval_options(period): if period in ['1d', '5d']: return {"choices": ["1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h"], "value": "5m"} elif period in ['1mo', '3mo']: return {"choices": ["1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d"], "value": "1d"} else: return {"choices": ["1d", "5d", "1wk", "1mo", "3mo"], "value": "1d"} # Connect the dynamic update function period_input.change(fn=update_interval_options, inputs=[period_input], outputs=[interval_input]) # Connect the analyze function to the interface analyze_button.click( fn=analyze_stock, inputs=[ticker_input, period_input, interval_input], outputs=[info_output, chart_output, news_output, advice_output, recommendations_output, summary_output] ) return iface # Launch the interface if __name__ == "__main__": iface = create_interface() iface.launch()