Spaces:
Sleeping
Sleeping
Download simple_app.py from pareshmishra/StockSignalAI: direct link, hf CLI and curl.
- Browser
- Download file 6.62 kB
-
https://huggingface.co/spaces/pareshmishra/StockSignalAI/resolve/main/simple_app.py
- Command line
-
hf download hf://spaces/pareshmishra/StockSignalAI/simple_app.py
-
curl -L -o simple_app.py https://huggingface.co/spaces/pareshmishra/StockSignalAI/resolve/main/simple_app.py
6.62 kB
| import streamlit as st | |
| import yfinance as yf | |
| import plotly.graph_objects as go | |
| from datetime import datetime, timedelta | |
| import warnings | |
| warnings.filterwarnings('ignore') | |
| # Configure page | |
| st.set_page_config( | |
| page_title="AI Stock Trading Signals", | |
| page_icon="π", | |
| layout="wide" | |
| ) | |
| def get_stock_data(symbol, period="3mo"): | |
| """Get stock data using yfinance""" | |
| try: | |
| ticker = yf.Ticker(symbol) | |
| data = ticker.history(period=period) | |
| return data | |
| except Exception as e: | |
| st.error(f"Error fetching data: {str(e)}") | |
| return None | |
| def get_live_price(stock_symbol): | |
| """Get live stock price""" | |
| try: | |
| # Try nsepython first | |
| try: | |
| import nsepython as nse | |
| stock_name = stock_symbol.replace('.NS', '') | |
| live_data = nse.equity_quote(stock_name) | |
| if live_data and 'lastPrice' in live_data: | |
| return float(live_data['lastPrice']) | |
| except: | |
| pass | |
| # Fallback to yfinance | |
| ticker = yf.Ticker(stock_symbol) | |
| data = ticker.history(period="1d", interval="1m") | |
| if not data.empty: | |
| return float(data['Close'].iloc[-1]) | |
| return None | |
| except Exception as e: | |
| st.warning(f"Could not fetch live price: {str(e)}") | |
| return None | |
| def create_simple_chart(stock_symbol): | |
| """Create simple price chart""" | |
| try: | |
| data = get_stock_data(stock_symbol, period="1mo") | |
| if data is None or data.empty: | |
| return None | |
| # Get last 30 days | |
| data = data.tail(30) | |
| fig = go.Figure() | |
| # Add candlestick chart | |
| fig.add_trace(go.Candlestick( | |
| x=data.index, | |
| open=data['Open'], | |
| high=data['High'], | |
| low=data['Low'], | |
| close=data['Close'], | |
| name='Price' | |
| )) | |
| # Add simple moving averages | |
| sma_20 = data['Close'].rolling(window=20).mean() | |
| sma_50 = data['Close'].rolling(window=50).mean() | |
| fig.add_trace(go.Scatter( | |
| x=data.index, | |
| y=sma_20, | |
| name='SMA 20', | |
| line=dict(color='orange', width=2) | |
| )) | |
| fig.add_trace(go.Scatter( | |
| x=data.index, | |
| y=sma_50, | |
| name='SMA 50', | |
| line=dict(color='blue', width=2) | |
| )) | |
| fig.update_layout( | |
| title=f"{stock_symbol} - Price Chart", | |
| xaxis_rangeslider_visible=False, | |
| height=600, | |
| yaxis_title="Price (βΉ)" | |
| ) | |
| return fig | |
| except Exception as e: | |
| st.error(f"Error creating chart: {str(e)}") | |
| return None | |
| def simple_trading_signal(stock_symbol): | |
| """Generate simple trading signal based on moving averages""" | |
| try: | |
| data = get_stock_data(stock_symbol, period="3mo") | |
| if data is None or data.empty: | |
| return None, "No data available" | |
| # Calculate simple moving averages | |
| current_price = data['Close'].iloc[-1] | |
| sma_20 = data['Close'].rolling(window=20).mean().iloc[-1] | |
| sma_50 = data['Close'].rolling(window=50).mean().iloc[-1] | |
| # Simple signal logic | |
| if current_price > sma_20 and sma_20 > sma_50: | |
| signal = "BUY" | |
| confidence = 0.75 | |
| elif current_price < sma_20 and sma_20 < sma_50: | |
| signal = "SELL" | |
| confidence = 0.75 | |
| else: | |
| signal = "HOLD" | |
| confidence = 0.60 | |
| return { | |
| 'signal': signal, | |
| 'confidence': confidence, | |
| 'current_price': current_price, | |
| 'sma_20': sma_20, | |
| 'sma_50': sma_50 | |
| }, None | |
| except Exception as e: | |
| return None, f"Error generating signal: {str(e)}" | |
| def main(): | |
| st.title("π Stock Trading Signals App") | |
| st.markdown("### NSE Stock Analysis (Simplified Version)") | |
| # Sidebar for stock selection | |
| st.sidebar.header("Stock Selection") | |
| # Stock options | |
| stock_options = { | |
| "Reliance Industries": "RELIANCE.NS", | |
| "Tata Consultancy Services": "TCS.NS", | |
| "Infosys": "INFY.NS" | |
| } | |
| selected_stock_name = st.sidebar.selectbox( | |
| "Choose a stock:", | |
| list(stock_options.keys()) | |
| ) | |
| selected_stock = stock_options[selected_stock_name] | |
| # Main content | |
| st.header("π Live Market Data") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| if st.button("π Get Live Price", type="primary"): | |
| live_price = get_live_price(selected_stock) | |
| if live_price: | |
| st.metric("Live Price (LTP)", f"βΉ{live_price:.2f}") | |
| else: | |
| st.warning("Could not fetch live price") | |
| # Trading signal section | |
| st.header("π― Trading Signal") | |
| if st.button("π Get Signal", type="primary"): | |
| signal_result, error = simple_trading_signal(selected_stock) | |
| if signal_result: | |
| signal = signal_result['signal'] | |
| confidence = signal_result['confidence'] | |
| # Display signal with color coding | |
| if signal == "BUY": | |
| st.success(f"π’ **{signal}** Signal") | |
| elif signal == "SELL": | |
| st.error(f"π΄ **{signal}** Signal") | |
| else: | |
| st.info(f"π‘ **{signal}** Signal") | |
| # Display metrics | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| st.metric("Confidence", f"{confidence:.1%}") | |
| with col2: | |
| st.metric("Current Price", f"βΉ{signal_result['current_price']:.2f}") | |
| with col3: | |
| st.metric("SMA 20", f"βΉ{signal_result['sma_20']:.2f}") | |
| else: | |
| st.error(f"Signal generation failed: {error}") | |
| # Chart section | |
| st.header("π Price Chart") | |
| if st.button("π Show Chart"): | |
| chart = create_simple_chart(selected_stock) | |
| if chart: | |
| st.plotly_chart(chart, use_container_width=True) | |
| # Information section | |
| st.header("βΉοΈ About This App") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.info("**Signal Logic:**\n- BUY: Price > SMA20 > SMA50\n- SELL: Price < SMA20 < SMA50\n- HOLD: Mixed signals") | |
| with col2: | |
| st.info("**Data Source:**\n- Yahoo Finance (yfinance)\n- NSE Python for live prices\n- 3 months historical data") | |
| if __name__ == "__main__": | |
| main() |