Skip to content

Market data

Where prices come from, separate from where orders go. Every source follows the same conventions (half-open windows, bars stamped at their close, raw prices, volume in lots), so sources can be chained and cached freely.

Warning

Every source except PriceCache makes network calls. FinMind and Yahoo limit how much history and how many requests a free account gets.

cjtrade.pkgs.marketdata.base

The MarketData interface: where prices come from.

A MarketData knows nothing about accounts or orders. A broker that can only place orders needs no MarketData of its own, and a backtest needs nothing but a MarketData.

Conventions every implementation follows, so that sources can be swapped, chained and cached without changing what a strategy sees:

  • Windows are half-open, start <= bar.timestamp < end. start and end may be a date, a datetime or an ISO string; a date means 00:00 of that day, so end="2025-09-02" stops before 2 September.
  • Timestamps are naive Asia/Taipei time.
  • Intraday bars are stamped at the minute they CLOSE: the first 1m bar of a session is 09:01, a 5m bar covering 09:00-09:05 is stamped 09:05.
  • Daily bars are stamped 09:00 on the session date and close at 13:30.
  • Only CLOSED bars are returned: a bar is left out until its close is at or before the source's "now" (the wall clock for a live source, the simulated clock for ArenaX). So the last bar of any answer is complete, and a replay cannot see a bar it has not reached. Ticks follow the same rule.
  • Prices are raw, not adjusted for dividends or splits.
  • Volume is in lots (張, 1,000 shares) for listed and OTC stocks.

Snapshots describe the trading day so far: open, high and low since the open, close the latest price, volume the day's total, and timestamp the time of the quote.

Granularity: ticks are the finest data, then 1m bars, then everything coarser, which is aggregated from 1m by :func:~cjtrade.pkgs.marketdata.aggregate.aggregate. A source that only has ticks can build 1m bars from them with :func:~cjtrade.pkgs.marketdata.aggregate.bars_from_ticks.

Setting CJTRADE_OFFLINE=1 makes every network source raise :class:MarketDataUnavailable, so only the local price cache answers.

Intervals are named 1m 5m 15m 30m 1h 1d. A source declares which ones it serves through :attr:MarketData.capabilities, and asking for anything else raises :class:UnsupportedRequest rather than returning an empty list, so a :class:~cjtrade.pkgs.marketdata.compose.Fallback can move on to the next source and a cache never records a window it was not given.

MarketData

Bases: ABC

A source of prices. Subclass it to plug in a new one.

Only :meth:get_kbars and :attr:capabilities are required. The other methods raise :class:UnsupportedRequest unless overridden, and capabilities must say which of them a subclass implements.

Examples:

class MyCSV(MarketData):
    name = "my-csv"

    @property
    def capabilities(self):
        return Capabilities(intervals=frozenset({"1d"}))

    def get_kbars(self, symbol, start, end, interval="1d"):
        self.require_interval(interval)
        start, end = to_window(start, end)
        return [k for k in read_my_csv(symbol) if start <= k.timestamp < end]

capabilities abstractmethod property

What this source can serve.

now()

The moment this source answers as of; a bar later than it is not closed.

The wall clock. Override it to replay or to test against a fixed time.

Source code in src/cjtrade/pkgs/marketdata/base.py
149
150
151
152
153
154
def now(self) -> datetime:
    """The moment this source answers as of; a bar later than it is not closed.

    The wall clock. Override it to replay or to test against a fixed time.
    """
    return datetime.now()

supports(interval)

Return whether get_kbars accepts interval.

Source code in src/cjtrade/pkgs/marketdata/base.py
156
157
158
def supports(self, interval: str) -> bool:
    """Return whether ``get_kbars`` accepts `interval`."""
    return interval in self.capabilities.intervals

require_interval(interval)

Raise UnsupportedRequest unless interval is supported.

Source code in src/cjtrade/pkgs/marketdata/base.py
160
161
162
163
164
165
def require_interval(self, interval: str) -> None:
    """Raise UnsupportedRequest unless `interval` is supported."""
    if not self.supports(interval):
        raise UnsupportedRequest(
            f"{self.name} does not serve {interval!r} bars "
            f"(it serves {sorted(self.capabilities.intervals) or 'none'})")

get_kbars(symbol, start, end, interval='1m') abstractmethod

Return the closed bars of symbol with start <= timestamp < end.

Parameters:

Name Type Description Default
symbol str

TWSE/TPEx code, e.g. "2330".

required
start (date, datetime or str)

Half-open window; see the module docstring.

required
end (date, datetime or str)

Half-open window; see the module docstring.

required
interval str

One of capabilities.intervals.

'1m'

Returns:

Type Description
list of Kbar

Oldest first. Empty when the window holds no bars.

Raises:

Type Description
UnsupportedRequest

The interval, or the data behind it, is not available here.

MarketDataUnavailable

The source could not be reached.

Source code in src/cjtrade/pkgs/marketdata/base.py
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
@abstractmethod
def get_kbars(self, symbol: str, start: TimeLike, end: TimeLike,
              interval: str = "1m") -> List[Kbar]:
    """Return the closed bars of `symbol` with ``start <= timestamp < end``.

    Parameters
    ----------
    symbol : str
        TWSE/TPEx code, e.g. ``"2330"``.
    start, end : date, datetime or str
        Half-open window; see the module docstring.
    interval : str
        One of ``capabilities.intervals``.

    Returns
    -------
    list of Kbar
        Oldest first. Empty when the window holds no bars.

    Raises
    ------
    UnsupportedRequest
        The interval, or the data behind it, is not available here.
    MarketDataUnavailable
        The source could not be reached.
    """

get_snapshots(symbols)

Return the latest quote of each symbol.

Raises:

Type Description
UnsupportedRequest

Unless the subclass implements it.

Source code in src/cjtrade/pkgs/marketdata/base.py
194
195
196
197
198
199
200
201
202
def get_snapshots(self, symbols: List[str]) -> List[Snapshot]:
    """Return the latest quote of each symbol.

    Raises
    ------
    UnsupportedRequest
        Unless the subclass implements it.
    """
    raise UnsupportedRequest(f"{self.name} does not serve snapshots")

get_bid_ask(symbol, intraday_odd=False)

Return the current order book of symbol.

Raises:

Type Description
UnsupportedRequest

Unless the subclass implements it.

Source code in src/cjtrade/pkgs/marketdata/base.py
204
205
206
207
208
209
210
211
212
def get_bid_ask(self, symbol: str, intraday_odd: bool = False) -> BidAsk:
    """Return the current order book of `symbol`.

    Raises
    ------
    UnsupportedRequest
        Unless the subclass implements it.
    """
    raise UnsupportedRequest(f"{self.name} does not serve bid/ask")

get_ticks(symbol, day)

Return the trade prints of symbol on day up to now, oldest first.

Raises:

Type Description
UnsupportedRequest

Unless the subclass implements it.

Source code in src/cjtrade/pkgs/marketdata/base.py
214
215
216
217
218
219
220
221
222
def get_ticks(self, symbol: str, day: TimeLike) -> List[Tick]:
    """Return the trade prints of `symbol` on `day` up to now, oldest first.

    Raises
    ------
    UnsupportedRequest
        Unless the subclass implements it.
    """
    raise UnsupportedRequest(f"{self.name} does not serve ticks")

Capabilities(intervals=frozenset(), snapshots=False, bid_ask=False, ticks=False) dataclass

What a MarketData can serve.

Attributes:

Name Type Description
intervals frozenset of str

Bar intervals get_kbars accepts.

snapshots bool

Whether get_snapshots works.

bid_ask bool

Whether get_bid_ask works.

ticks bool

Whether get_ticks works.

MarketDataError

Bases: Exception

Base class for market data failures.

UnsupportedRequest

Bases: MarketDataError

The source cannot serve this kind of request at all.

Not a transient failure: asking again will not help. Raised for an interval the source does not offer, data behind a plan the account does not have, or a method the source does not implement.

MarketDataUnavailable

Bases: MarketDataError

The source could not answer this time: network, rate limit, outage.

cjtrade.pkgs.marketdata.compose

Combine MarketData sources: try several in turn, or put a cache in front.

Fallback(sources)

Bases: MarketData

Ask each source in order; the first non-empty answer wins.

A source that does not support the request is skipped. One that fails or returns nothing is logged and the next one is asked. Its capabilities are the union of its sources'.

Parameters:

Name Type Description Default
sources sequence of MarketData

In order of preference.

required

Attributes:

Name Type Description
last_source str or None

Name of the source that answered the latest get_kbars call.

Examples:

market = Fallback([FinMindMarketData(token="..."), YFinanceMarketData()])
market.get_kbars("2330", "2025-01-01", "2025-07-01", "1d")   # FinMind
market.get_kbars("2330", "2025-06-02", "2025-06-03", "1m")   # yfinance
Source code in src/cjtrade/pkgs/marketdata/compose.py
55
56
57
58
59
60
def __init__(self, sources: Sequence[MarketData]) -> None:
    if not sources:
        raise ValueError("Fallback needs at least one source")
    self.sources = list(sources)
    self.name = "+".join(s.name for s in self.sources)
    self.last_source = None

Cached(source, cache=None)

Bases: MarketData

Serve bars from a local cache, fetching only the windows it lacks.

Each missing window is fetched in chunks (30 days for intraday bars, a year for daily ones). A chunk that comes back with bars is stored and recorded as fetched; one that comes back empty is not, so it is asked for again next time rather than treated as permanently empty. A recorded window never reaches past the present.

Snapshots, bid/ask and ticks are live data and pass straight through.

Parameters:

Name Type Description Default
source MarketData

Where missing bars come from.

required
cache PriceCache

Defaults to PriceCache(), the shared cache file.

None
Warnings

Writes every fetched bar to the cache file.

Source code in src/cjtrade/pkgs/marketdata/compose.py
135
136
137
138
def __init__(self, source: MarketData, cache: PriceCache | None = None) -> None:
    self.source = source
    self.cache = cache if cache is not None else PriceCache()
    self.name = f"cached({source.name})"

cjtrade.pkgs.marketdata.cache

PriceCache: the local SQLite price cache, as a MarketData.

The same file and tables ArenaX has always used (paths.price_db_path()), so bars already downloaded are reused. It also records which windows have been fetched ("coverage"), which is what lets :class:Cached tell a gap from a window that simply has no trading in it.

PriceCache(path=None)

Bases: MarketData

Bars stored on this machine. Never reaches the network.

Parameters:

Name Type Description Default
path str

SQLite file. Defaults to paths.price_db_path().

None
Warnings

Creates the file and its directory on first use. One SQLite connection is opened per thread.

Source code in src/cjtrade/pkgs/marketdata/cache.py
47
48
49
def __init__(self, path: Optional[str] = None) -> None:
    self.path = str(path) if path else str(paths.price_db_path())
    self._local = threading.local()

conn property

The SQLite connection for the current thread, opened lazily.

close()

Close the current thread's connection.

Source code in src/cjtrade/pkgs/marketdata/cache.py
60
61
62
63
64
65
def close(self) -> None:
    """Close the current thread's connection."""
    conn = getattr(self._local, "conn", None)
    if conn is not None:
        conn.close()
        self._local.conn = None

get_kbars(symbol, start, end, interval='1m')

Return the cached bars in [start, end); never fetches.

Source code in src/cjtrade/pkgs/marketdata/cache.py
71
72
73
74
75
76
77
78
79
80
def get_kbars(self, symbol: str, start: TimeLike, end: TimeLike,
              interval: str = "1m") -> List[Kbar]:
    """Return the cached bars in ``[start, end)``; never fetches."""
    self.require_interval(interval)
    start_dt, end_dt = to_window(start, end)
    rows = db_api.get_price_from_arenax_local_price_db(
        conn=self.conn, symbol=symbol, timeframe=interval,
        start_ts=start_dt, end_ts=end_dt)
    # Several sources may hold the same bar; in_window keeps one.
    return in_window(rows, start_dt, end_dt)

missing(symbol, interval, start, end)

Sub-windows of [start, end) never fetched, as half-open pairs.

Source code in src/cjtrade/pkgs/marketdata/cache.py
84
85
86
87
88
89
90
91
def missing(self, symbol: str, interval: str, start: datetime,
            end: datetime) -> List[Tuple[datetime, datetime]]:
    """Sub-windows of ``[start, end)`` never fetched, as half-open pairs."""
    gaps = db_api.compute_missing_ranges(
        self.conn, symbol, interval,
        int(start.timestamp()), int(end.timestamp()) - 1)
    return [(datetime.fromtimestamp(s), datetime.fromtimestamp(e + 1))
            for s, e in gaps]

store(symbol, interval, kbars, source)

Add bars without overwriting any already stored; returns how many landed.

Source code in src/cjtrade/pkgs/marketdata/cache.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
def store(self, symbol: str, interval: str, kbars: List[Kbar],
          source: str) -> int:
    """Add bars without overwriting any already stored; returns how many landed."""
    landed = 0
    for k in kbars:
        if db_api.insert_price_to_arenax_local_price_db(
                conn=self.conn, symbol=symbol, price=k, timeframe=interval,
                source=source, overwrite=False):
            landed += 1
    return landed

mark_fetched(symbol, interval, start, end, source)

Record [start, end) as fetched, clamped to the bars that have closed.

A bar still open is not in the cache yet, so the window it sits in must stay a gap and be asked for again.

Source code in src/cjtrade/pkgs/marketdata/cache.py
104
105
106
107
108
109
110
111
112
113
114
115
116
def mark_fetched(self, symbol: str, interval: str, start: datetime,
                 end: datetime, source: str) -> None:
    """Record ``[start, end)`` as fetched, clamped to the bars that have closed.

    A bar still open is not in the cache yet, so the window it sits in
    must stay a gap and be asked for again.
    """
    end = min(end, closed_until(interval, datetime.now()))
    if end <= start:
        return
    db_api.upsert_coverage_range(
        self.conn, symbol, interval,
        int(start.timestamp()), int(end.timestamp()) - 1, source)

cjtrade.pkgs.marketdata.finmind

FinMindMarketData: TWSE/TPEx data from the FinMind open-data API.

https://finmind.github.io/ . Daily bars are free with or without a token (more requests per hour with one). Minute bars and ticks need a sponsor plan: until the account has one, those requests raise UnsupportedRequest and the source stops advertising them, so a Fallback moves on.

FinMindMarketData(token=None, timeout=30.0)

Bases: MarketData

Bars and ticks from FinMind.

Parameters:

Name Type Description Default
token str

API token. Defaults to the FINMIND_TOKEN setting; works without one at a lower request limit.

None
timeout float

Seconds per HTTP request.

30.0
Notes

Datasets used: TaiwanStockPrice (1d), TaiwanStockKBar (1m, one request per symbol per day; 5m-1h are aggregated from it) and TaiwanStockPriceTick. Daily volume is converted from shares to lots; FinMind's minute bars are stamped at their start and are shifted to their close.

Warnings

Makes network calls and counts against the account's hourly request limit (600 for a registered free account).

Source code in src/cjtrade/pkgs/marketdata/finmind.py
68
69
70
71
72
73
def __init__(self, token: Optional[str] = None, timeout: float = 30.0) -> None:
    self.token = token if token is not None else os.environ.get("FINMIND_TOKEN", "")
    self.timeout = timeout
    # None: not tried yet. False: the plan does not include it.
    self._minute_ok: Optional[bool] = None
    self._ticks_ok: Optional[bool] = None

trading_days(start, end)

Sessions in [start, end), holidays excluded.

Warnings

Makes a network call.

Source code in src/cjtrade/pkgs/marketdata/finmind.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def trading_days(self, start: TimeLike, end: TimeLike) -> List[datetime]:
    """Sessions in ``[start, end)``, holidays excluded.

    Warnings
    --------
    Makes a network call.
    """
    start_dt, end_dt = to_window(start, end)
    rows = self._request({
        "dataset": "TaiwanStockTradingDate",
        "start_date": start_dt.strftime("%Y-%m-%d"),
        "end_date": (end_dt - timedelta(microseconds=1)).strftime("%Y-%m-%d"),
    })
    return [datetime.strptime(r["date"], "%Y-%m-%d") for r in rows]

cjtrade.pkgs.marketdata.yfinance

YFinanceMarketData: free bars from Yahoo Finance.

YFinanceMarketData

Bases: MarketData

Bars from Yahoo Finance. No account or key needed.

Tries <symbol>.TW (listed) first, then <symbol>.TWO (OTC). Bars are converted to the MarketData conventions: raw prices (auto_adjust=False), intraday bars stamped at their close, daily bars at 09:00, volume in lots.

Warnings

Makes network calls to an unofficial API. Yahoo only keeps recent intraday history (about 30 days of 1m bars, 60 days of 5m-30m, two years of 1h), so older intraday windows come back empty.

cjtrade.pkgs.marketdata.sinopac

SinopacMarketData: bars and quotes through a Sinopac (shioaji) session.

SinopacMarketData(broker)

Bases: MarketData

Market data from a connected Sinopac session.

Shares the session of the broker it is given, so it adds no login of its own. Bars are fetched as 1m and aggregated here, so every interval follows the MarketData stamping rules.

Parameters:

Name Type Description Default
broker SinopacBrokerAPI or AccountClient

A Sinopac broker. It must be connected before data is requested.

required
Warnings

Makes network calls through the shioaji session. Quotes are whatever the account's market-data permissions allow.

Source code in src/cjtrade/pkgs/marketdata/sinopac.py
43
44
def __init__(self, broker) -> None:
    self.broker = getattr(broker, "broker_api", broker)

cjtrade.pkgs.marketdata.arenax

ArenaXMarketData: read prices from a running ArenaX server.

ArenaXMarketData(broker)

Bases: MarketData

The prices an ArenaX server is simulating with.

Use this, not a separate source, when trading against ArenaX: the server fills orders against its own data, so a strategy must see the same bars. Which source the server reads from is chosen when the server starts (arenaxd --data=...). "Now", for which bars have closed, is the server's simulated clock, not the wall clock.

Parameters:

Name Type Description Default
broker ArenaXBrokerAPI_v2 or AccountClient

An ArenaX broker client.

required
Warnings

Makes HTTP calls to the server. Its bid/ask book is simulated around the last close, not real.

Source code in src/cjtrade/pkgs/marketdata/arenax.py
41
42
def __init__(self, broker) -> None:
    self.broker = getattr(broker, "broker_api", broker)

cjtrade.pkgs.marketdata.offline

OfflineMarketData: a source that never has anything.

Put it behind a cache to serve only what is already on disk: Cached(OfflineMarketData(), PriceCache(path)), or arenaxd --data=offline.

OfflineMarketData

Bases: MarketData

Answers every bar request with no bars and makes no network call.

It claims every interval so that a :class:~cjtrade.pkgs.marketdata.compose.Cached in front of it serves whatever the cache holds for any interval, and a window the cache lacks simply comes back empty. Snapshots, bid/ask and ticks are unsupported.

cjtrade.pkgs.marketdata.factory

Build a MarketData from source names, as configuration and CLIs spell them.

parse_names(spec)

Split "finmind,yfinance" into names, rejecting unknown ones.

Source code in src/cjtrade/pkgs/marketdata/factory.py
16
17
18
19
20
21
22
23
24
def parse_names(spec: Union[str, Iterable[str]]) -> list:
    """Split ``"finmind,yfinance"`` into names, rejecting unknown ones."""
    names = [n.strip().lower() for n in (spec.split(",") if isinstance(spec, str) else spec)]
    names = [n for n in names if n]
    unknown = [n for n in names if n not in SOURCE_NAMES]
    if unknown or not names:
        raise ValueError(f"unknown market data source(s) {unknown or spec!r}; "
                         f"choose from {', '.join(SOURCE_NAMES)}")
    return names

from_names(spec, *, sinopac=None, finmind_token=None, cache=True, cache_path=None)

Build a MarketData from names, in order of preference.

Parameters:

Name Type Description Default
spec str or iterable of str

"sinopac", "finmind", "yfinance", "cache" (bars already on disk) and "offline" (nothing; with the cache in front, only what is on disk is served), e.g. "finmind,yfinance".

required
sinopac SinopacBrokerAPI or AccountClient

A connected Sinopac broker; required when "sinopac" is named.

None
finmind_token str

Defaults to the FINMIND_TOKEN setting.

None
cache bool or PriceCache

Put a price cache in front (default True). Pass a PriceCache to choose the file, or False for no cache.

True
cache_path str

Cache file when cache is True, and the file the "cache" source reads. Defaults to paths.price_db_path().

None

Returns:

Type Description
MarketData

Raises:

Type Description
ValueError

An unknown name, or "sinopac" without a broker.

Examples:

market = from_names("finmind,yfinance")     # cached, FinMind first
market = from_names("offline", cache_path="exp.db")   # exp.db only
Source code in src/cjtrade/pkgs/marketdata/factory.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
def from_names(spec: Union[str, Iterable[str]], *, sinopac=None,
               finmind_token: Optional[str] = None,
               cache: Optional[Union[PriceCache, bool]] = True,
               cache_path: Optional[str] = None) -> MarketData:
    """Build a MarketData from names, in order of preference.

    Parameters
    ----------
    spec : str or iterable of str
        ``"sinopac"``, ``"finmind"``, ``"yfinance"``, ``"cache"`` (bars
        already on disk) and ``"offline"`` (nothing; with the cache in front,
        only what is on disk is served), e.g. ``"finmind,yfinance"``.
    sinopac : SinopacBrokerAPI or AccountClient, optional
        A connected Sinopac broker; required when ``"sinopac"`` is named.
    finmind_token : str, optional
        Defaults to the ``FINMIND_TOKEN`` setting.
    cache : bool or PriceCache, optional
        Put a price cache in front (default True). Pass a PriceCache to
        choose the file, or False for no cache.
    cache_path : str, optional
        Cache file when `cache` is True, and the file the ``"cache"``
        source reads. Defaults to ``paths.price_db_path()``.

    Returns
    -------
    MarketData

    Raises
    ------
    ValueError
        An unknown name, or ``"sinopac"`` without a broker.

    Examples
    --------
    ```python
    market = from_names("finmind,yfinance")     # cached, FinMind first
    market = from_names("offline", cache_path="exp.db")   # exp.db only
    ```
    """
    if isinstance(cache, PriceCache) and cache_path is None:
        cache_path = cache.path
    sources: list = []
    for name in parse_names(spec):
        if name == "sinopac":
            if sinopac is None:
                raise ValueError("the 'sinopac' source needs a connected Sinopac broker")
            from cjtrade.pkgs.marketdata.sinopac import SinopacMarketData
            sources.append(SinopacMarketData(sinopac))
        elif name == "finmind":
            from cjtrade.pkgs.marketdata.finmind import FinMindMarketData
            sources.append(FinMindMarketData(token=finmind_token))
        elif name == "yfinance":
            from cjtrade.pkgs.marketdata.yfinance import YFinanceMarketData
            sources.append(YFinanceMarketData())
        elif name == "cache":
            sources.append(cache if isinstance(cache, PriceCache) else PriceCache(cache_path))
        elif name == "offline":
            from cjtrade.pkgs.marketdata.offline import OfflineMarketData
            sources.append(OfflineMarketData())
    source = sources[0] if len(sources) == 1 else Fallback(sources)
    if cache is False:
        return source
    store = cache if isinstance(cache, PriceCache) else PriceCache(cache_path)
    return Cached(source, store)

cjtrade.pkgs.marketdata.aggregate

Build bars from finer data: 1m bars from ticks, coarser bars from 1m.

Both follow the MarketData conventions, so a source that only has the finer data can still serve every interval.

aggregate(minute_bars, interval)

Aggregate 1m bars into interval bars.

Parameters:

Name Type Description Default
minute_bars list of Kbar

1-minute bars stamped at the minute they close.

required
interval str

1m, 5m, 15m, 30m, 1h or 1d.

required

Returns:

Type Description
list of Kbar

Intraday bars stamped at their bucket's close (the last bucket of a session ends at 13:30); daily bars stamped 09:00 on the session date.

Raises:

Type Description
ValueError

For any other interval.

Source code in src/cjtrade/pkgs/marketdata/aggregate.py
45
46
47
48
49
50
51
52
53
54
55
56
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
def aggregate(minute_bars: List[Kbar], interval: str) -> List[Kbar]:
    """Aggregate 1m bars into `interval` bars.

    Parameters
    ----------
    minute_bars : list of Kbar
        1-minute bars stamped at the minute they close.
    interval : str
        ``1m``, ``5m``, ``15m``, ``30m``, ``1h`` or ``1d``.

    Returns
    -------
    list of Kbar
        Intraday bars stamped at their bucket's close (the last bucket of a
        session ends at 13:30); daily bars stamped 09:00 on the session date.

    Raises
    ------
    ValueError
        For any other interval.
    """
    bars = sorted(minute_bars, key=lambda k: k.timestamp)
    if interval == "1m" or not bars:
        return bars
    if interval == "1d":
        key = lambda k: k.timestamp.date()                       # noqa: E731
        stamp = lambda d: datetime(d.year, d.month, d.day, 9, 0)  # noqa: E731
    elif interval in INTERVAL_MINUTES:
        width = INTERVAL_MINUTES[interval]
        key = lambda k: _bucket_end(k.timestamp, width)           # noqa: E731
        stamp = lambda end: end                                   # noqa: E731
    else:
        raise ValueError(f"cannot aggregate to {interval!r}")

    out: List[Kbar] = []
    group: List[Kbar] = []
    current = None
    for k in bars:
        bucket = key(k)
        if group and bucket != current:
            out.append(_merge(group, stamp(current), group[0].symbol))
            group = []
        current = bucket
        group.append(k)
    if group:
        out.append(_merge(group, stamp(current), group[0].symbol))
    return out

bars_from_ticks(ticks)

Build 1m bars from trade prints.

A print at hh:mm:ss belongs to the bar closing at hh:mm+1, so a 09:00:30 print lands in the 09:01 bar. The closing auction prints at 13:30 and is folded into the 13:30 bar rather than opening a 13:31 one. Minutes without a print get no bar.

Parameters:

Name Type Description Default
ticks list of Tick

Any order; volumes in lots.

required

Returns:

Type Description
list of Kbar

Oldest first, stamped at their close. The last bar may still be forming; pass the result through :func:~cjtrade.pkgs.marketdata.base.closed to drop it.

Source code in src/cjtrade/pkgs/marketdata/aggregate.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
def bars_from_ticks(ticks: List[Tick]) -> List[Kbar]:
    """Build 1m bars from trade prints.

    A print at ``hh:mm:ss`` belongs to the bar closing at ``hh:mm+1``, so a
    09:00:30 print lands in the 09:01 bar. The closing auction prints at
    13:30 and is folded into the 13:30 bar rather than opening a 13:31 one.
    Minutes without a print get no bar.

    Parameters
    ----------
    ticks : list of Tick
        Any order; volumes in lots.

    Returns
    -------
    list of Kbar
        Oldest first, stamped at their close. The last bar may still be
        forming; pass the result through
        :func:`~cjtrade.pkgs.marketdata.base.closed` to drop it.
    """
    out: List[Kbar] = []
    group: List[Tick] = []
    current = None
    for t in sorted(ticks, key=lambda t: t.timestamp):
        stamp = t.timestamp.replace(second=0, microsecond=0) + timedelta(minutes=1)
        close = t.timestamp.replace(hour=SESSION_CLOSE.hour, minute=SESSION_CLOSE.minute,
                                    second=0, microsecond=0)
        if stamp == close + timedelta(minutes=1):     # 13:30:xx auction print
            stamp = close
        if group and stamp != current:
            out.append(_from_ticks(group, current))
            group = []
        current = stamp
        group.append(t)
    if group:
        out.append(_from_ticks(group, current))
    return out