fix: Align except block with try block in get_stock_data function

This commit is contained in:
Bobby Abellana (aider) 2025-02-07 08:56:00 -08:00 committed by Bobby Abellana
parent b5125a409f
commit 4f545d5041
No known key found for this signature in database
GPG Key ID: 647714CC45F3647B

View File

@ -33,89 +33,90 @@ def get_interval_choice() -> str:
def get_stock_data(ticker: str, start_date: datetime, end_date: datetime, interval: str) -> pd.DataFrame: def get_stock_data(ticker: str, start_date: datetime, end_date: datetime, interval: str) -> pd.DataFrame:
"""Fetch stock data from the database""" """Fetch stock data from the database"""
client = create_client() try:
client = create_client()
# Calculate proper date range (looking back from today) # Calculate proper date range (looking back from today)
end_date = datetime.now() end_date = datetime.now()
start_date = end_date - timedelta(days=60) # 60 days of history start_date = end_date - timedelta(days=60) # 60 days of history
if interval == "daily": if interval == "daily":
table = "stock_prices_daily" table = "stock_prices_daily"
date_col = "date" date_col = "date"
query = f""" query = f"""
SELECT SELECT
{date_col} as date, {date_col} as date,
open, open,
high, high,
low, low,
close, close,
volume volume
FROM stock_db.{table} FROM stock_db.{table}
WHERE ticker = '{ticker}' WHERE ticker = '{ticker}'
AND {date_col} BETWEEN '{start_date.date()}' AND '{end_date.date()}' AND {date_col} BETWEEN '{start_date.date()}' AND '{end_date.date()}'
ORDER BY date ASC ORDER BY date ASC
""" """
else: else:
table = "stock_prices" table = "stock_prices"
date_col = "window_start" date_col = "window_start"
minutes_map = { minutes_map = {
"5min": 5, "5min": 5,
"15min": 15, "15min": 15,
"30min": 30, "30min": 30,
"1hour": 60 "1hour": 60
} }
minutes = minutes_map[interval] minutes = minutes_map[interval]
# Get 5-minute bars and resample them to the desired interval # Get 5-minute bars and resample them to the desired interval
query = f""" query = f"""
SELECT SELECT
fromUnixTimestamp(intDiv(window_start/1000000000, 300) * 300) as interval_start, fromUnixTimestamp(intDiv(window_start/1000000000, 300) * 300) as interval_start,
min(open) as open, min(open) as open,
max(high) as high, max(high) as high,
min(low) as low, min(low) as low,
argMax(close, window_start) as close, argMax(close, window_start) as close,
sum(volume) as volume sum(volume) as volume
FROM stock_db.{table} FROM stock_db.{table}
WHERE ticker = '{ticker}' WHERE ticker = '{ticker}'
AND window_start/1000000000 BETWEEN AND window_start/1000000000 BETWEEN
toUnixTimestamp('{start_date.date()}') AND toUnixTimestamp('{start_date.date()}') AND
toUnixTimestamp('{end_date.date()}') toUnixTimestamp('{end_date.date()}')
GROUP BY interval_start GROUP BY interval_start
ORDER BY interval_start ASC ORDER BY interval_start ASC
""" """
print("\nExecuting Query:") print("\nExecuting Query:")
print(query) # Debugging: Print the query to verify its correctness print(query) # Debugging: Print the query to verify its correctness
result = client.query(query) result = client.query(query)
if not result.result_rows: if not result.result_rows:
print(f"No data found for {ticker}") print(f"No data found for {ticker}")
return pd.DataFrame() return pd.DataFrame()
df = pd.DataFrame( df = pd.DataFrame(
result.result_rows, result.result_rows,
columns=['date', 'open', 'high', 'low', 'close', 'volume'] columns=['date', 'open', 'high', 'low', 'close', 'volume']
) )
if interval != "daily" and interval != "5min": if interval != "daily" and interval != "5min":
# Resample to desired interval # Resample to desired interval
df.set_index('date', inplace=True) df.set_index('date', inplace=True)
minutes = minutes_map[interval] minutes = minutes_map[interval]
rule = f'{minutes}T' rule = f'{minutes}T'
df = df.resample(rule).agg({ df = df.resample(rule).agg({
'open': 'first', 'open': 'first',
'high': 'max', 'high': 'max',
'low': 'min', 'low': 'min',
'close': 'last', 'close': 'last',
'volume': 'sum' 'volume': 'sum'
}).dropna() }).dropna()
df.reset_index(inplace=True) df.reset_index(inplace=True)
return df return df
except Exception as e: except Exception as e:
print(f"Error fetching data for {ticker}: {str(e)}") print(f"Error fetching data for {ticker}: {str(e)}")
return pd.DataFrame() return pd.DataFrame()