API Reference¶
API documentation for the ml4t-data library, generated from
source docstrings via mkdocstrings.
DataManager¶
The primary entry point for all data operations. DataManager is a facade that
delegates to focused manager classes for configuration, fetching, storage,
metadata, and batch operations.
from ml4t.data import DataManager
# Fetch-only (no storage)
manager = DataManager()
df = manager.fetch("AAPL", "2024-01-01", "2024-12-31", provider="yahoo")
# With storage for load/update workflows
from ml4t.data.storage import HiveStorage, StorageConfig
storage = HiveStorage(StorageConfig(base_path="./data"))
manager = DataManager(storage=storage)
key = manager.load("AAPL", "2024-01-01", "2024-12-31")
key = manager.update("AAPL")
DataManager
¶
DataManager(
config_path=None,
output_format="polars",
providers=None,
storage=None,
enable_validation=True,
progress_callback=None,
**kwargs,
)
Unified interface for financial data access and storage.
The DataManager provides a single, consistent API for fetching and managing data from multiple providers. It handles:
Data Fetching: - Provider selection based on symbol patterns - Configuration management (YAML, environment, parameters) - Connection pooling and session management - Output format conversion (Polars, pandas, lazy) - Batch fetching with error handling
Storage Operations (when storage configured): - Initial data loading with validation - Incremental updates with gap detection and filling - Atomic generation-based replacement - Progress callbacks for UI integration - Data validation (OHLCV, cross-validation)
Usage:
Fetch only (no storage): >>> manager = DataManager() >>> df = manager.fetch("AAPL", "2024-01-01", "2024-12-31", provider="yahoo")
With storage for load/update: >>> from ml4t.data.storage.hive import HiveStorage >>> from ml4t.data.storage.backend import StorageConfig >>> storage = HiveStorage(StorageConfig(base_path="./data")) >>> manager = DataManager(storage=storage) >>> key = manager.load("AAPL", "2024-01-01", "2024-12-31") >>> key = manager.update("AAPL") # Incremental update
Initialize DataManager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
str | None
|
Path to YAML configuration file |
None
|
output_format
|
str
|
Output format ('polars', 'pandas', 'lazy') |
'polars'
|
providers
|
dict[str, dict[str, Any]] | None
|
Provider-specific configuration overrides |
None
|
storage
|
Any | None
|
Optional storage backend for load/update operations |
None
|
enable_validation
|
bool
|
Enable data validation during load/update |
True
|
progress_callback
|
Callable[[str, float], None] | None
|
Optional callback for progress updates (message, progress) |
None
|
**kwargs
|
Any
|
Additional configuration parameters |
{}
|
fetch
¶
Fetch data for a symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol to fetch |
required |
start
|
str
|
Start date (YYYY-MM-DD) |
required |
end
|
str
|
End date (YYYY-MM-DD) |
required |
frequency
|
str
|
Data frequency (daily, hourly, etc.) |
'daily'
|
provider
|
str | None
|
Optional provider override |
None
|
**kwargs
|
Any
|
Additional provider-specific parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame | LazyFrame | Any
|
Data in configured output format |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no provider found or data fetch fails |
fetch_batch
¶
Fetch data for multiple symbols.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
list[str]
|
List of symbols to fetch |
required |
start
|
str
|
Start date (YYYY-MM-DD) |
required |
end
|
str
|
End date (YYYY-MM-DD) |
required |
frequency
|
str
|
Data frequency |
'daily'
|
**kwargs
|
Any
|
Additional parameters |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, DataFrame | LazyFrame | Any | None]
|
Dictionary mapping symbols to data (or None if fetch failed) |
Raises:
| Type | Description |
|---|---|
ProviderRoutingError
|
If any symbol has no explicit or unambiguous route. The entire batch is rejected before the first provider request. |
batch_load
¶
batch_load(
symbols,
start,
end,
frequency="daily",
provider=None,
max_workers=4,
fail_on_partial=False,
**kwargs,
)
Fetch data for multiple symbols and return in multi-asset stacked format.
batch_load_universe
¶
batch_load_universe(
universe,
start,
end,
frequency="daily",
provider=None,
max_workers=4,
fail_on_partial=False,
**kwargs,
)
Fetch data for all symbols in a pre-defined universe.
batch_load_from_storage
¶
batch_load_from_storage(
symbols,
start,
end,
frequency="daily",
asset_class="equities",
provider=None,
fetch_missing=True,
max_workers=4,
**kwargs,
)
Load multiple symbols with optional fetch fallback and inclusive UTC date bounds.
load
¶
load(
symbol,
start,
end,
frequency="daily",
asset_class="equities",
provider=None,
bar_type="time",
bar_threshold=None,
exchange="UNKNOWN",
calendar=UNSET_CALENDAR,
*,
feed_spec=None,
)
Load data from provider and store it.
import_data
¶
import_data(
data,
symbol,
provider,
frequency="daily",
asset_class="equities",
bar_type="time",
bar_threshold=None,
exchange="UNKNOWN",
calendar=UNSET_CALENDAR,
*,
feed_spec=None,
)
Import external data into storage with metadata.
update
¶
update(
symbol,
frequency="daily",
asset_class="equities",
lookback_days=7,
fill_gaps=None,
provider=None,
initial_start=None,
initial_end=None,
initial_load_days=365,
*,
calendar=UNSET_CALENDAR,
feed_spec=None,
check_gaps=True,
)
Update existing data with incremental fetch.
list_symbols
¶
List all symbols in storage, optionally filtered by metadata.
get_metadata
¶
Get metadata for a specific symbol.
assign_sessions
¶
assign_sessions(
df,
exchange=None,
calendar=UNSET_CALENDAR,
bar_frequency="auto",
*,
feed_spec=None,
)
Assign sessions to daily period labels or intraday timestamps.
complete_sessions
¶
complete_sessions(
df,
exchange=None,
calendar=UNSET_CALENDAR,
fill_gaps=True,
fill_method="none",
zero_volume=False,
*,
feed_spec=None,
)
Expose absent minute positions as nulls without inventing market values.
update_all
¶
Update all stored data matching the filters.
Acquisition compatibility¶
The opt-in ml4t.data.compat.empyrical module adapts acquisition, CSV caches and paths only.
Analytical Empyrical replacements belong in Diagnostic. No legacy package is a Data runtime
dependency. See the migration workflow
and FRED, Fama-French and
Yahoo provider contracts.
empyrical
¶
Opt-in acquisition compatibility, not Empyrical's analytical functions.
get_fama_french
¶
get_fama_french(
start="1-1-1970",
end=None,
datasets=(
"F-F_Research_Data_Factors_daily",
"F-F_Momentum_Factor_daily",
),
)
Return decimal factors/RF on the legacy complete-case UTC date sample.
load_portfolio_risk_factors
¶
get_treasury_yield
¶
Return annual percent yield; legacy filling only affects existing reported rows.
get_symbol_returns_from_yahoo
¶
Return adjusted-close simple returns with upstream exclusive-end semantics and no fill.
get_returns_cached
¶
Keep legacy file-mtime freshness, with validated UTC CSV and atomic replacement.
cache_dir
¶
Use legacy EMPYRICAL_CACHE_DIR, then XDG_CACHE_HOME/empyrical.
Storage¶
StorageConfig¶
Validated configuration for the storage backend. Controls partitioning strategy, compression, locking, and metadata tracking.
from ml4t.data.storage import StorageConfig
# Hive-partitioned storage for minute data
config = StorageConfig(
base_path="./market_data",
strategy="hive",
partition_granularity="day",
compression="zstd",
)
# Flat storage for small datasets
config = StorageConfig(
base_path="./data",
strategy="flat",
compression="snappy",
)
StorageConfig
¶
Bases: BaseModel
Configuration shared by every supported storage entry point.
StorageBackend¶
Abstract base class defining the storage interface. All backends (Hive, Flat) implement this contract.
StorageBackend
¶
Bases: ABC
Abstract base class for storage backends.
Initialize storage backend with configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
StorageConfig
|
Storage configuration |
required |
write
abstractmethod
¶
Write data to storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
LazyFrame | DataFrame
|
Polars LazyFrame to write |
required |
key
|
str
|
Storage key (e.g., "BTC-USD", "SPY") |
required |
metadata
|
dict[str, Any] | None
|
Optional metadata to store alongside data |
None
|
preserve_metadata
|
bool
|
Merge metadata into the current custom block under the write lock |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to written file |
read
abstractmethod
¶
Read data from storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key |
required |
start_date
|
datetime | None
|
Optional start date filter |
None
|
end_date
|
datetime | None
|
Optional end date filter |
None
|
columns
|
list[str] | None
|
Optional columns to select |
None
|
Returns:
| Type | Description |
|---|---|
LazyFrame
|
Polars LazyFrame with requested data |
list_keys
abstractmethod
¶
List all available keys in storage.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of storage keys |
exists
abstractmethod
¶
Check if a key exists in storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key to check |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if key exists |
delete
abstractmethod
¶
Delete data for a key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key to delete |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if deletion was successful |
get_metadata
¶
Get metadata for a key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
Metadata dict or None |
HiveStorage¶
Hive-partitioned storage with configurable time-based partitioning and time-range partition pruning.
from ml4t.data.storage import HiveStorage, StorageConfig
config = StorageConfig(
base_path="./data",
partition_granularity="month", # year, month, day, or hour
)
storage = HiveStorage(config)
# Write data (partitions by timestamp automatically)
storage.write(df, "equities/daily/AAPL")
# Read with partition pruning
from datetime import datetime
lf = storage.read(
"equities/daily/AAPL",
start_date=datetime(2024, 6, 1),
end_date=datetime(2024, 12, 31),
columns=["timestamp", "close", "volume"],
)
df = lf.collect()
HiveStorage
¶
Bases: StorageBackend
Hive partitioned storage with configurable time-based partitioning.
This implementation provides: - Partition pruning for time-based queries - Configurable partition granularity (year, month, day, hour) - Atomic writes with temp file pattern - Metadata tracking in JSON manifests - File locking for concurrent access safety - Polars lazy evaluation throughout
Partition Granularity
Configure via StorageConfig.partition_granularity: - "year": Best for daily data (~252 rows/partition) - "month": Best for hourly data (~720 rows/partition) [default] - "day": Best for minute data (~1,440 rows/partition) - "hour": Best for second/tick data (~3,600 rows/partition)
Example
from ml4t.data.storage import HiveStorage, StorageConfig
For minute data, use day-level partitioning¶
config = StorageConfig(base_path="./data", partition_granularity="day") storage = HiveStorage(config)
Initialize Hive storage backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
StorageConfig
|
Storage configuration |
required |
write
¶
Write data using Hive partitioning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
LazyFrame | DataFrame
|
DataFrame or LazyFrame to write |
required |
key
|
str
|
Storage key (e.g., "BTC-USD" or "equities/daily/AAPL") |
required |
metadata
|
dict[str, Any] | None
|
Optional metadata dict |
None
|
preserve_metadata
|
bool
|
Merge metadata into the current custom block under the write lock |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the committed data generation |
read
¶
Read data from Hive partitions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key |
required |
start_date
|
datetime | None
|
Optional start date filter |
None
|
end_date
|
datetime | None
|
Optional end date filter |
None
|
columns
|
list[str] | None
|
Optional columns to select |
None
|
Returns:
| Type | Description |
|---|---|
LazyFrame
|
LazyFrame with requested data |
list_keys
¶
List all keys in storage.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of storage keys |
exists
¶
Check if key exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if key exists |
delete
¶
Delete all data for a key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if successful |
get_latest_timestamp
¶
Get the latest timestamp for a symbol from a provider.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol identifier |
required |
provider
|
str
|
Data provider name |
required |
Returns:
| Type | Description |
|---|---|
datetime | None
|
Latest timestamp in the dataset, or None if no data exists |
save_chunk
¶
Save an incremental data chunk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame with OHLCV data |
required |
symbol
|
str
|
Symbol identifier |
required |
provider
|
str
|
Data provider name |
required |
start_time
|
datetime
|
Start time of this chunk |
required |
end_time
|
datetime
|
End time of this chunk |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Path to the saved chunk file |
update_combined_file
¶
Update the main combined file with new data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
New data to append |
required |
symbol
|
str
|
Symbol identifier |
required |
provider
|
str
|
Data provider name |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of new records added (after deduplication) |
read_data
¶
Read data for a symbol with optional time filtering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol identifier |
required |
provider
|
str
|
Data provider name |
required |
start_time
|
datetime | None
|
Optional start time filter |
None
|
end_time
|
datetime | None
|
Optional end time filter |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with filtered data |
update_metadata
¶
Update metadata after incremental update.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol identifier |
required |
provider
|
str
|
Data provider name |
required |
last_update
|
datetime
|
Timestamp of this update |
required |
records_added
|
int
|
Number of records added |
required |
chunk_file
|
str
|
Name of the chunk file saved |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no published dataset exists for the provider and symbol. |
FlatStorage¶
Simple single-file-per-key storage. Suitable for smaller datasets or when partition pruning is not beneficial.
from ml4t.data.storage import FlatStorage, StorageConfig
config = StorageConfig(base_path="./data", strategy="flat")
storage = FlatStorage(config)
storage.write(df, "reference/spy")
lf = storage.read("reference/spy")
FlatStorage
¶
Bases: StorageBackend
Flat file storage without partitioning.
This implementation provides: - Simple single-file storage per key - Atomic writes with temp file pattern - Metadata tracking in JSON manifests - File locking for concurrent access safety - Polars lazy evaluation throughout
Initialize flat storage backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
StorageConfig
|
Storage configuration |
required |
write
¶
Write data as a single file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
LazyFrame | DataFrame
|
Data to write |
required |
key
|
str
|
Storage key (e.g., "BTC-USD") |
required |
metadata
|
dict[str, Any] | None
|
Optional metadata |
None
|
preserve_metadata
|
bool
|
Merge metadata into the current custom block under the write lock |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to written file |
read
¶
Read data from flat file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key |
required |
start_date
|
datetime | None
|
Optional start date filter |
None
|
end_date
|
datetime | None
|
Optional end date filter |
None
|
columns
|
list[str] | None
|
Optional columns to select |
None
|
Returns:
| Type | Description |
|---|---|
LazyFrame
|
LazyFrame with requested data |
list_keys
¶
List all keys in storage.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of storage keys |
exists
¶
Check if key exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if key exists |
delete
¶
Delete data for a key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if successful |
create_storage¶
Factory function for creating storage backends from a strategy name.
from ml4t.data.storage import create_storage
storage = create_storage("./data", strategy="hive", partition_granularity="day")
create_storage
¶
Create a storage backend with the specified strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_path
|
StorageConfig | str | Path
|
Base directory or a complete storage configuration |
required |
strategy
|
str | StorageStrategy | None
|
Storage strategy ("hive" or "flat") when passing a directory |
None
|
**kwargs
|
Any
|
Additional configuration options |
{}
|
Returns:
| Type | Description |
|---|---|
StorageBackend
|
Configured storage backend |
Example
storage = create_storage("/data", strategy="hive") storage.write(df.lazy(), "BTC-USD")
Providers¶
BaseProvider¶
Abstract base class for all data providers. Composes rate-limiting, circuit-breaker, validation, and HTTP session mixins into a single base.
Concrete providers implement either:
_fetch_and_transform_data()for a single-step workflow, or_fetch_raw_data()+_transform_data()for a two-step workflow.
from ml4t.data.providers.base import BaseProvider
import polars as pl
class MyProvider(BaseProvider):
@property
def name(self) -> str:
return "my_provider"
def _fetch_and_transform_data(self, symbol, start, end, frequency):
# Fetch from API and return canonical OHLCV DataFrame
...
BaseProvider
¶
Bases: RateLimitMixin, CircuitBreakerMixin, ValidationMixin, SessionMixin, ABC
Enhanced base provider composing all mixins.
All providers must return OHLCV data in the canonical schema with columns in standard order: [timestamp, symbol, open, high, low, close, volume].
Each provider must implement either: - _fetch_and_transform_data() for single-step implementation - _fetch_raw_data() + _transform_data() for two-step implementation
Class Variables
DEFAULT_RATE_LIMIT: Default (calls, period_seconds) for rate limiting FREQUENCY_MAP: Mapping of frequency names to provider-specific values CIRCUIT_BREAKER_CONFIG: Circuit breaker failure threshold and reset timeout
Key Contracts
- Columns always in order: timestamp, symbol, open, high, low, close, volume
- Timestamps are Datetime type
- OHLCV values are Float64
- Symbol is uppercase String
- Data sorted by timestamp ascending
- No duplicate timestamps
Initialize base provider with common infrastructure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rate_limit
|
tuple[int, float] | None
|
Tuple of (calls, period_seconds) for rate limiting |
None
|
session_config
|
dict[str, Any] | None
|
HTTP session configuration |
None
|
circuit_breaker_config
|
dict[str, Any] | None
|
Circuit breaker configuration |
None
|
fetch_ohlcv
¶
Template method for fetching OHLCV data.
This method implements the common workflow: 1. Validate inputs 2. Apply rate limiting 3. Fetch and transform data (provider-specific) 4. Validate and normalize data
Providers can implement either: - _fetch_and_transform_data() for single-step implementation - _fetch_raw_data() + _transform_data() for two-step implementation
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The symbol to fetch data for |
required |
start
|
str
|
Start date in YYYY-MM-DD format (inclusive) |
required |
end
|
str
|
End date in YYYY-MM-DD format (see note below) |
required |
frequency
|
str
|
Data frequency (daily, minute, etc.) |
'daily'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with OHLCV data in canonical schema: |
DataFrame
|
[timestamp, symbol, open, high, low, close, volume] |
Note
Date range semantics vary by provider: - Most providers: Both start and end are INCLUSIVE - Yahoo Finance: end is EXCLUSIVE (internally adds 1 day)
fetch_ohlcv_async
async
¶
Async wrapper around fetch_ohlcv using a thread pool.
Providers with native async support should override this method.
capabilities
¶
Return provider capabilities (default implementation).
Override in subclasses to provide accurate capabilities.
ProviderCapabilities¶
Frozen dataclass describing what a provider supports (intraday, crypto, forex, futures, authentication requirements, rate limits).
from ml4t.data.providers.protocols import ProviderCapabilities
caps = ProviderCapabilities(
supports_intraday=True,
supports_crypto=True,
requires_api_key=True,
rate_limit=(120, 60.0), # 120 calls per 60 seconds
)
ProviderCapabilities
dataclass
¶
ProviderCapabilities(
supports_intraday=False,
supports_crypto=False,
supports_forex=False,
supports_futures=False,
requires_api_key=False,
max_history_days=None,
rate_limit=(60, 60.0),
)
Describes what a provider can do.
Attributes:
| Name | Type | Description |
|---|---|---|
supports_intraday |
bool
|
Can fetch minute/hourly data |
supports_crypto |
bool
|
Handles cryptocurrency symbols |
supports_forex |
bool
|
Handles forex pairs |
supports_futures |
bool
|
Handles futures contracts |
requires_api_key |
bool
|
Needs authentication |
max_history_days |
int | None
|
Maximum historical data available |
rate_limit |
tuple[int, float]
|
(calls, period_seconds) tuple |
OHLCVProvider (Protocol)¶
Structural typing protocol for OHLCV providers. Any class implementing
name, fetch_ohlcv(), and capabilities() satisfies this protocol
without inheriting from BaseProvider.
OHLCVProvider
¶
Bases: Protocol
Protocol for OHLCV data providers.
Any class implementing these methods is considered an OHLCVProvider, regardless of inheritance. This enables duck typing with type safety.
Example
class MyCustomProvider: ... @property ... def name(self) -> str: ... return "custom" ... ... def fetch_ohlcv(self, symbol, start, end, frequency="daily"): ... # Custom implementation ... pass ... ... def capabilities(self) -> ProviderCapabilities: ... return ProviderCapabilities() ... isinstance(MyCustomProvider(), OHLCVProvider) # True
fetch_ohlcv
¶
Fetch OHLCV data for a symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol to fetch (e.g., 'AAPL', 'BTCUSDT') |
required |
start
|
str
|
Start date in YYYY-MM-DD format |
required |
end
|
str
|
End date in YYYY-MM-DD format |
required |
frequency
|
str
|
Data frequency ('daily', 'hourly', 'minute', etc.) |
'daily'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: [timestamp, symbol, open, high, low, close, volume] |
Configuration¶
Config¶
Pydantic model for top-level library configuration. Reads ML4T_DATA_PATH and
ML4T_DATA_LOG_LEVEL. Former QLDM names are covered by the
migration guide.
from ml4t.data import Config
# Use defaults
config = Config()
# Override data root
config = Config(data_root="/mnt/fast/market_data", log_level="DEBUG")
Config
¶
Bases: BaseModel
Main configuration for ml4t-data.
Initialize config with environment variables.
validation
class-attribute
instance-attribute
¶
RetryConfig¶
Configuration for automatic retry with exponential backoff.
RetryConfig
¶
Bases: BaseModel
Retry configuration.
CacheConfig¶
Configuration for in-memory caching.
CacheConfig
¶
Bases: BaseModel
Cache configuration.
Exceptions¶
All exceptions inherit from ML4TDataError, which carries an optional
details dictionary for structured error context.
ML4TDataError
├── ProviderError
│ ├── NetworkError
│ │ └── RateLimitError
│ ├── AuthenticationError
│ ├── DataValidationError
│ ├── SymbolNotFoundError
│ └── DataNotAvailableError
├── StorageError
│ └── LockError
├── ConfigurationError
└── CircuitBreakerOpenError
ML4TDataError¶
ML4TDataError
¶
Bases: Exception
Base exception for all ml4t-data errors.
Initialize ml4t-data error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message |
required |
details
|
dict[str, Any] | None
|
Optional dictionary with error details |
None
|
ProviderError¶
ProviderError
¶
Bases: ML4TDataError
Base exception for provider-related errors.
Initialize provider error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
str
|
Provider name |
required |
message
|
str
|
Error message |
required |
details
|
dict[str, Any] | None
|
Optional error details |
None
|
NetworkError¶
NetworkError
¶
NetworkError(
provider,
message="Network error occurred",
details=None,
retry_after=None,
retryable=True,
)
Bases: ProviderError
Network-related errors (connection, timeout, etc.).
Initialize network error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
str
|
Provider name |
required |
message
|
str
|
Error message |
'Network error occurred'
|
details
|
dict[str, Any] | None
|
Optional error details |
None
|
retry_after
|
float | None
|
Seconds to wait before retry |
None
|
retryable
|
bool
|
Whether a higher-level operation should retry this error |
True
|
RateLimitError¶
RateLimitError
¶
Bases: NetworkError
Rate limit exceeded error.
Initialize rate limit error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
str
|
Provider name |
required |
retry_after
|
float | None
|
Seconds to wait before retry |
None
|
remaining
|
int | None
|
Remaining API calls |
None
|
limit
|
int | None
|
API call limit |
None
|
retryable
|
bool
|
Whether a higher-level operation should retry this error |
True
|
AuthenticationError¶
AuthenticationError
¶
DataValidationError¶
DataValidationError
¶
Bases: ProviderError
Data validation errors.
Initialize data validation error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
str
|
Provider name |
required |
message
|
str
|
Error message |
required |
field
|
str | None
|
Field that failed validation |
None
|
value
|
Any | None
|
Invalid value |
None
|
details
|
dict[str, Any] | None
|
Optional error details |
None
|
SymbolNotFoundError¶
SymbolNotFoundError
¶
Bases: ProviderError
Symbol not found or invalid.
Initialize symbol not found error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
str
|
Provider name |
required |
symbol
|
str
|
The symbol that was not found |
required |
details
|
dict[str, Any] | None
|
Optional error details |
None
|
DataNotAvailableError¶
DataNotAvailableError
¶
Bases: ProviderError
Data not available for the requested period.
Initialize data not available error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
str
|
Provider name |
required |
symbol
|
str
|
Symbol requested |
required |
start
|
str | None
|
Start date |
None
|
end
|
str | None
|
End date |
None
|
frequency
|
str | None
|
Data frequency |
None
|
details
|
dict[str, Any] | None
|
Optional error details |
None
|
StorageError¶
StorageError
¶
Bases: ML4TDataError
Storage-related errors.
Initialize storage error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message |
required |
key
|
str | None
|
Storage key involved |
None
|
details
|
dict[str, Any] | None
|
Optional error details |
None
|
LockError¶
LockError
¶
Bases: StorageError
File locking errors.
Initialize lock error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key |
required |
timeout
|
float
|
Lock timeout that was exceeded |
required |
details
|
dict[str, Any] | None
|
Optional error details |
None
|
ConfigurationError¶
ConfigurationError
¶
Bases: ML4TDataError
Configuration-related errors.
Initialize configuration error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message |
required |
parameter
|
str | None
|
Configuration parameter involved |
None
|
details
|
dict[str, Any] | None
|
Optional error details |
None
|
CircuitBreakerOpenError¶
CircuitBreakerOpenError
¶
Bases: ML4TDataError
Circuit breaker is open and preventing calls.
Initialize circuit breaker open error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message |
'Circuit breaker is open'
|
failure_count
|
int | None
|
Number of failures that caused circuit to open |
None
|
details
|
dict[str, Any] | None
|
Optional error details |
None
|
Futures Expiry Rolls¶
TimeBasedRoll selects the nearest available contract until its configured pre-expiry trigger.
FirstNoticeDateRoll delegates the same calendar selection while retaining its existing
first-notice offset convention and five-session cash-settled fallback.
| Mode | Offset units | Calendar behavior |
|---|---|---|
use_business_days=True (default) |
Authoritative sessions strictly before expiration | Explicit calendar, then feed_spec, then NYSE |
use_business_days=False |
Elapsed civil days | No session counting; an explicitly disabled calendar is allowed |
Session-count mode with calendar=None |
Unsupported observation-based expiry offset | Raises clearly; does not substitute NYSE or 24/7 |
The legacy use_business_days name now counts the selected exchange's sessions rather than
weekdays. calendar="24/7" counts a real continuous schedule. Contract exchange identity does not
select a calendar. Pass the feed declaration explicitly when constructing a roll strategy from
stored metadata. Named calendars are validated before selection.
An offset of zero uses expiration itself. A missing scheduled trigger does not move the trigger backward to an observed date: selection switches at the first eligible later observation, subject to the existing contract availability and paired-price checks. Explicit elapsed-day mode also stops snapping its target backward. Neither mode reinterprets missing data as a closure or changes elapsed days into row counts.
TimeBasedRoll
¶
TimeBasedRoll(
days_before_expiration=5,
use_business_days=True,
*,
calendar=UNSET_CALENDAR,
feed_spec=None,
)
Bases: RollStrategy
Select the nearest contract until its configured pre-expiry roll date.
use_business_days=True counts authoritative sessions strictly before expiration.
Explicit calendar overrides feed_spec, then NYSE; an exchange identity does not
select a calendar. A missing target session never moves the trigger to an earlier observation.
use_business_days=False selects elapsed civil days, not an observation count.
Calendar-free row-based expiry offsets are unsupported in session-count mode.
Equal expirations use the declared tie_breaker_col,then contract identity;the default is symbol.
FirstNoticeDateRoll
¶
Bases: RollStrategy
Select contracts before supplied dated notice facts,or a legacy root-offset estimate.
A first_notice_date column takes precedence over root estimates. Without actual dates,the existing ContractSpec fallback remains;zero notice days is distinct from an unknown offset.
Versioned individual-contract inputs¶
prepare_futures_inputs prepares individual bars, dated definitions, independently available
volume/OI facts, one current selection per root/venue and paired source roll marks. It does not
execute a continuous series or infer fills, margin or settlement. See the
offline migration recipe.
prepare_futures_inputs
¶
prepare_futures_inputs(
bars,
definitions,
*,
as_of,
roll_strategy=None,
feed_spec=None,
calendar=UNSET_CALENDAR,
price_quote_unit=None,
definitions_feed_spec=None,
identity_mode="stable_id",
)
Prepare individual source bars and one current research selection per root/venue.
A causal call uses only source revisions and ranking metrics published by as_of. Call again at each actual decision cutoff for historical decisions;this does not backdate a current source-vintage selection into previously executed account history. The existing strategy's observed-session lag and confirmation defaults remain unchanged. Bars are unadjusted captures; metrics carries separately eligible OI/volume facts,not a guarantee that every raw bar field was published together. Missing OI availability is never copied from a price timestamp.
FuturesInputs
dataclass
¶
Source bars,dated definitions,eligible metric facts and one current decision per chain.
Bars retain their raw source fields and field-specific availability declarations. A later OI
publication in a captured bar is not eligible merely because its price was already available.
Only metrics and the derived selection use that field's known-at cutoff. Roll proposals
contain actual raw paired observations,not continuous prices,execution fills or account policy.
Price-table representations¶
Convert one price field between native long observations and a pandas clock-by-asset panel. The functions preserve supplied values and missing cells; they do not fill prices, infer availability or calculate returns. Other observation fields remain in the original table. The panel's attrs retain the declared feed, source dtypes and sparse presence information. Default metadata supports pandas Parquet round trips; caller-supplied provenance must also be JSON-serializable to use pandas' metadata export.
See the offline migration recipe for required input columns, mapping conflicts and the qualified consumer versions.
to_price_panel
¶
to_price_panel(
data,
*,
feed_spec=None,
timestamp_col=None,
entity_col=None,
price_col=None,
metadata=None,
)
Project a price field to a pandas clock-by-asset panel without filling cells.
Clock and asset order follow first occurrence. Duplicate/null keys and ambiguous mappings
fail. Other observation fields remain in the caller's original table, not in the price panel.
attrs['ml4t_price_panel'] retains the feed, source dtype, metadata and an observation mask
distinguishing an observed null from an absent asset/clock pair. Keep these attrs for a sparse
inverse. The caller must keep per-observation availability and revision facts separately.
from_price_panel
¶
Return clock-major native price observations, retaining nulls and typed asset IDs.
Panels from to_price_panel retain sparse presence and source dtypes in attrs. An ordinary
pandas panel without those attrs treats every cell, including a null, as an observation.
A stale mask after changing panel axes is rejected, never silently realigned or filled.
Corporate-action input preparation¶
Validate versioned source facts or apply supplied per-observation factors without changing the existing split/dividend kernels. Source facts do not mutate broker positions or cash. Unavailable terms remain explicit; requesting missing applicable terms fails before output.
See the offline action migration recipe for ratio direction, required source fields and native versus vendor adjustment definitions.
prepare_action_inputs
¶
prepare_action_inputs(
actions,
instruments=None,
*,
feed_spec=None,
calendar=UNSET_CALENDAR,
split_convention=None,
required_terms=(),
)
Validate versioned action facts and retain unavailable terms as explicit coverage.
Defaults use asset and effective_at; map existing names with feed_spec. Stable
IDs, event/revision IDs, action kind and source are required. Optional instruments is a
captured unique-ID table, not a dated registry. All dates, source columns and revisions remain
in the result. Unknown availability is never copied from an ex-date or a download timestamp.
Split ratios are new shares per old share. Explicit price_factor reciprocates imported
legacy ratios, retaining raw_split_ratio and source_split_convention. Cash, stock
distributions and mergers remain facts, not positions or cash flows. missing_terms records
unavailable applicable terms; requesting any of them in required_terms fails atomically.
A declared calendar is retained in preparation_calendar; omission is not replaced by NYSE.
apply_adjustment_factors
¶
Multiply raw prices by supplied per-observation factors without changing their definition.
Price factors must cover exactly the unique timestamp/entity keys. Preserve raw columns,
add adj_<price> and explicit factors, and retain the supplied method. Volume is adjusted
only when a volume factor is supplied. No dividend factor, currency conversion, missing row,
source availability or unknown volume factor is inferred.
Dated identity and known-at history inputs¶
Use captured identity intervals and source availability for preparation,not an asset database or runtime history request. The offline dated-history recipe shows symbol normalization,pre-entry observations and actual source revisions.
InstrumentRegistry
¶
Resolve dated source symbols to stable IDs without building an asset database.
Identity rows require asset,symbol,exchange,instrument_type,source,revision_id,valid_from and
optional valid_to/available_at. valid_to is exclusive. Listing/delisting fields remain
source facts; interval endpoints,not missing prices,declare identity coverage. Optional
memberships have asset,universe,source,revision_id and the same interval/availability fields.
as_of=None is explicitly retrospective. A causal cutoff requires actual availability.
identities
property
¶
Return a detached captured identity table,including source revisions.
memberships
property
¶
Return captured membership provenance,or None when no coverage was supplied.
from_frame
classmethod
¶
Validate captured identity/membership intervals without changing caller tables.
resolve
¶
Resolve exactly one stable ID,or raise for missing/ambiguous dated symbols.
lifetimes
¶
Return declared identity coverage,optionally known-at membership on a date.
Absence of a declared row does not establish delisting or completeness of an entire
universe. Original membership intervals and revision provenance remain in memberships.
prepare_adjusted_history
¶
prepare_adjusted_history(
prices,
actions,
*,
as_of,
feed_spec=None,
calendar=UNSET_CALENDAR,
basis=None,
action_coverage="unknown",
ex_date_closes=None,
factors=None,
factor_method=None,
instruments=None,
identity_mode="stable_id",
action_feed_spec=None,
)
Prepare source revisions available at a cutoff,or explicitly retrospective latest history.
Price revisions require source,revision_id,available_at and unique asset/timestamp keys per revision. New handoffs use timestamp/asset; FeedSpec maps existing physical price columns. Raw values and missing observations are retained. Adjustment requires an explicit declaration of complete source action coverage for the supplied range,not inference from missing events. Native total-return factors use the actual available ex-date close. Intraday callers supply a separately captured ex_date_closes table with the same units and revision/availability keys. No action cash,positions,synthetic prices,FX or historical availability is inferred.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prices
|
DataFrame | DataFrame
|
Raw observations with source,revision_id,available_at and declared entity/clock. |
required |
actions
|
DataFrame | DataFrame | None
|
Captured action revisions,or None. Absence does not declare complete coverage. |
required |
as_of
|
datetime | str | None
|
Availability cutoff instant;None explicitly selects retrospective latest revisions. |
required |
feed_spec
|
Any | None
|
Shared observation clock,entity,price,calendar and bar-grid declaration. |
None
|
calendar
|
str | None | CalendarUnset
|
Explicit schedule override;None disables schedules,omission preserves the feed. |
UNSET_CALENDAR
|
basis
|
Literal['raw', 'split_adjusted', 'total_return'] | None
|
raw,split_adjusted or total_return. Native default is total_return. Supplied factors require an explicit basis and method;native defaults are not substituted. |
None
|
action_coverage
|
Literal['complete', 'unknown']
|
Caller declaration of complete or unknown source event coverage for the requested price range. Native adjusted history requires complete coverage. |
'unknown'
|
ex_date_closes
|
DataFrame | DataFrame | None
|
Captured native cash-factor close facts keyed by asset/ex_date with source,revision_id,available_at,reference price and currency. Required intraday. |
None
|
factors
|
DataFrame | DataFrame | None
|
Exact per-observation supplied factors. Causal inputs require version identity, actual availability and one known basis_at instant per asset,not a future/stale basis. |
None
|
factor_method
|
str | None
|
Name of the supplied financial definition,retained in output provenance. |
None
|
instruments
|
InstrumentRegistry | None
|
Optional captured dated registry for ID validation or symbol normalization. |
None
|
identity_mode
|
Literal['stable_id', 'symbol']
|
stable_id validates declared IDs;symbol resolves the feed entity column by date and optional exchange. Source symbols remain and stable IDs are added. |
'stable_id'
|
action_feed_spec
|
Any | None
|
Separate physical action clock/entity mappings when source names differ. |
None
|
Returns:
| Type | Description |
|---|---|
AdjustedHistory
|
Prepared raw/derived prices,selected actions,used identity provenance and between-endpoint |
AdjustedHistory
|
missing/null coverage. metadata.feed_spec points consumers to the requested basis and |
AdjustedHistory
|
stable IDs;input_feed_spec and source_feed_spec describe input/raw physical fields. |
AdjustedHistory
dataclass
¶
Prepared native prices,facts,coverage and explicit source/basis declarations.
Portable input capture¶
Capture selected tables and caller-declared effective configuration, then verify all members before returning reconstructed native frames. See the storage contract and migration recipe. Optional bundle exchange uses standard Zipline readers/writers only in the conversion environment.
SnapshotTable
dataclass
¶
One frame or storage key, its role, and explicit source declarations.
InputSnapshot
dataclass
¶
Eager tables returned only after every declared file has been verified.
export_snapshot
¶
export_snapshot(
path,
tables,
*,
effective_config,
artifacts,
required_tables=None,
unavailable=None,
calendar=UNSET_CALENDAR,
)
Copy an immutable input set; existing different snapshots are never overwritten.
Per-table declarations require source_revision, identity_namespace, units, as_of, price_basis, share_basis and revisions. Explicit null retains an unknown optional fact. Consumer policies and artifact hashes come from the caller, never from guessed defaults.
read_snapshot
¶
Validate manifest, every file hash and schema before returning any input tables.
export_bundle
¶
export_bundle(
bundle,
path,
*,
namespace,
source_revision,
sids,
start,
end,
frequencies=("daily",),
frequency_bounds=None,
calendar=UNSET_CALENDAR,
effective_config=None,
artifacts=None,
)
Read a bounded loaded BundleData without opening private stores or mutating it.
The caller owns BundleData.close(). Namespace and source revision must be persistent. Unknown currency/publication/merger terms stay unknown. Exported symbol intervals are the reader's lookup policy, not inferred listing intervals. Daily and minute bounds are inclusive.
make_bundle_ingest
¶
Return a standard Zipline ingest callable; validate before invoking any writer.