""" Data loading and resampling utilities. """ import sqlite3 from pathlib import Path import pandas as pd DB_PATH = Path("/home/jonathan/Projects/ForexBots/data/candles.db") _RESAMPLE_MAP = { "open": "first", "high": "max", "low": "min", "close": "last", "tick_volume": "sum", } def load_candles(symbol: str, timeframe: str, db_path: Path = DB_PATH) -> pd.DataFrame: conn = sqlite3.connect(db_path) df = pd.read_sql_query( "SELECT time, open, high, low, close, tick_volume " "FROM candles WHERE symbol=? AND timeframe=? ORDER BY time", conn, params=(symbol, timeframe), ) conn.close() df["time"] = pd.to_datetime(df["time"]) df.set_index("time", inplace=True) return df def resample(df: pd.DataFrame, rule: str) -> pd.DataFrame: """Resample an OHLCV dataframe to a coarser timeframe. rule follows pandas offset alias (e.g. '1h', '4h', '1D'). """ agg = {c: _RESAMPLE_MAP[c] for c in df.columns if c in _RESAMPLE_MAP} return df.resample(rule, label="left", closed="left").agg(agg).dropna()