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:
"""Fetch stock data from the database"""
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]
try:
client = create_client()
# 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()
# Calculate proper date range (looking back from today)
end_date = datetime.now()
start_date = end_date - timedelta(days=60) # 60 days of history
df = pd.DataFrame(
result.result_rows,
columns=['date', 'open', 'high', 'low', 'close', 'volume']
)
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
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:
except Exception as e:
print(f"Error fetching data for {ticker}: {str(e)}")
return pd.DataFrame()