Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/user-guide/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,11 @@ Each provider entry configures connection parameters:
| `enabled` | `true` | Toggle provider on/off |
| `api_key` | `null` | API key (use `${ENV_VAR}` format) |
| `rate_limit` | see below | Provider request-rate configuration |
| `extra` | `{}` | Constructor settings specific to the selected provider |
| `extra` | `{}` | Constructor settings specific to the selected provider, plus `ohlc_mode` |

`extra.ohlc_mode` sets how the provider treats bars that break `low <= open, close <= high`:
`strict` (default) rejects the download, `drop` removes those rows, `warn` logs and keeps them.
Adjusted bars can break the rule by a rounding error, so `warn` suits adjusted data.

Rate limiting sub-config:

Expand Down
6 changes: 6 additions & 0 deletions src/ml4t/data/cli/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ def update_all(ctx, config, dataset, dry_run):
datasets = {dataset: datasets[dataset]}

console.print(f"\n[bold]Updating {len(datasets)} dataset(s)[/bold]\n")
failures = 0

# Update each dataset
for ds_name, ds_config in datasets.items():
Expand All @@ -132,6 +133,7 @@ def update_all(ctx, config, dataset, dry_run):
console.print(f"Loaded {len(symbols)} symbols")
except FileNotFoundError as e:
console.print(f"[red]Error: {e}[/red]")
failures += 1
continue
elif ds_config.universe:
universe = cfg.get_universe(ds_config.universe)
Expand All @@ -144,6 +146,7 @@ def update_all(ctx, config, dataset, dry_run):
console.print(
f"[red]Dataset '{ds_name}' must have 'symbols' or 'symbols_file'[/red]"
)
failures += 1
continue

console.print(f"Provider: {provider}")
Expand Down Expand Up @@ -188,11 +191,14 @@ def update_all(ctx, config, dataset, dry_run):

except Exception as e:
console.print(f"[red]FAIL {e}[/red]")
failures += 1
if verbose:
console.print(f"[dim]{e}[/dim]")

console.print()

if failures:
raise click.ClickException(f"Update finished with {failures} failure(s)")
console.print("[bold green]OK Update complete![/bold green]")

except FileNotFoundError:
Expand Down
9 changes: 9 additions & 0 deletions src/ml4t/data/managers/provider_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,10 +295,19 @@ def get_provider(
extra = provider_config.pop("extra", None)
if isinstance(extra, dict):
provider_config = {**extra, **provider_config}
# How OHLC violations are handled is the validation mixin's setting, not a constructor
# argument: adjusted bars can break high >= close by a rounding error.
ohlc_mode = provider_config.pop("ohlc_mode", None)
if ohlc_mode not in (None, "strict", "drop", "warn"):
raise ValueError(
f"Provider '{provider_name}': ohlc_mode must be strict, drop or warn, not {ohlc_mode!r}"
)

# Create provider instance
try:
provider = provider_class(**provider_config)
if ohlc_mode is not None:
provider.ohlc_mode = ohlc_mode
self.providers[provider_name] = provider
logger.info(f"Initialized {provider_name} provider")
return provider
Expand Down
51 changes: 51 additions & 0 deletions tests/test_config_ohlc_update.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""Configuration controls validation through the real update-all workflow."""

from unittest.mock import MagicMock, patch

import pytest
from click.testing import CliRunner

from ml4t.data.cli_interface import cli
from ml4t.data.storage import create_storage


@pytest.mark.parametrize("mode,rows", [("warn", 2), ("drop", 1), ("strict", None), ("loose", None)])
def test_configured_ohlc_mode_controls_stored_adjusted_bars(tmp_path, mode, rows):
config = tmp_path / "data.yaml"
root = tmp_path / "stored"
config.write_text(
f"storage:\n base_path: {root}\n"
"providers:\n - name: alpaca\n type: alpaca\n"
" api_key: test-key\n api_secret: test-secret\n extra:\n"
f" adjustment: all\n ohlc_mode: {mode}\n"
"datasets:\n - name: adjusted\n provider: alpaca\n"
" symbols: [SPY]\n asset_class: equities\n frequency: daily\n"
" start_date: '2026-11-19'\n end_date: '2026-11-20'\n"
)
response = MagicMock(status_code=200)
response.json.return_value = {
"bars": [
{"t": "2026-11-19T05:00:00Z", "o": 100, "h": 101, "l": 99, "c": 100, "v": 1000},
{"t": "2026-11-20T05:00:00Z", "o": 100, "h": 101, "l": 99, "c": 101.01, "v": 1000},
],
"next_page_token": None,
}
with patch("httpx.Client.get", return_value=response) as get:
result = CliRunner().invoke(cli, ["update-all", "--config", str(config)])
storage = create_storage(root)
key = "equities/daily/SPY"
if rows is None:
assert result.exit_code != 0, result.output
assert "OK Update complete!" not in result.output
assert "FAIL" in result.output
assert not storage.exists(key)
if mode == "loose":
get.assert_not_called()
assert "ohlc_mode must be strict, drop or warn" in result.output
else:
assert result.exit_code == 0, result.output
assert "FAIL" not in result.output
stored = storage.read(key).collect()
assert stored.height == rows
assert stored["close"].to_list() == ([100.0, 101.01] if mode == "warn" else [100.0])
assert get.call_args.kwargs["params"]["adjustment"] == "all"
11 changes: 11 additions & 0 deletions tests/test_data_manager_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,17 @@ def test_unavailable_optional_provider_alias_is_not_fatal():
assert not manager.is_available("databento_main")


def test_provider_extra_sets_how_ohlc_violations_are_handled():
"""`ohlc_mode` in a provider's extra reaches its validation, which keeps or drops bad rows."""
manager = ProviderManager({"providers": {"yahoo": {"extra": {"ohlc_mode": "warn"}}}})
assert manager.get_provider("yahoo").ohlc_mode == "warn"
assert ProviderManager({"providers": {}}).get_provider("yahoo").ohlc_mode == "strict"

loose = ProviderManager({"providers": {"yahoo": {"extra": {"ohlc_mode": "loose"}}}})
with pytest.raises(ValueError, match="ohlc_mode must be strict, drop or warn"):
loose.get_provider("yahoo")


class TestMassiveProviderConfig:
"""Tests for Massive provider config and availability wiring."""

Expand Down
Loading