Download app.py from erenmika/Scanner: direct link, hf CLI and curl.
- Browser
- Download file 9.84 kB
-
https://huggingface.co/spaces/erenmika/Scanner/resolve/main/app.py
- Command line
-
hf download hf://spaces/erenmika/Scanner/app.py
-
curl -L -o app.py https://huggingface.co/spaces/erenmika/Scanner/resolve/main/app.py
9.84 kB
| import streamlit as st | |
| import yfinance as yf | |
| import pandas as pd | |
| import sqlite3 | |
| from datetime import datetime, timedelta | |
| import time | |
| import numpy as np | |
| from streamlit_option_menu import option_menu | |
| import plotly.graph_objects as go | |
| # Initialize SQLite database | |
| def init_db(): | |
| conn = sqlite3.connect('stock_screener.db') | |
| c = conn.cursor() | |
| c.execute('''CREATE TABLE IF NOT EXISTS trades | |
| (symbol TEXT, entry_date TEXT, entry_price REAL, | |
| exit_date TEXT, exit_price REAL, status TEXT, | |
| profit_loss REAL)''') | |
| conn.commit() | |
| conn.close() | |
| # Calculate EMAs | |
| def calculate_emas(df): | |
| df['EMA20'] = df['Close'].ewm(span=20, adjust=False).mean() | |
| df['EMA50'] = df['Close'].ewm(span=50, adjust=False).mean() | |
| df['EMA34'] = df['Close'].ewm(span=34, adjust=False).mean() | |
| df['EMA89'] = df['Close'].ewm(span=89, adjust=False).mean() | |
| return df | |
| # Check EMA conditions | |
| def check_ema_conditions(daily_df, hourly_df): | |
| if len(daily_df) < 50 or len(hourly_df) < 89: | |
| return False | |
| daily_condition = daily_df['EMA20'].iloc[-1] > daily_df['EMA50'].iloc[-1] | |
| hourly_condition = hourly_df['EMA34'].iloc[-1] > hourly_df['EMA89'].iloc[-1] | |
| return daily_condition and hourly_condition | |
| # Stock Scanner | |
| def scan_stocks(): | |
| nifty50_stocks = [ | |
| "ADANIENT.NS", "ADANIPORTS.NS", "APOLLOHOSP.NS", "ASIANPAINT.NS", | |
| "AXISBANK.NS", "BAJAJ-AUTO.NS", "BAJFINANCE.NS", "BAJAJFINSV.NS", | |
| "BEL.NS", "BPCL.NS", "BHARTIARTL.NS", "BRITANNIA.NS", "CIPLA.NS", | |
| "COALINDIA.NS", "DRREDDY.NS", "EICHERMOT.NS", "GRASIM.NS", "HCLTECH.NS", | |
| "HDFCBANK.NS", "HDFCLIFE.NS", "HEROMOTOCO.NS", "HINDALCO.NS", | |
| "HINDUNILVR.NS", "ICICIBANK.NS", "ITCHOTELS.NS", "ITC.NS", | |
| "INDUSINDBK.NS", "INFY.NS", "JSWSTEEL.NS", "KOTAKBANK.NS", "LT.NS", | |
| "M&M.NS", "MARUTI.NS", "NTPC.NS", "NESTLEIND.NS", "ONGC.NS", | |
| "POWERGRID.NS", "RELIANCE.NS", "SBILIFE.NS", "SHRIRAMFIN.NS", | |
| "SBIN.NS", "SUNPHARMA.NS", "TCS.NS", "TATACONSUM.NS", "TATAMOTORS.NS", | |
| "TATASTEEL.NS", "TECHM.NS", "TITAN.NS", "TRENT.NS", "ULTRACEMCO.NS", | |
| "WIPRO.NS" | |
| ] | |
| signals = [] | |
| for stock in nifty50_stocks: | |
| try: | |
| # Get daily data | |
| daily_data = yf.download(stock, start=(datetime.now() - timedelta(days=100)).strftime('%Y-%m-%d')) | |
| daily_data = calculate_emas(daily_data) | |
| # Get hourly data | |
| hourly_data = yf.download(stock, start=(datetime.now() - timedelta(days=10)).strftime('%Y-%m-%d'), interval='1h') | |
| hourly_data = calculate_emas(hourly_data) | |
| if check_ema_conditions(daily_data, hourly_data): | |
| signals.append({ | |
| 'symbol': stock, | |
| 'price': daily_data['Close'].iloc[-1], | |
| 'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S') | |
| }) | |
| # Add to database if not already present | |
| conn = sqlite3.connect('stock_screener.db') | |
| c = conn.cursor() | |
| c.execute("SELECT * FROM trades WHERE symbol=? AND status='ACTIVE'", (stock,)) | |
| if not c.fetchone(): | |
| c.execute("""INSERT INTO trades (symbol, entry_date, entry_price, status, profit_loss) | |
| VALUES (?, ?, ?, 'ACTIVE', 0)""", | |
| (stock, datetime.now().strftime('%Y-%m-%d %H:%M:%S'), daily_data['Close'].iloc[-1])) | |
| conn.commit() | |
| conn.close() | |
| except Exception as e: | |
| st.error(f"Error processing {stock}: {str(e)}") | |
| continue | |
| return signals | |
| # Check for exit conditions | |
| def check_exits(): | |
| conn = sqlite3.connect('stock_screener.db') | |
| c = conn.cursor() | |
| c.execute("SELECT * FROM trades WHERE status='ACTIVE'") | |
| active_trades = c.fetchall() | |
| for trade in active_trades: | |
| symbol = trade[0] | |
| entry_price = trade[2] | |
| try: | |
| # Get current price | |
| current_price = yf.download(symbol, period='1d')['Close'].iloc[-1] | |
| profit_percentage = ((current_price - entry_price) / entry_price) * 100 | |
| # Check exit conditions | |
| daily_data = yf.download(symbol, start=(datetime.now() - timedelta(days=100)).strftime('%Y-%m-%d')) | |
| hourly_data = yf.download(symbol, start=(datetime.now() - timedelta(days=10)).strftime('%Y-%m-%d'), interval='1h') | |
| daily_data = calculate_emas(daily_data) | |
| hourly_data = calculate_emas(hourly_data) | |
| # Exit if EMAs cross negatively or take profit reached | |
| if (daily_data['EMA20'].iloc[-1] < daily_data['EMA50'].iloc[-1] or | |
| hourly_data['EMA34'].iloc[-1] < hourly_data['EMA89'].iloc[-1] or | |
| profit_percentage >= 5): | |
| c.execute("""UPDATE trades | |
| SET status='CLOSED', exit_date=?, exit_price=?, profit_loss=? | |
| WHERE symbol=? AND status='ACTIVE'""", | |
| (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), | |
| current_price, | |
| profit_percentage, | |
| symbol)) | |
| except Exception as e: | |
| st.error(f"Error checking exits for {symbol}: {str(e)}") | |
| continue | |
| conn.commit() | |
| conn.close() | |
| def main(): | |
| st.set_page_config(page_title="Stock Screener", layout="wide") | |
| # Initialize database | |
| init_db() | |
| # Navigation | |
| selected = option_menu( | |
| menu_title=None, | |
| options=["Dashboard", "Scanner", "Portfolio"], | |
| icons=["house", "search", "book"], | |
| menu_icon="cast", | |
| default_index=0, | |
| orientation="horizontal", | |
| ) | |
| if selected == "Dashboard": | |
| st.title("Trading Dashboard") | |
| # Get active trades | |
| conn = sqlite3.connect('stock_screener.db') | |
| active_trades_df = pd.read_sql("SELECT * FROM trades WHERE status='ACTIVE'", conn) | |
| closed_trades_df = pd.read_sql("SELECT * FROM trades WHERE status='CLOSED'", conn) | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| st.metric("Active Trades", len(active_trades_df)) | |
| with col2: | |
| total_profit = closed_trades_df['profit_loss'].sum() if not closed_trades_df.empty else 0 | |
| st.metric("Total Profit/Loss", f"{total_profit:.2f}%") | |
| with col3: | |
| win_rate = (len(closed_trades_df[closed_trades_df['profit_loss'] > 0]) / len(closed_trades_df) * 100 | |
| if not closed_trades_df.empty else 0) | |
| st.metric("Win Rate", f"{win_rate:.1f}%") | |
| # Active Trades Table | |
| st.subheader("Active Trades") | |
| if not active_trades_df.empty: | |
| st.dataframe(active_trades_df) | |
| else: | |
| st.info("No active trades at the moment.") | |
| # Recent Closed Trades | |
| st.subheader("Recent Closed Trades") | |
| if not closed_trades_df.empty: | |
| st.dataframe(closed_trades_df.tail(10)) | |
| else: | |
| st.info("No closed trades yet.") | |
| conn.close() | |
| elif selected == "Scanner": | |
| st.title("Stock Scanner") | |
| if st.button("Scan Now"): | |
| with st.spinner("Scanning stocks..."): | |
| signals = scan_stocks() | |
| check_exits() | |
| if signals: | |
| st.success(f"Found {len(signals)} signals!") | |
| st.write(pd.DataFrame(signals)) | |
| else: | |
| st.info("No new signals found.") | |
| # Add auto-refresh option | |
| auto_refresh = st.checkbox("Auto refresh every hour") | |
| if auto_refresh: | |
| time.sleep(3600) # Wait for 1 hour | |
| st.experimental_rerun() | |
| elif selected == "Portfolio": | |
| st.title("Portfolio Performance") | |
| conn = sqlite3.connect('stock_screener.db') | |
| trades_df = pd.read_sql("SELECT * FROM trades", conn) | |
| conn.close() | |
| # Portfolio Statistics | |
| st.subheader("Portfolio Statistics") | |
| col1, col2, col3, col4 = st.columns(4) | |
| closed_trades = trades_df[trades_df['status'] == 'CLOSED'] | |
| with col1: | |
| st.metric("Total Trades", len(trades_df)) | |
| with col2: | |
| total_profit = closed_trades['profit_loss'].sum() if not closed_trades.empty else 0 | |
| st.metric("Total Profit/Loss", f"{total_profit:.2f}%") | |
| with col3: | |
| avg_profit = closed_trades['profit_loss'].mean() if not closed_trades.empty else 0 | |
| st.metric("Average Profit/Loss per Trade", f"{avg_profit:.2f}%") | |
| with col4: | |
| win_rate = (len(closed_trades[closed_trades['profit_loss'] > 0]) / len(closed_trades) * 100 | |
| if not closed_trades.empty else 0) | |
| st.metric("Win Rate", f"{win_rate:.1f}%") | |
| # Profit/Loss Chart | |
| if not closed_trades.empty: | |
| st.subheader("Profit/Loss Distribution") | |
| fig = go.Figure(data=[go.Histogram(x=closed_trades['profit_loss'])]) | |
| fig.update_layout(title_text='Distribution of Trade Profits/Losses') | |
| st.plotly_chart(fig) | |
| else: | |
| st.info("No closed trades yet to display profit/loss distribution.") | |
| # Detailed Trade History | |
| st.subheader("Complete Trade History") | |
| if not trades_df.empty: | |
| st.dataframe(trades_df) | |
| else: | |
| st.info("No trades recorded yet.") | |
| if __name__ == "__main__": | |
| main() |