|
|
import requests |
|
|
import pandas as pd |
|
|
from datetime import datetime, timedelta |
|
|
|
|
|
API_KEY = "UUrRnlZXDllgVVn9bekrSTiBYRUqNFwp" |
|
|
|
|
|
def fetch_ohlcv(symbol="AAPL"): |
|
|
start_date = (datetime.utcnow() - timedelta(days=5)).strftime('%Y-%m-%d') |
|
|
end_date = (datetime.utcnow() - timedelta(days=1)).strftime('%Y-%m-%d') |
|
|
|
|
|
url = f"https://api.polygon.io/v2/aggs/ticker/{symbol}/range/1/minute/{start_date}/{end_date}" |
|
|
params = { |
|
|
"adjusted": "true", |
|
|
"sort": "asc", |
|
|
"limit": 5000, |
|
|
"apiKey": API_KEY, |
|
|
} |
|
|
|
|
|
print("π‘ URL:", url) |
|
|
print("π‘ Params:", params) |
|
|
|
|
|
try: |
|
|
response = requests.get(url, params=params) |
|
|
print("π΅ Status Code:", response.status_code) |
|
|
|
|
|
|
|
|
if response.status_code != 200: |
|
|
print("β Full response:", response.text) |
|
|
return None |
|
|
|
|
|
data = response.json() |
|
|
print("π Response JSON:", data) |
|
|
|
|
|
if "results" not in data: |
|
|
print("β 'results' key not found in response.") |
|
|
return None |
|
|
|
|
|
if not data["results"]: |
|
|
print("β Empty 'results' list.") |
|
|
return None |
|
|
|
|
|
df = pd.DataFrame(data["results"]) |
|
|
df["t"] = pd.to_datetime(df["t"], unit="ms") |
|
|
df.set_index("t", inplace=True) |
|
|
df.rename(columns={ |
|
|
"o": "Open", "h": "High", "l": "Low", "c": "Close", "v": "Volume" |
|
|
}, inplace=True) |
|
|
|
|
|
df = df[["Open", "High", "Low", "Close", "Volume"]] |
|
|
|
|
|
print(f"β
Successfully loaded {len(df)} rows.") |
|
|
return df |
|
|
|
|
|
except Exception as e: |
|
|
print("β Exception:", str(e)) |
|
|
return None |
|
|
|