feat: Fetch current prices from ClickHouse instead of Polygon API

This commit is contained in:
Bobby (aider) 2025-02-19 20:52:18 -08:00
parent 7916dc764f
commit 9c49d8eb3c

View File

@ -4,7 +4,6 @@ from datetime import datetime, timedelta
from trading.position_calculator import PositionCalculator from trading.position_calculator import PositionCalculator
from utils.common_utils import get_user_input, get_stock_data, get_qualified_stocks from utils.common_utils import get_user_input, get_stock_data, get_qualified_stocks
from typing import Optional from typing import Optional
import requests
def get_float_input(prompt: str) -> Optional[float]: def get_float_input(prompt: str) -> Optional[float]:
return get_user_input(prompt, float) return get_user_input(prompt, float)
@ -14,36 +13,27 @@ def get_current_prices(tickers: list) -> dict:
if not tickers: if not tickers:
return {} return {}
polygon_api_key = os.environ.get("POLYGON_API_KEY")
if not polygon_api_key:
print("Error: POLYGON_API_KEY environment variable not set.")
return {}
prices = {} prices = {}
try: try:
for ticker in tickers: with create_client() as client:
url = f"https://api.polygon.io/v2/last/trade/{ticker}?apiKey={polygon_api_key}" for ticker in tickers:
response = requests.get(url) query = f"""
SELECT close
FROM stock_db.stock_prices_daily
WHERE ticker = '{ticker}'
ORDER BY date DESC
LIMIT 1
"""
result = client.query(query)
if response.status_code == 200:
data = response.json()
try: try:
prices[ticker] = data['results']['price'] prices[ticker] = result.result_rows[0][0]
except KeyError: except KeyError:
prices[ticker] = 0.0 prices[ticker] = 0.0
else:
print(f"Error fetching price for {ticker}: {response.status_code} - {response.text}")
prices[ticker] = 0.0
# Verify that we have prices for all tickers
for ticker in tickers:
if ticker not in prices or prices[ticker] == 0:
print(f"Could not fetch price for {ticker}")
prices[ticker] = 0.0
except Exception as e: except Exception as e:
print(f"Error fetching prices: {e}") print(f"Error fetching prices: {e}")
# If there's an error, fall back to setting price to 0.0 # If there's an error, set price to 0.0
for ticker in tickers: for ticker in tickers:
if ticker not in prices: if ticker not in prices:
prices[ticker] = 0.0 prices[ticker] = 0.0