Spaces:
Sleeping
Sleeping
File size: 2,418 Bytes
d96a847 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | # file: agent_system/data_loader.py
import yfinance as yf
import pandas as pd
import os
class DataLoader:
def __init__(self, data_dir="data"):
self.data_dir = data_dir
if not os.path.exists(data_dir):
os.makedirs(data_dir)
def fetch_data(self, ticker="BTC-USD", start="2010-01-01", end="2026-01-01"):
"""
Fetches historical data from Yahoo Finance or local CSV cache.
"""
file_path = os.path.join(self.data_dir, f"{ticker}_{start}_{end}.csv")
# 1. Check Cache
if os.path.exists(file_path):
print(f"📂 Loading {ticker} data from cache...")
df = pd.read_csv(file_path, index_col=0, parse_dates=True)
else:
# 2. Download if not cached
print(f"⬇️ Downloading {ticker} from Yahoo Finance...")
df = yf.download(ticker, start=start, end=end)
# 3. Clean and Save
# yfinance returns multi-index columns sometimes; flatten them if needed
if isinstance(df.columns, pd.MultiIndex):
df.columns = df.columns.get_level_values(0)
# Ensure we have lowercase columns for our Classifier
df.columns = [c.lower() for c in df.columns]
# Save to CSV
df.to_csv(file_path)
print(f"✅ Data saved to {file_path}")
# 4. Final Formatting
# The Orchestrator expects a list of dictionaries or a specific structure.
# For now, we return the DataFrame.
return df
def get_price_at(self, df, index):
"""Safe accessor for the orchestrator loop"""
try:
return df.iloc[index]['close']
except IndexError:
return None
def fetch_initial_data_yf(symbol="BTC-USD", interval="15m", count=100):
"""
Fetches the last N candles to warm up the classifier.
"""
print(f"📡 Seeding classifier with {count} candles from Yahoo Finance...")
# We fetch slightly more than 'count' to ensure we have enough after cleaning
df = yf.download(tickers=symbol, period="5d", interval=interval)
# Clean column names to match your orchestrator (lowercase 'close')
df = df.tail(count).copy()
df.columns = [col.lower() for col in df.columns]
return df[['close']]
|