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.startandendmay be adate, adatetimeor an ISO string; a date means 00:00 of that day, soend="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 | |
supports(interval)
¶
Return whether get_kbars accepts interval.
Source code in src/cjtrade/pkgs/marketdata/base.py
156 157 158 | |
require_interval(interval)
¶
Raise UnsupportedRequest unless interval is supported.
Source code in src/cjtrade/pkgs/marketdata/base.py
160 161 162 163 164 165 | |
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. |
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 |
'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 | |
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 | |
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 | |
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 | |
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 |
snapshots |
bool
|
Whether |
bid_ask |
bool
|
Whether |
ticks |
bool
|
Whether |
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 |
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 | |
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 |
None
|
Warnings
Writes every fetched bar to the cache file.
Source code in src/cjtrade/pkgs/marketdata/compose.py
135 136 137 138 | |
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 |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
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 | |
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 | |
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 | |
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 | |
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 | |
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
|
|
required |
sinopac
|
SinopacBrokerAPI or AccountClient
|
A connected Sinopac broker; required when |
None
|
finmind_token
|
str
|
Defaults to the |
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 |
None
|
Returns:
| Type | Description |
|---|---|
MarketData
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
An unknown name, or |
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 | |
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
|
|
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 | |
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: |
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 | |