from datetime import datetime, timedelta import pandas as pd from db.db_connection import create_client from indicators.sunny_bands import SunnyBands def get_interval_choice() -> str: """Get user's preferred time interval""" print("\nSelect Time Interval:") print("1. Daily") print("2. 5 minute") print("3. 15 minute") print("4. 30 minute") print("5. 1 hour") while True: choice = input("\nEnter your choice (1-5): ") if choice == "1": return "daily" elif choice == "2": return "5min" elif choice == "3": return "15min" elif choice == "4": return "30min" elif choice == "5": return "1hour" else: print("Invalid choice. Please try again.") def get_stock_data(ticker: str, start_date: datetime, end_date: datetime, interval: str) -> pd.DataFrame: """Fetch stock data from the database""" client = create_client() # Always look back 60 days for proper DMA calculation today = datetime.now().date() start_date = today - timedelta(days=60) if interval == "daily": table = "stock_prices_daily" date_col = "date" query = f""" SELECT {date_col} as date, open, high, low, close, volume FROM stock_db.{table} WHERE ticker = '{ticker}' AND {date_col} BETWEEN '{start_date}' AND '{today}' ORDER BY date ASC """ else: table = "stock_prices" date_col = "window_start" minutes_map = { "5min": 5, "15min": 15, "30min": 30, "1hour": 60 } minutes = minutes_map[interval] # Get 5-minute bars and resample them to the desired interval query = f""" SELECT fromUnixTimestamp(intDiv({date_col}, 300) * 300) as interval_start, min(open) as open, max(high) as high, min(low) as low, argMax(close, {date_col}) as close, sum(volume) as volume FROM stock_db.{table} WHERE ticker = '{ticker}' AND {date_col} BETWEEN toUnixTimestamp('{start_date}') AND toUnixTimestamp('{today}') GROUP BY interval_start ORDER BY interval_start ASC """ try: result = client.query(query) if not result.result_rows: print(f"No data found for {ticker}") return pd.DataFrame() df = pd.DataFrame( result.result_rows, columns=['date', 'open', 'high', 'low', 'close', 'volume'] ) if interval != "daily" and interval != "5min": # Resample to desired interval df.set_index('date', inplace=True) minutes = minutes_map[interval] rule = f'{minutes}T' df = df.resample(rule).agg({ 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum' }).dropna() df.reset_index(inplace=True) return df except Exception as e: print(f"Error fetching data for {ticker}: {str(e)}") return pd.DataFrame() def get_valid_tickers(min_price: float, max_price: float, min_volume: int, interval: str) -> list: """Get tickers that meet the price and volume criteria""" client = create_client() yesterday = (datetime.now() - timedelta(days=1)).date() # First get valid tickers from daily data daily_query = f""" SELECT DISTINCT ticker FROM stock_db.stock_prices_daily WHERE date = '{yesterday}' AND close BETWEEN {min_price} AND {max_price} AND volume >= {min_volume} ORDER BY ticker ASC """ try: result = client.query(daily_query) tickers = [row[0] for row in result.result_rows] print(f"\nFound {len(tickers)} stocks matching price and volume criteria") if interval != "daily": # Now verify these tickers have intraday data in the last trading day # Get the most recent trading day's timestamp range today = datetime.now().date() yesterday_open = int(datetime.combine(yesterday, datetime.strptime("09:30", "%H:%M").time()).timestamp()) yesterday_close = int(datetime.combine(yesterday, datetime.strptime("16:00", "%H:%M").time()).timestamp()) today_open = int(datetime.combine(today, datetime.strptime("09:30", "%H:%M").time()).timestamp()) today_close = int(datetime.combine(today, datetime.strptime("16:00", "%H:%M").time()).timestamp()) intraday_query = f""" SELECT DISTINCT ticker FROM stock_db.stock_prices WHERE ticker IN ({','.join([f"'{t}'" for t in tickers])}) AND ( (window_start BETWEEN {yesterday_open} AND {yesterday_close}) OR (window_start BETWEEN {today_open} AND {today_close}) ) GROUP BY ticker HAVING count() >= 10 -- Ensure we have enough data points """ result = client.query(intraday_query) tickers = [row[0] for row in result.result_rows] print(f"Of those, {len(tickers)} have recent intraday data") return tickers except Exception as e: print(f"Error fetching tickers: {str(e)}") return [] def view_stock_details(ticker: str, interval: str, start_date: datetime, end_date: datetime) -> None: """Display detailed data for a single stock""" print(f"\nšŸ“Š Detailed Analysis for {ticker}") print(f"Interval: {interval}") print(f"Date Range: {start_date.date()} to {end_date.date()}") try: # Get price data df = get_stock_data(ticker, start_date, end_date, interval) if df.empty: print("No data found for this stock") return print("\nData Sample:") print("First 5 rows:") print(df.head().to_string()) print("\nLast 5 rows:") print(df.tail().to_string()) print(f"\nTotal rows: {len(df)}") # Calculate SunnyBands sunny = SunnyBands() results = sunny.calculate(df) # Get last values last_price = df.iloc[-1] last_bands = results.iloc[-1] print("\nLatest Values:") print(f"Date: {last_price['date']}") print(f"Open: ${last_price['open']:.2f}") print(f"High: ${last_price['high']:.2f}") print(f"Low: ${last_price['low']:.2f}") print(f"Close: ${last_price['close']:.2f}") print(f"Volume: {last_price['volume']:,}") print(f"\nSunnyBands Indicators:") print(f"DMA: ${last_bands['dma']:.2f}") print(f"Upper Band: ${last_bands['upper_band']:.2f}") print(f"Lower Band: ${last_bands['lower_band']:.2f}") print(f"Bullish Signal: {'Yes' if last_bands['bullish_signal'] else 'No'}") print(f"Bearish Signal: {'Yes' if last_bands['bearish_signal'] else 'No'}") except Exception as e: print(f"Error analyzing {ticker}: {str(e)}") def run_sunny_scanner(min_price: float, max_price: float, min_volume: int) -> None: """Run the SunnyBand scanner and save results""" print(f"\nInitializing scan for stocks between ${min_price:.2f} and ${max_price:.2f}") print(f"Minimum volume: {min_volume:,}") # Get user's preferred interval interval = get_interval_choice() # Set date range to 60 days for proper DMA calculation end_date = datetime.now() start_date = end_date - timedelta(days=60) print(f"\nAnalyzing data from {start_date.date()} to {end_date.date()}") # Get valid tickers print("\nFetching qualified stocks...") tickers = get_valid_tickers(min_price, max_price, min_volume, interval) if not tickers: print("No stocks found matching your criteria.") return print(f"\nFound {len(tickers)} stocks to scan") print("Looking for SunnyBand crossovers...") print("This may take a few minutes...") # Initialize results lists bullish_signals = [] bearish_signals = [] errors = [] # Initialize SunnyBands indicator sunny = SunnyBands() # Track progress total = len(tickers) processed = 0 # Scan each ticker for ticker in tickers: processed += 1 if processed % 10 == 0: # Show progress every 10 stocks print(f"Progress: {processed}/{total} stocks processed ({(processed/total)*100:.1f}%)") try: # Get price data df = get_stock_data(ticker, start_date, end_date, interval) if df.empty: continue if len(df) < 50: # Need enough data for the indicator continue # Calculate SunnyBands results = sunny.calculate(df) # Check last day's signals last_day = df.iloc[-1] if results['bullish_signal'].iloc[-1]: signal_data = { 'ticker': ticker, 'price': last_day['close'], 'volume': last_day['volume'], 'date': last_day['date'], 'dma': results['dma'].iloc[-1], 'lower_band': results['lower_band'].iloc[-1] } bullish_signals.append(signal_data) print(f"🟢 Bullish Signal: {ticker} at ${last_day['close']:.2f}") elif results['bearish_signal'].iloc[-1]: signal_data = { 'ticker': ticker, 'price': last_day['close'], 'volume': last_day['volume'], 'date': last_day['date'], 'dma': results['dma'].iloc[-1], 'upper_band': results['upper_band'].iloc[-1] } bearish_signals.append(signal_data) print(f"šŸ”“ Bearish Signal: {ticker} at ${last_day['close']:.2f}") except Exception as e: errors.append(f"{ticker}: {str(e)}") continue # Save and display results output_date = datetime.now().strftime("%Y%m%d") print(f"\nScan Complete! Processed {total} stocks.") if errors: print(f"\nEncountered {len(errors)} errors during scan:") for error in errors[:5]: # Show first 5 errors print(error) if len(errors) > 5: print(f"...and {len(errors) - 5} more errors") if bullish_signals: print(f"\n🟢 Found {len(bullish_signals)} Bullish Signals:") df_bullish = pd.DataFrame(bullish_signals) bullish_file = f'src/reports/sunny_bullish_{output_date}.csv' df_bullish.to_csv(bullish_file, index=False) print(f"Saved to {bullish_file}") for signal in bullish_signals: print(f"\n{signal['ticker']}:") print(f"Price: ${signal['price']:.2f}") print(f"Volume: {signal['volume']:,}") print(f"DMA: ${signal['dma']:.2f}") print(f"Lower Band: ${signal['lower_band']:.2f}") if bearish_signals: print(f"\nšŸ”“ Found {len(bearish_signals)} Bearish Signals:") df_bearish = pd.DataFrame(bearish_signals) bearish_file = f'src/reports/sunny_bearish_{output_date}.csv' df_bearish.to_csv(bearish_file, index=False) print(f"Saved to {bearish_file}") for signal in bearish_signals: print(f"\n{signal['ticker']}:") print(f"Price: ${signal['price']:.2f}") print(f"Volume: {signal['volume']:,}") print(f"DMA: ${signal['dma']:.2f}") print(f"Upper Band: ${signal['upper_band']:.2f}") if not bullish_signals and not bearish_signals: print("\nNo signals found for today.") else: while True: view_choice = input("\nWould you like to view detailed data for a stock? (Enter ticker or 'n' to exit): ").upper() if view_choice == 'N': break # Check if ticker is in our signals found = False for signals in [bullish_signals, bearish_signals]: for signal in signals: if signal['ticker'] == view_choice: found = True view_stock_details(view_choice, interval, start_date, end_date) break if found: break if not found: print(f"Ticker {view_choice} not found in signals list.")