stock_system/src/screener/t_sunnyband.py

408 lines
15 KiB
Python

import os
import os
import numpy as np
from datetime import datetime, timedelta
import pandas as pd
from db.db_connection import create_client
from indicators.sunny_bands import SunnyBands
from trading.position_calculator import PositionCalculator
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"""
try:
client = create_client()
# Calculate proper date range (looking back from today)
end_date = datetime.now()
start_date = end_date - timedelta(days=60) # 60 days of history
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.date()}' AND '{end_date.date()}'
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(window_start/1000000000, 300) * 300) as interval_start,
min(open) as open,
max(high) as high,
min(low) as low,
argMax(close, window_start) as close,
sum(volume) as volume
FROM stock_db.{table}
WHERE ticker = '{ticker}'
AND window_start/1000000000 BETWEEN
toUnixTimestamp('{start_date.date()}') AND
toUnixTimestamp('{end_date.date()}')
GROUP BY interval_start
ORDER BY interval_start ASC
"""
print("\nExecuting Query:")
print(query) # Debugging: Print the query to verify its correctness
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()
# Get the most recent trading day
today = datetime.now().date()
yesterday = today - timedelta(days=1)
# 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
# Convert to Unix timestamp in nanoseconds
start_ts = int(datetime.combine(yesterday, datetime.strptime("09:30", "%H:%M").time()).timestamp() * 1000000000)
end_ts = int(datetime.combine(yesterday, datetime.strptime("16:00", "%H:%M").time()).timestamp() * 1000000000)
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 {start_ts} AND {end_ts}
GROUP BY ticker
HAVING count() >= 50 -- Ensure we have enough data points for the indicator
"""
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:
# Construct query
client = create_client()
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]
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
"""
# Print the actual query being executed
print("\nExecuting Query:")
print(query)
# Execute query and get results
result = client.query(query)
if not result.result_rows:
print("\nNo data found for this stock")
return
# Convert to DataFrame
df = pd.DataFrame(
result.result_rows,
columns=['date', 'open', 'high', 'low', 'close', 'volume']
)
# Print raw query results
print("\nRaw Query Results:")
print(f"Number of rows returned: {len(result.result_rows)}")
print("\nFirst 5 rows of raw data:")
for i, row in enumerate(result.result_rows[:5]):
print(f"Row {i + 1}: {row}")
print("\nLast 5 rows of raw data:")
for i, row in enumerate(result.result_rows[-5:]):
print(f"Row {len(result.result_rows) - 4 + i}: {row}")
# 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, portfolio_size: float = None) -> None:
print(f"\nScanning for stocks ${min_price:.2f}-${max_price:.2f} with min volume {min_volume:,}")
interval = get_interval_choice()
end_date = datetime.now()
start_date = end_date - timedelta(days=1) # Get last trading day
# First get qualified stocks from database
client = create_client()
# Convert dates to Unix timestamp in nanoseconds
end_ts = int(end_date.timestamp() * 1000000000)
start_ts = int(start_date.timestamp() * 1000000000)
# Query to get stocks meeting criteria with their latest data
query = f"""
WITH latest_data AS (
SELECT
ticker,
argMax(close, window_start) as last_close,
sum(volume) as total_volume,
max(window_start) as last_update
FROM stock_db.stock_prices
WHERE window_start BETWEEN {start_ts} AND {end_ts}
GROUP BY ticker
HAVING last_close BETWEEN {min_price} AND {max_price}
AND total_volume >= {min_volume}
)
SELECT
ticker,
last_close,
total_volume,
last_update
FROM latest_data
ORDER BY ticker
"""
try:
result = client.query(query)
qualified_stocks = [(row[0], row[1], row[2], row[3]) for row in result.result_rows]
qualified_stocks = [(row[0], row[1], row[2], row[3]) for row in result.result_rows]
if not qualified_stocks:
print("No stocks found matching criteria.")
return
print(f"\nFound {len(qualified_stocks)} stocks matching criteria")
# Initialize indicators
sunny = SunnyBands()
calculator = None
if portfolio_size and portfolio_size > 0:
calculator = PositionCalculator(account_size=portfolio_size)
bullish_signals = []
bearish_signals = []
# Process each qualified stock
for ticker, current_price, current_volume, last_update in qualified_stocks:
try:
# Get historical data based on interval
df = get_stock_data(ticker, start_date, end_date, interval)
if df.empty or len(df) < 50: # Need at least 50 bars for the indicator
continue
# Calculate SunnyBands
results = sunny.calculate(df)
# Check for signals
if results['bullish_signal'].iloc[-1]:
target_price = results['upper_band'].iloc[-1]
if calculator:
position = calculator.calculate_position_size(current_price, target_price)
if position['shares'] > 0:
signal_data = {
'ticker': ticker,
'entry': current_price,
'target': target_price,
'volume': current_volume,
'last_update': datetime.fromtimestamp(last_update/1000000000),
'shares': position['shares'],
'position_size': position['position_value'],
'stop_loss': position['stop_loss'],
'risk': position['potential_loss'],
'reward': position['potential_profit'],
'r_r': position['risk_reward_ratio']
}
bullish_signals.append(signal_data)
print(f"\n🟢 {ticker} Entry: ${current_price:.2f} Target: ${target_price:.2f}")
print(f" Shares: {signal_data['shares']} | Risk: ${abs(signal_data['risk']):.2f} | "
f"Reward: ${signal_data['reward']:.2f} | R/R: {signal_data['r_r']:.2f}")
elif results['bearish_signal'].iloc[-1]:
bearish_signals.append({
'ticker': ticker,
'price': current_price,
'volume': current_volume,
'last_update': datetime.fromtimestamp(last_update/1000000000)
})
print(f"\n🔴 {ticker} at ${current_price:.2f}")
except Exception as e:
print(f"Error processing {ticker}: {str(e)}")
continue
# Save results
output_dir = 'reports'
os.makedirs(output_dir, exist_ok=True)
output_date = datetime.now().strftime("%Y%m%d_%H%M")
if bullish_signals:
df_bullish = pd.DataFrame(bullish_signals)
output_file = f'{output_dir}/sunny_bullish_{output_date}.csv'
df_bullish.to_csv(output_file, index=False)
print(f"\nSaved bullish signals to {output_file}")
if bearish_signals:
df_bearish = pd.DataFrame(bearish_signals)
output_file = f'{output_dir}/sunny_bearish_{output_date}.csv'
df_bearish.to_csv(output_file, index=False)
print(f"\nSaved bearish signals to {output_file}")
print(f"\nFound {len(bullish_signals)} bullish and {len(bearish_signals)} bearish signals")
except Exception as e:
print(f"Error during scan: {str(e)}")