Data Module¶
Loaders¶
signalflow.data.source.binance.BinanceSpotLoader
dataclass
¶
BinanceSpotLoader(store: DuckDbSpotStore = (lambda: DuckDbSpotStore(db_path=(Path('raw_data.duckdb'))))(), timeframe: str = '1m')
Bases: RawDataLoader
Downloads and stores Binance spot OHLCV data for fixed timeframe.
Combines BinanceClient (source) and DuckDbSpotStore (storage) to provide complete data pipeline with gap filling and incremental updates.
Attributes:
| Name | Type | Description |
|---|---|---|
store |
DuckDbSpotStore
|
Storage backend. Default: raw_data.duckdb. |
timeframe |
str
|
Fixed timeframe for all data. Default: "1m". |
download
async
¶
download(pairs: list[str], days: Optional[int] = None, start: Optional[datetime] = None, end: Optional[datetime] = None, fill_gaps: bool = True) -> None
Download historical data with intelligent range detection.
Automatically determines what to download
- If no existing data: download full range
- If data exists: download before/after existing range
- If fill_gaps=True: detect and fill gaps in existing range
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
list[str]
|
Trading pairs to download. |
required |
days
|
int | None
|
Number of days back from end. Default: 7. |
None
|
start
|
datetime | None
|
Range start (overrides days). |
None
|
end
|
datetime | None
|
Range end. Default: now. |
None
|
fill_gaps
|
bool
|
Detect and fill gaps. Default: True. |
True
|
Note
Runs async download for all pairs concurrently. Logs progress for large downloads. Errors logged but don't stop other pairs.
Source code in src/signalflow/data/source/binance.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | |
sync
async
¶
Real-time sync - continuously update with latest data.
Runs indefinitely, fetching latest candles at specified interval. Useful for live trading or monitoring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
list[str]
|
Trading pairs to sync. |
required |
update_interval_sec
|
int
|
Update interval in seconds. Default: 60. |
60
|
Note
Runs forever - use Ctrl+C to stop or run in background task. Fetches last 5 candles per update (ensures no gaps). Errors logged but sync continues.
Source code in src/signalflow/data/source/binance.py
Storage¶
signalflow.data.raw_store.duckdb_stores.DuckDbSpotStore
dataclass
¶
Bases: RawDataStore
DuckDB storage backend for OHLCV spot data.
Provides efficient storage and retrieval of candlestick (OHLCV) data using DuckDB as the backend. Designed for fixed-timeframe storage (timeframe not stored per-row, configured at database level).
Key features
- Automatic schema migration from legacy formats
- Efficient batch inserts with upsert (INSERT OR REPLACE)
- Gap detection for data continuity checks
- Multi-pair batch loading
- Indexed queries for fast retrieval
Schema
- pair (VARCHAR): Trading pair
- timestamp (TIMESTAMP): Bar open time (timezone-naive)
- open, high, low, close (DOUBLE): OHLC prices
- volume (DOUBLE): Trading volume
- trades (INTEGER): Number of trades
Attributes:
| Name | Type | Description |
|---|---|---|
db_path |
Path
|
Path to DuckDB file. |
timeframe |
str
|
Fixed timeframe for all data (e.g., "1m", "5m"). Default: "1m". |
_con |
DuckDBPyConnection
|
Database connection (initialized in post_init). |
Example
from signalflow.data.raw_store import DuckDbSpotStore
from pathlib import Path
from datetime import datetime
# Create store
store = DuckDbSpotStore(
db_path=Path("data/binance_spot.duckdb"),
timeframe="1m"
)
try:
# Insert data
klines = [
{
"timestamp": datetime(2024, 1, 1, 10, 0),
"open": 45000.0,
"high": 45100.0,
"low": 44900.0,
"close": 45050.0,
"volume": 100.5,
"trades": 150
}
]
store.insert_klines("BTCUSDT", klines)
# Load data
df = store.load("BTCUSDT", hours=24)
# Check data bounds
min_ts, max_ts = store.get_time_bounds("BTCUSDT")
print(f"Data range: {min_ts} to {max_ts}")
# Get statistics
stats = store.get_stats()
print(stats)
finally:
store.close()
Note
Timeframe is fixed per database, not per row. Automatically migrates from legacy schema (open_time, timeframe columns). Always call close() to cleanup database connection.
See Also
RawDataStore: Base class with interface definition. RawDataFactory: Factory for creating RawData from stores.
__post_init__ ¶
close ¶
Close database connection and cleanup resources.
Always call in finally block or use context manager to ensure cleanup.
Example
Source code in src/signalflow/data/raw_store/duckdb_stores.py
find_gaps ¶
find_gaps(pair: str, start: datetime, end: datetime, tf_minutes: int) -> list[tuple[datetime, datetime]]
Find gaps in data coverage for a pair.
Detects missing bars in expected continuous sequence based on timeframe. Useful for data quality checks and incremental backfilling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
str
|
Trading pair (e.g., "BTCUSDT"). |
required |
start
|
datetime
|
Start of expected range. |
required |
end
|
datetime
|
End of expected range. |
required |
tf_minutes
|
int
|
Timeframe in minutes (e.g., 1 for 1m, 5 for 5m). |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[datetime, datetime]]
|
list[tuple[datetime, datetime]]: List of (gap_start, gap_end) tuples. Empty list if no gaps found. |
Example
from datetime import datetime
# Check for gaps in January 2024
gaps = store.find_gaps(
pair="BTCUSDT",
start=datetime(2024, 1, 1),
end=datetime(2024, 1, 31),
tf_minutes=1
)
if gaps:
print(f"Found {len(gaps)} gaps:")
for gap_start, gap_end in gaps:
duration = gap_end - gap_start
print(f" {gap_start} to {gap_end} ({duration})")
# Backfill gaps
backfill_data(pair="BTCUSDT", start=gap_start, end=gap_end)
else:
print("No gaps found - data is continuous")
# Data quality report
gaps = store.find_gaps("BTCUSDT", start, end, tf_minutes=1)
total_expected = int((end - start).total_seconds() / 60)
total_missing = sum((g[1] - g[0]).total_seconds() / 60 for g in gaps)
coverage = (1 - total_missing / total_expected) * 100
print(f"Data coverage: {coverage:.2f}%")
Note
Returns full range [(start, end)] if no data exists. Computationally expensive for large date ranges - use sparingly.
Source code in src/signalflow/data/raw_store/duckdb_stores.py
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 | |
get_stats ¶
Get database statistics per pair.
Returns summary statistics for all pairs in database.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: Statistics with columns: - pair (str): Trading pair - rows (int): Number of bars - first_candle (datetime): Earliest timestamp - last_candle (datetime): Latest timestamp - total_volume (float): Sum of volume |
Example
# Get overview
stats = store.get_stats()
print(stats)
# Check coverage
for row in stats.iter_rows(named=True):
pair = row["pair"]
days = (row["last_candle"] - row["first_candle"]).days
print(f"{pair}: {row['rows']:,} bars over {days} days")
# Identify incomplete data
min_rows = stats["rows"].min()
incomplete = stats.filter(pl.col("rows") < min_rows * 0.9)
print(f"Pairs with <90% coverage: {incomplete['pair'].to_list()}")
Note
Timeframe not included in output (stored in meta table). Sorted alphabetically by pair.
Source code in src/signalflow/data/raw_store/duckdb_stores.py
get_time_bounds ¶
Get earliest and latest timestamps for a pair.
Useful for
- Checking data availability
- Planning data updates
- Validating date ranges
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
str
|
Trading pair (e.g., "BTCUSDT"). |
required |
Returns:
| Type | Description |
|---|---|
tuple[Optional[datetime], Optional[datetime]]
|
tuple[datetime | None, datetime | None]: (min_timestamp, max_timestamp). Both None if no data exists for pair. |
Example
# Check data availability
min_ts, max_ts = store.get_time_bounds("BTCUSDT")
if min_ts and max_ts:
print(f"Data available: {min_ts} to {max_ts}")
days = (max_ts - min_ts).days
print(f"Total days: {days}")
else:
print("No data available")
# Plan incremental update
_, max_ts = store.get_time_bounds("BTCUSDT")
if max_ts:
# Fetch data from max_ts to now
fetch_data(start=max_ts, end=datetime.now())
Source code in src/signalflow/data/raw_store/duckdb_stores.py
insert_klines ¶
Upsert klines (INSERT OR REPLACE).
Efficient batch insertion with automatic upsert on (pair, timestamp) conflict. Uses Arrow-based bulk insert for >10 rows for better performance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
str
|
Trading pair (e.g., "BTCUSDT"). |
required |
klines
|
list[dict]
|
List of kline dictionaries. Each must contain: - timestamp (datetime): Bar open time - open (float): Open price - high (float): High price - low (float): Low price - close (float): Close price - volume (float): Trading volume - trades (int, optional): Number of trades |
required |
Example
from datetime import datetime
# Insert single kline
store.insert_klines("BTCUSDT", [
{
"timestamp": datetime(2024, 1, 1, 10, 0),
"open": 45000.0,
"high": 45100.0,
"low": 44900.0,
"close": 45050.0,
"volume": 100.5,
"trades": 150
}
])
# Batch insert (efficient for >10 rows)
klines = [
{
"timestamp": datetime(2024, 1, 1, 10, i),
"open": 45000.0 + i,
"high": 45100.0 + i,
"low": 44900.0 + i,
"close": 45050.0 + i,
"volume": 100.0,
"trades": 150
}
for i in range(100)
]
store.insert_klines("BTCUSDT", klines)
# Upsert - updates existing rows
store.insert_klines("BTCUSDT", [
{
"timestamp": datetime(2024, 1, 1, 10, 0),
"open": 45010.0, # Updated price
"high": 45110.0,
"low": 44910.0,
"close": 45060.0,
"volume": 101.0,
"trades": 152
}
])
Note
Empty klines list is silently ignored. Uses executemany for ≤10 rows, Arrow bulk insert for >10 rows. Automatically logs insert count at debug level.
Source code in src/signalflow/data/raw_store/duckdb_stores.py
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | |
load ¶
load(pair: str, hours: Optional[int] = None, start: Optional[datetime] = None, end: Optional[datetime] = None) -> pl.DataFrame
Load data for a single trading pair.
Output columns: pair, timestamp, open, high, low, close, volume, trades
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
str
|
Trading pair (e.g., "BTCUSDT"). |
required |
hours
|
int | None
|
Load last N hours of data. Mutually exclusive with start/end. |
None
|
start
|
datetime | None
|
Start datetime (inclusive). Requires end parameter. |
None
|
end
|
datetime | None
|
End datetime (inclusive). Requires start parameter. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: OHLCV data sorted by timestamp. Timezone-naive timestamps. |
Example
Source code in src/signalflow/data/raw_store/duckdb_stores.py
load_many ¶
load_many(pairs: Iterable[str], hours: Optional[int] = None, start: Optional[datetime] = None, end: Optional[datetime] = None) -> pl.DataFrame
Batch load for multiple pairs.
Output columns: pair, timestamp, open, high, low, close, volume, trades
More efficient than multiple load() calls due to single query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
Iterable[str]
|
Trading pairs to load. |
required |
hours
|
int | None
|
Load last N hours of data. |
None
|
start
|
datetime | None
|
Start datetime (inclusive). |
None
|
end
|
datetime | None
|
End datetime (inclusive). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: Combined OHLCV data sorted by (pair, timestamp). Empty DataFrame with correct schema if no pairs provided. |
Example
Source code in src/signalflow/data/raw_store/duckdb_stores.py
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 | |
load_many_pandas ¶
load_many_pandas(pairs: list[str], start: datetime | None = None, end: datetime | None = None) -> pd.DataFrame
Load data for multiple pairs as Pandas DataFrame.
Convenience wrapper around load_many() for Pandas compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
list[str]
|
List of trading pairs. |
required |
start
|
datetime | None
|
Start datetime (inclusive). |
None
|
end
|
datetime | None
|
End datetime (inclusive). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Combined OHLCV data as Pandas DataFrame. |
Example
Source code in src/signalflow/data/raw_store/duckdb_stores.py
Factory¶
signalflow.data.raw_data_factory.RawDataFactory ¶
Factory for creating RawData instances from various sources.
Provides static methods to construct RawData objects from different storage backends (DuckDB, Parquet, etc.) with proper validation and schema normalization.
Key features
- Automatic schema validation
- Duplicate detection
- Timezone normalization
- Column cleanup (remove unnecessary columns)
- Proper sorting by (pair, timestamp)
Example
from signalflow.data import RawDataFactory
from pathlib import Path
from datetime import datetime
# Load spot data from DuckDB
raw_data = RawDataFactory.from_duckdb_spot_store(
spot_store_path=Path("data/binance_spot.duckdb"),
pairs=["BTCUSDT", "ETHUSDT"],
start=datetime(2024, 1, 1),
end=datetime(2024, 12, 31),
data_types=["spot"]
)
# Access loaded data
spot_df = raw_data["spot"]
print(f"Loaded {len(spot_df)} bars")
print(f"Pairs: {raw_data.pairs}")
print(f"Date range: {raw_data.datetime_start} to {raw_data.datetime_end}")
# Use in detector
from signalflow.detector import SmaCrossSignalDetector
detector = SmaCrossSignalDetector(fast_window=10, slow_window=20)
signals = detector.detect(raw_data)
See Also
RawData: Immutable container for raw market data. DuckDbSpotStore: DuckDB storage backend for spot data.
from_duckdb_spot_store
staticmethod
¶
from_duckdb_spot_store(spot_store_path: Path, pairs: list[str], start: datetime, end: datetime, data_types: list[str] | None = None) -> RawData
Create RawData from DuckDB spot store.
Loads spot trading data from DuckDB storage with validation, deduplication checks, and schema normalization.
Processing steps
- Load data from DuckDB for specified pairs and date range
- Validate required columns (pair, timestamp)
- Remove unnecessary columns (timeframe)
- Normalize timestamps (microseconds, timezone-naive)
- Check for duplicates (pair, timestamp)
- Sort by (pair, timestamp)
- Package into RawData container
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spot_store_path
|
Path
|
Path to DuckDB file. |
required |
pairs
|
list[str]
|
List of trading pairs to load (e.g., ["BTCUSDT", "ETHUSDT"]). |
required |
start
|
datetime
|
Start datetime (inclusive). |
required |
end
|
datetime
|
End datetime (inclusive). |
required |
data_types
|
list[str] | None
|
Data types to load. Default: None. Currently supports: ["spot"]. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
RawData |
RawData
|
Immutable container with loaded and validated data. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If required columns missing (pair, timestamp). |
ValueError
|
If duplicate (pair, timestamp) combinations detected. |
Example
from pathlib import Path
from datetime import datetime
from signalflow.data import RawDataFactory
# Load single pair
raw_data = RawDataFactory.from_duckdb_spot_store(
spot_store_path=Path("data/binance.duckdb"),
pairs=["BTCUSDT"],
start=datetime(2024, 1, 1),
end=datetime(2024, 1, 31),
data_types=["spot"]
)
# Load multiple pairs
raw_data = RawDataFactory.from_duckdb_spot_store(
spot_store_path=Path("data/binance.duckdb"),
pairs=["BTCUSDT", "ETHUSDT", "BNBUSDT"],
start=datetime(2024, 1, 1),
end=datetime(2024, 12, 31),
data_types=["spot"]
)
# Check loaded data
spot_df = raw_data["spot"]
print(f"Shape: {spot_df.shape}")
print(f"Columns: {spot_df.columns}")
print(f"Pairs: {spot_df['pair'].unique().to_list()}")
# Verify no duplicates
dup_check = (
spot_df.group_by(["pair", "timestamp"])
.len()
.filter(pl.col("len") > 1)
)
assert dup_check.is_empty()
# Use in pipeline
from signalflow.core import RawDataView
view = RawDataView(raw=raw_data)
spot_pandas = view.to_pandas("spot")
Example
# Handle missing data gracefully
try:
raw_data = RawDataFactory.from_duckdb_spot_store(
spot_store_path=Path("data/binance.duckdb"),
pairs=["BTCUSDT"],
start=datetime(2024, 1, 1),
end=datetime(2024, 1, 31),
data_types=["spot"]
)
except ValueError as e:
if "missing columns" in str(e):
print("Data schema invalid")
elif "Duplicate" in str(e):
print("Data contains duplicates")
raise
# Validate date range
assert raw_data.datetime_start == datetime(2024, 1, 1)
assert raw_data.datetime_end == datetime(2024, 1, 31)
# Check data quality
spot_df = raw_data["spot"]
# Verify timestamps are sorted
assert spot_df["timestamp"].is_sorted()
# Verify timezone-naive
assert spot_df["timestamp"].dtype == pl.Datetime("us")
# Verify no nulls in key columns
assert spot_df["pair"].null_count() == 0
assert spot_df["timestamp"].null_count() == 0
Note
Store connection is automatically closed via finally block. Timestamps are normalized to timezone-naive microseconds. Duplicate detection shows first 10 examples if found. All data sorted by (pair, timestamp) for consistent ordering.
Source code in src/signalflow/data/raw_data_factory.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | |