Data Module¶
Data Sources¶
Binance¶
signalflow.data.source.binance.BinanceClient
dataclass
¶
BinanceClient(base_url: str = 'https://api.binance.com', klines_path: str = '/api/v3/klines', exchange_info_path: str = '/api/v3/exchangeInfo', max_retries: int = 3, timeout_sec: int = 30, min_delay_sec: float = 0.05)
Bases: RawDataSource
Async client for Binance REST API.
Provides async methods for fetching OHLCV candlestick data with automatic retries, rate limit handling, and pagination.
IMPORTANT: Returned timestamps are candle CLOSE times (Binance k[6]), UTC-naive.
Attributes:
| Name | Type | Description |
|---|---|---|
base_url |
str
|
Binance API base URL. Default: "https://api.binance.com". |
max_retries |
int
|
Maximum retry attempts. Default: 3. |
timeout_sec |
int
|
Request timeout in seconds. Default: 30. |
min_delay_sec |
float
|
Minimum delay between requests. Default: 0.05. |
__aenter__
async
¶
Enter async context - creates session.
__aexit__
async
¶
get_klines
async
¶
get_klines(pair: str, timeframe: str = '1m', *, start_time: datetime | None = None, end_time: datetime | None = None, limit: int = 1000) -> list[dict[str, Any]]
Fetch OHLCV klines from Binance.
IMPORTANT: Returned "timestamp" is CANDLE CLOSE TIME (UTC-naive).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
str
|
Trading pair (e.g., "BTCUSDT"). |
required |
timeframe
|
str
|
Interval (1m, 5m, 1h, 1d, etc.). Default: "1m". |
'1m'
|
start_time
|
datetime | None
|
Range start (naive=UTC or aware). |
None
|
end_time
|
datetime | None
|
Range end (naive=UTC or aware). |
None
|
limit
|
int
|
Max candles (max 1000). Default: 1000. |
1000
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
list[dict]: OHLCV dicts with keys: timestamp, open, high, low, close, volume, trades. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If not in async context or API error. |
Source code in src/signalflow/data/source/binance.py
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 226 227 228 229 230 | |
get_klines_range
async
¶
get_klines_range(pair: str, timeframe: str, start_time: datetime, end_time: datetime, *, limit: int = 1000) -> list[dict[str, Any]]
Download all klines for period with automatic pagination.
Semantics
- Range by CANDLE CLOSE TIME: [start_time, end_time] inclusive
- Returns UTC-naive timestamps
- Automatic deduplication
Pagination strategy
- Request windows of size limit * timeframe
- Advance based on last returned close time + 1ms
- Additional dedup at end for safety
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
str
|
Trading pair. |
required |
timeframe
|
str
|
Interval (must be in TIMEFRAME_MS). |
required |
start_time
|
datetime
|
Range start (inclusive). |
required |
end_time
|
datetime
|
Range end (inclusive). |
required |
limit
|
int
|
Candles per request. Default: 1000. |
1000
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
list[dict]: Deduplicated, sorted OHLCV dicts. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If timeframe unsupported. |
RuntimeError
|
If pagination exceeds safety limit (2M loops). |
Source code in src/signalflow/data/source/binance.py
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 319 320 321 322 323 324 325 326 327 328 | |
get_pairs
async
¶
Get list of available trading pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quote
|
str | None
|
Filter by quote asset (e.g., "USDT", "BTC"). If None, returns all trading pairs. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: List of trading pair symbols (e.g., ["BTCUSDT", "ETHUSDT"]). |
Example
Source code in src/signalflow/data/source/binance.py
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: int | None = None, start: datetime | None = None, end: datetime | None = 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
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 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | |
get_pairs
async
¶
Get list of available trading pairs from Binance Spot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quote
|
str | None
|
Filter by quote asset (e.g., "USDT"). If None, returns all trading pairs. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: List of trading pair symbols. |
Example
Source code in src/signalflow/data/source/binance.py
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
signalflow.data.source.binance.BinanceFuturesUsdtLoader
dataclass
¶
BinanceFuturesUsdtLoader(store: DuckDbSpotStore = (lambda: DuckDbSpotStore(db_path=(Path('raw_data_futures_usdt.duckdb'))))(), timeframe: str = '1m')
Bases: RawDataLoader
Downloads and stores Binance USDT-M Futures OHLCV data.
Uses the fapi.binance.com endpoint for USDT-margined perpetual
and delivery contracts. Follows the same pipeline as
BinanceSpotLoader (gap filling, incremental sync).
Attributes:
| Name | Type | Description |
|---|---|---|
store |
DuckDbSpotStore
|
Storage backend. |
timeframe |
str
|
Fixed timeframe for all data. Default: "1m". |
download
async
¶
download(pairs: list[str], days: int | None = None, start: datetime | None = None, end: datetime | None = None, fill_gaps: bool = True) -> None
Download historical USDT-M futures data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
list[str]
|
Trading pairs to download (e.g. ["BTCUSDT"]). |
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
|
Source code in src/signalflow/data/source/binance.py
542 543 544 545 546 547 548 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 | |
get_pairs
async
¶
Get list of available USDT-M futures pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quote
|
str | None
|
Filter by quote asset (e.g., "USDT"). If None, returns all futures pairs. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: List of futures pair symbols. |
Example
Source code in src/signalflow/data/source/binance.py
sync
async
¶
Continuously sync latest USDT-M futures data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
list[str]
|
Trading pairs to sync. |
required |
update_interval_sec
|
int
|
Update interval in seconds. Default: 60. |
60
|
Source code in src/signalflow/data/source/binance.py
signalflow.data.source.binance.BinanceFuturesCoinLoader
dataclass
¶
BinanceFuturesCoinLoader(store: DuckDbSpotStore = (lambda: DuckDbSpotStore(db_path=(Path('raw_data_futures_coin.duckdb'))))(), timeframe: str = '1m')
Bases: RawDataLoader
Downloads and stores Binance COIN-M Futures OHLCV data.
Uses the dapi.binance.com endpoint for coin-margined perpetual
and delivery contracts.
Attributes:
| Name | Type | Description |
|---|---|---|
store |
DuckDbSpotStore
|
Storage backend. |
timeframe |
str
|
Fixed timeframe for all data. Default: "1m". |
download
async
¶
download(pairs: list[str], days: int | None = None, start: datetime | None = None, end: datetime | None = None, fill_gaps: bool = True) -> None
Download historical COIN-M futures data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
list[str]
|
Trading pairs to download (e.g. ["BTCUSD_PERP"]). |
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
|
Source code in src/signalflow/data/source/binance.py
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 | |
get_pairs
async
¶
Get list of available COIN-M futures pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quote
|
str | None
|
Filter by margin asset (e.g., "BTC"). If None, returns all COIN-M futures pairs. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: List of futures pair symbols (e.g., ["BTCUSD_PERP"]). |
Example
Source code in src/signalflow/data/source/binance.py
sync
async
¶
Continuously sync latest COIN-M futures data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
list[str]
|
Trading pairs to sync. |
required |
update_interval_sec
|
int
|
Update interval in seconds. Default: 60. |
60
|
Source code in src/signalflow/data/source/binance.py
Other Exchanges¶
Additional exchange sources (Bybit, OKX, Deribit, Kraken, Hyperliquid, WhiteBIT) are provided by the signalflow-data extension package. Install it separately to access these loaders.
Virtual Data¶
signalflow.data.source.virtual.VirtualDataProvider
dataclass
¶
VirtualDataProvider(store: Any = None, timeframe: str = '1m', base_prices: dict[str, float] = dict(), volatility: float = 0.02, trend: float = 0.0001, seed: int | None = 42)
Bases: RawDataLoader
Generates and streams synthetic OHLCV data into a store.
Drop-in replacement for BinanceSpotLoader in tests and paper
trading dry-runs. Data is generated deterministically when a seed
is provided.
Attributes:
| Name | Type | Description |
|---|---|---|
store |
Any
|
Any raw data store with |
timeframe |
str
|
Candle interval. |
base_prices |
dict[str, float]
|
Starting price per pair (defaults to 100.0). |
volatility |
float
|
Per-bar return std dev. |
trend |
float
|
Per-bar drift. |
seed |
int | None
|
Random seed for reproducibility. |
download ¶
download(pairs: list[str] | None = None, n_bars: int = 200, start: datetime | None = None, **kwargs: Any) -> None
Pre-populate store with historical data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
list[str] | None
|
Trading pairs to generate. |
None
|
n_bars
|
int
|
Number of bars per pair. |
200
|
start
|
datetime | None
|
Start timestamp. Defaults to |
None
|
Source code in src/signalflow/data/source/virtual.py
sync
async
¶
Continuously generate new bars at a fixed interval.
Mimics BinanceSpotLoader.sync() - runs forever, writing
new bars to the store each cycle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
list[str]
|
Trading pairs to stream. |
required |
update_interval_sec
|
int
|
Seconds between new bars. |
60
|
Source code in src/signalflow/data/source/virtual.py
Storage¶
signalflow.data.raw_store.duckdb_stores.DuckDbSpotStore
module-attribute
¶
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, target_timeframe: str | None = None) -> RawData
Create RawData from DuckDB spot store.
Loads spot trading data from DuckDB storage with validation, deduplication checks, and schema normalization.
If data_types is None, defaults to ["spot"].
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
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 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 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 448 449 450 451 452 453 454 455 456 457 | |
from_stores
staticmethod
¶
from_stores(stores: Mapping[str, RawDataStore] | Sequence[RawDataStore], pairs: list[str], start: datetime, end: datetime, default_source: str | None = None, target_timeframe: str | None = None) -> RawData
Create RawData from multiple stores.
Supports two input formats: - Dict: {source_name: store} for multi-source per data_type (nested structure) - Sequence: [store1, store2] for single source per data_type (flat structure)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stores
|
Mapping[str, RawDataStore] | Sequence[RawDataStore]
|
Either dict mapping source names to stores, or sequence of stores. Dict format creates nested structure: data[data_type][source] = DataFrame. Sequence format creates flat structure: data[data_type] = DataFrame. |
required |
pairs
|
list[str]
|
List of trading pairs to load. |
required |
start
|
datetime
|
Start datetime (inclusive). |
required |
end
|
datetime
|
End datetime (inclusive). |
required |
default_source
|
str | None
|
Default source for nested data access. Used when accessing data without explicit source. |
None
|
target_timeframe
|
str | None
|
Target timeframe (e.g. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
RawData |
RawData
|
Container with merged data from all stores. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If stores have duplicate keys (flat) or conflicting data_types (nested). |
Example
from signalflow.data import RawDataFactory, DuckDbRawStore
# Multi-source (dict) - creates nested structure
raw = RawDataFactory.from_stores(
stores={
"binance": DuckDbRawStore(db_path="binance.duckdb", data_type="perpetual"),
"okx": DuckDbRawStore(db_path="okx.duckdb", data_type="perpetual"),
"bybit": DuckDbRawStore(db_path="bybit.duckdb", data_type="perpetual"),
},
pairs=["BTCUSDT", "ETHUSDT"],
start=datetime(2024, 1, 1),
end=datetime(2024, 12, 31),
default_source="binance",
)
# Hierarchical access
df = raw.perpetual.binance # specific source
df = raw.perpetual.to_polars() # default with warning
print(raw.perpetual.sources) # ["binance", "okx", "bybit"]
# Single-source (sequence) - creates flat structure
raw = RawDataFactory.from_stores(
stores=[spot_store, futures_store],
pairs=["BTCUSDT", "ETHUSDT"],
start=datetime(2024, 1, 1),
end=datetime(2024, 12, 31),
)
# Simple access
spot_df = raw["spot"]
futures_df = raw["futures"]
Source code in src/signalflow/data/raw_data_factory.py
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 | |
Resampling¶
Unified OHLCV timeframe resampling with exchange-aware timeframe selection.
from signalflow.data.resample import (
resample_ohlcv,
align_to_timeframe,
detect_timeframe,
select_best_timeframe,
can_resample,
)
# Auto-detect and resample to 1h
df_1h = align_to_timeframe(raw_df, target_tf="1h")
# Find best exchange timeframe for download
best = select_best_timeframe("bybit", target_tf="8h") # "4h"
signalflow.data.resample.resample_ohlcv ¶
resample_ohlcv(df: DataFrame, source_tf: str, target_tf: str, *, pair_col: str = 'pair', ts_col: str = 'timestamp', fill_rules: dict[str, str] | None = None) -> pl.DataFrame
Resample an OHLCV DataFrame from source_tf to target_tf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Source DataFrame with OHLCV columns. |
required |
source_tf
|
str
|
Current timeframe of the data. |
required |
target_tf
|
str
|
Desired target timeframe. |
required |
pair_col
|
str
|
Pair/group column name. |
'pair'
|
ts_col
|
str
|
Timestamp column name. |
'timestamp'
|
fill_rules
|
dict[str, str] | None
|
Per-column aggregation rules. Defaults to
:data: |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Resampled DataFrame. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If resampling is not possible. |
Example
df_4h = resample_ohlcv(df_1h, "1h", "4h")
Source code in src/signalflow/data/resample.py
signalflow.data.resample.align_to_timeframe ¶
align_to_timeframe(df: DataFrame, target_tf: str, *, pair_col: str = 'pair', ts_col: str = 'timestamp', fill_rules: dict[str, str] | None = None) -> pl.DataFrame
Detect source timeframe and resample to target_tf if possible.
If the source timeframe equals the target, returns the data unchanged.
If resampling is not possible (e.g. "3m" → "2m"), emits a
warning and returns the original data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
OHLCV DataFrame. |
required |
target_tf
|
str
|
Desired timeframe. |
required |
pair_col
|
str
|
Pair/group column name. |
'pair'
|
ts_col
|
str
|
Timestamp column name. |
'timestamp'
|
fill_rules
|
dict[str, str] | None
|
Per-column aggregation rules. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Resampled DataFrame, or original if alignment is not possible. |
Example
df_1h = align_to_timeframe(raw_df, "1h")
Source code in src/signalflow/data/resample.py
signalflow.data.resample.detect_timeframe ¶
Auto-detect the timeframe of an OHLCV DataFrame.
Computes the most common timestamp delta per pair and maps it to the closest known timeframe string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
OHLCV DataFrame with at least ts_col and pair_col. |
required |
ts_col
|
str
|
Timestamp column name. |
'timestamp'
|
pair_col
|
str
|
Pair/group column name. |
'pair'
|
Returns:
| Type | Description |
|---|---|
str
|
Detected timeframe string (e.g. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the DataFrame is too small or the delta doesn't match any known timeframe. |
Example
detect_timeframe(hourly_df) '1h'
Source code in src/signalflow/data/resample.py
signalflow.data.resample.can_resample ¶
Check whether source_tf can be resampled to target_tf.
Resampling is possible when target_tf is an exact integer multiple of source_tf (and target >= source).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_tf
|
str
|
Source timeframe (e.g. |
required |
target_tf
|
str
|
Target timeframe (e.g. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Example
can_resample("1h", "4h") True can_resample("1h", "3h") False
Source code in src/signalflow/data/resample.py
signalflow.data.resample.select_best_timeframe ¶
Select the best download timeframe for an exchange.
Strategy
- If the exchange supports target_tf, return it.
- Otherwise pick the largest supported timeframe that evenly divides target_tf.
- If nothing divides evenly, return the smallest supported
timeframe (
"1m"in most cases).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exchange
|
str
|
Exchange name (lowercase, e.g. |
required |
target_tf
|
str
|
Desired target timeframe. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Best timeframe to download. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If exchange is unknown. |
Example
select_best_timeframe("bybit", "8h") '4h' select_best_timeframe("binance", "8h") '8h'
Source code in src/signalflow/data/resample.py
signalflow.data.resample.timeframe_to_minutes ¶
Convert a timeframe string to minutes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tf
|
str
|
Timeframe string (e.g. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of minutes. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If tf is not a recognised timeframe. |
Example
timeframe_to_minutes("4h") 240