DictSource

In-memory bars from a plain Python dict

DictSource wraps a {market_id: [(timestamp, price), ...]} dict as a DataSource. Useful for unit tests and one-off notebook experiments.

Import

python
from horizon.data import DictSource

Signature

python
DictSource(data: dict[str, list[tuple[datetime, float]]])

Example

python
from datetime import datetime
from horizon.data import DictSource

data = DictSource({
    "AAPL": [
        (datetime(2024, 1, 1), 180.0),
        (datetime(2024, 1, 2), 182.5),
        (datetime(2024, 1, 3), 179.0),
    ],
    "MSFT": [
        (datetime(2024, 1, 1), 400.0),
        (datetime(2024, 1, 2), 402.0),
        (datetime(2024, 1, 3), 405.0),
    ],
})

Chronological yielding

python
def iter_bars(self) -> Iterator[Bar]:
    entries = []
    for mid, series in self._data.items():
        for ts, price in series:
            entries.append((ts, mid, price))
    entries.sort(key=lambda x: (x[0], x[1]))
    for ts, mid, price in entries:
        yield Bar(market_id=mid, timestamp=ts, price=price)

Bars from multiple markets are merged by timestamp and yielded in chronological order.

Use in tests

python
import horizon as hz

def test_my_strategy_handles_crash():
    data = DictSource({
        "AAPL": [
            (datetime(2024, 1, 1), 100),
            (datetime(2024, 1, 2), 95),      # -5%
            (datetime(2024, 1, 3), 90),      # -5%
            (datetime(2024, 1, 4), 80),      # -11%
            (datetime(2024, 1, 5), 70),      # -12%
        ],
    })
    result = hz.run(
        mode="backtest",
        strategies=[MyStrategy()],
        data_source=data,
        ...
    )
    assert result.max_drawdown < 0.35   # risk layer should bound loss

Perfect for writing assertable unit tests against known price sequences.

Next