Repository navigation
fix(price): read bean-price's source specs, with ^ inversion and each source's ticker form - #2883
Merged
Merged
Conversation
`[price] timeout = 9223372036854775807` (the largest TOML integer), or anything near `u64::MAX` seconds, panicked inside ureq with "overflow when adding duration to instant": ureq adds the timeout to an `Instant`. #2876 introduced this, since the timeout used to be ignored. `http_get` now gives ureq no limit for a timeout over `MAX_REQUEST_TIMEOUT` (100 years), as it does for zero. The timeout error is now one message: ureq's trailing `: timeout: global` only repeated it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ch source's ticker form A `price:` spec written for bean-price failed in `rledger price`: `EUR:ratesapi/USD-EUR` asked Frankfurter for `USD-EUR` in EUR (HTTP 404), and a `^` was sent to the provider as part of the ticker. Matching bean-price 2.1.0's `price.py` and source modules: - `^TICKER` inverts on every source. The registry strips the `^`, fetches, and writes `1 / price` labeled with the declared quote currency, as bean-price does. The digits follow bean-price's `ONE / price` (28 significant digits, half-even; an exact quotient in its shortest form), within `rust_decimal`'s 28 decimal places. - A ticker that names its own quote currency is read into the fetched pair by a new `PriceSource::bean_price_pair` hook, before the dispatch: `ratesapi` and `ecb` read `BASE-SYMBOL`, `coinmarketcap` reads `SYMBOL-BASE`, and `alphavantage` reads `price:SYMBOL:BASE` and `fx:CCY:BASE`. - `quandl` reads `DB:DS[:COLUMN]` with beanprice's column choice (`Adj. Close`, else `Close`, or the named column with `_` as a space). - `coincap` looks up an upper-case symbol its table lacks in the asset list, taking the first match by market cap, as beanprice does. - `tsp` accepts beanprice's `LInco`. - `ecbrates`, beanprice's name for the ECB source, resolves to `ecb`. rledger's own ticker forms keep working. The bean-price compat harness gains a fixture covering every source's spec form and `^`, and maps bean-price's `1/TICKER` dry-run display to `^TICKER`. Closes #2866 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Contributor
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Review round 1 of #2883: - `^` inverts only in `price:` metadata, the one place bean-price's grammar applies. `PriceSourceRegistry::fetch_price` keeps every ticker verbatim again, so a `[price.mapping]` ticker, `--mapping` and `--source` send Yahoo's `^GSPC` as written, as on main; the new `fetch_price_for_spec` reads the spec grammar and is used for mappings read from `price:` metadata. - An inverse must be a price of the pair it is labeled with: the quote must be in the commodity and, for a ticker the source reads as a pair, the pair must be based in the declared currency. Otherwise it is refused, as the #2731 label check refuses the same mismatch without `^`. - The inverse is computed in exact integer arithmetic and rounded once, half to even, to 28 significant digits: it matched Python's `ONE / D(x)` on 20,000 random samples at or above 0.1. Below 0.1 the documented `rust_decimal` limit stands (k - 1 fewer digits near 10^-k). - Stricter than Python: bean-price's `ecbrates` leaks its leg precision into `ONE / price` (about six digits); rledger keeps 28. - `^^X` and a bare `^` are refused; an inverse that rounds to zero is refused like a zero price; a zero quote falls through the chain, where bean-price aborts. - `coincap`: the lookup comment no longer claims beanprice's exact scan, and a provider-returned asset ID is validated before it goes into the URL path. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review round 2 of #2883: - The base check of a `^` inversion ran only when `bean_price_pair` rewrote the pair, so oanda (`EUR_CHF`), coinbase (`BTC-USD`) and yahoo (`EURCHF=X`, `BTC-USD`), which read their own pair, were never checked: `USD:oanda/^EUR_CHF` on CHF wrote EUR per CHF labeled USD. A new `PriceSource::pair_base` hook names the base of a ticker that names its own pair; ratesapi, ecb, coinmarketcap, alphavantage, coinbase, oanda and yahoo implement it, and `fetch_inverse` checks it before any fetch. Yahoo share classes (`BRK-B`) name no pair. - A failed inversion now says the `^` was read as bean-price's inversion, and that a literal `^` ticker belongs in `[price.mapping]` or `--mapping`. The CHANGELOG and docs carry the migration line for `price: "USD:yahoo/^GSPC"`. - Docs: the inverse rule stated exactly, refusals apply without `-b` too, `^^X` is no longer listed as stricter than Python, and "at or above 2 * 10^28". Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review round 3 of #2883: - `pair_base` is now derived from the code each source builds its request with, not a separate pattern: ratesapi, ecb and coinmarketcap from `bean_price_pair`; coinbase from the new `spot_pair` its URL is built from; oanda from `format_instrument` and the new `instrument_sides` that also labels the response, so CFDs such as `NAS100_USD` are checked; alphavantage from the new `route` its fetch dispatches on. Bare tickers quoted in the requested currency report their base too, so a nonsense inversion of one is refused. - yahoo, which sends its ticker as it is, keeps its pair conventions, now case-insensitive, and reads `XXX=X` (`JPY=X`) as USD-based. - The inversion note is attached once per failed fetch, after the attempts, as ` (note: ...)`, and the `^^X` refusal carries it too. Mismatch messages print the base and quote upper-case. - Tests: oanda CFDs, Yahoo `JPY=X` both ways, lower-case tickers, alphavantage `price:IBM:USD` both ways, and the note once per fetch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # CHANGELOG.md
Review round 4 of #2883: coincap quotes every asset in USD, but had no `pair_base`, so `USD price: "EUR:coincap/^BTC"` wrote BTC per USD labeled EUR. Its `pair_base` is now the ticker, upper-case, and the inversion is refused unless declared in that asset. The `pair_base` trait doc now says what the default `None` means (the source cannot read a base), the coinmarketcap doc example uses `BTC-CHF`, and docs/commands/price.md lists coincap and says an inverted equity ticker is refused when its exchange-qualified base (`VOD.LON`) differs from the declared currency. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Two commits.
1. fix(price): treat a timeout past 100 years as no limit
This is a follow-up from round 2 of the #2876 review.
[price] timeout = 9223372036854775807(the largest TOML integer), or anything nearu64::MAXseconds, panicked inside ureq with "overflow when adding duration to instant". #2876 introduced this, because before it the timeout was ignored.http_getnow gives ureq no limit for a timeout overMAX_REQUEST_TIMEOUT(100 years), the same as for zero.test_http_get_huge_timeout_means_no_limitmakes requests against a local server with the cap itself and withi64::MAXseconds.http_getapart from a hang.: timeout: global.2. fix(price): read bean-price's source specs (#2866)
A
price:spec written for bean-price failed inrledger price.EUR:ratesapi/USD-EURgot HTTP 404 forUSD-EUR-EUR, and^was sent to the provider as part of the ticker. The behavior below follows bean-price 2.1.0's source code (price.pyand eachsources/*.py), read from the compat container.Grammar and
^. The grammar isCURRENCY:module/[^]TICKER. rledger's parser already split it this way and kept the^on the ticker.Scope.
^is read as an inversion only in a commodity'sprice:metadata, the one place bean-price's grammar applies.PriceSourceRegistry::fetch_price_for_specserves those mappings.fetch_price, used for[price.mapping],--mappingand--source, keeps every ticker verbatim, as on main, so Yahoo's^GSPCworks there. Aprice:spec such asUSD:yahoo/^GSPCnow means the inverse ofGSPC, as in bean-price; the CHANGELOG and docs carry a migration line.Inversion. For a
price:spec, rledger strips the^, fetches, and writes1 / pricelabeled with the declared quote currency, as bean-price'sfetch_pricedoes. This works on any source, including custom command sources.When an inverse is refused. The inverse of a price of B in Q is a price of Q in B, so it is written only when both hold:
PriceSource::pair_base), that base is the declared currency. Each source derives the base from the same code it builds the request with:bean_price_pairfor ratesapi, ecb and coinmarketcap,spot_pairfor coinbase,format_instrumentandinstrument_sidesfor oanda, androutefor alphavantage. Yahoo, which sends its ticker as it is, uses its own pair conventions (EURCHF=X,JPY=Xas USD-based, cryptoBTC-USD).Otherwise the inverse is refused, with or without
-b. A failed fetch that tried an inversion ends with one note naming the^as bean-price's inversion.Digits. The inverse is exact integer division, rounded once, half to even, to 28 significant digits, as bean-price's
ONE / priceis under Python's default context. An exact quotient takes its shortest form (1 / 8is0.125).rust_decimal's 28 decimal places: an inverse near 10^-k keeps k - 1 fewer significant digits. This is the documented "not fixable locally" case.No inverse. A zero quote, or one at or above 2 * 10^28 whose inverse rounds to zero, fails that attempt, and the fallback chain goes on.
Per-source tickers. A new
PriceSource::bean_price_pairhook runs at the top of the canonical dispatch. It reads a ticker that names its own quote currency into the(ticker, currency)pair that is fetched, so every source keeps fetching a plain pair.ratesapi,ecbBASE-SYMBOL^(\w+)-(\w+)$coinmarketcapSYMBOL-BASEalphavantageprice:SYMBOL:BASE,fx:CCY:BASE^(price|fx):([^:]+):(\w+)$, read into rledger'sSYMBOL/CCY/BASEquandlDB:DS[:COLUMN][A-Z0-9]+:[A-Z0-9]+(:[^:; ]+)?$. TakesAdj. Close, elseClose, or the named column with_as a space. rledger'sDB/DSkeeps its old column heuristiccoincapisupper)tspLIncoTSP_FUND_NAMESentry rledger missedcoinbase,oanda,yahoo,eastmoneyfundcoinbase,oandaandyahooreport their pair base for the inversion checkInversion base (
pair_base). Which sources report the base a^inverse must be declared in:ratesapi,ecb,coinmarketcapEURforEUR-GBPor a bareEURbean_price_paircoinbaseBTCforBTC-USDorBTCspot_pairoanda_:EUR_CHF,NAS100_USD, a bareEURformat_instrument,instrument_sidesalphavantageUSDforfx:USD:CHF/USD/CHF;IBMforprice:IBM:USD/IBM;BTCforCRYPTO:BTCroutecoincapyahooEURCHF=XisEUR,JPY=XisUSD, cryptoBTC-USDisBTCyahoonon-pair tickers (AAPL,BRK-B),quandl,tsp,eastmoneyfund, command sourcesbean-price's module name
ecbratesis now registered as an alias ofecb.All of rledger's own ticker forms keep working. The new forms are additions.
Decisions to check:
ecbratesalias. This adds a name to--list-sources. Without it, a bean-price ledger'secbrates/...spec still fails as an unknown source.GBP:ratesapi/USD-EUR. bean-price labels the EUR rate as GBP. rledger fetches EUR, and-brefuses the mismatch through the existing [Bug]: rledger price labels yahoo pence quotes GBP/GBp instead of the declared GBX #2731 label check instead of relabeling.-nkeeps showing the ticker as written (ratesapi(^EUR-GBP)), where bean-price shows1/EUR-GBP. The compat harness maps between the two.Not covered: bean-price's
iexmodule (rledger has no IEX source) and--swap-inverted.How to test
cargo test -p rustledger --all-features --lib price*_test.py(quandl_test.pytest_parse_ticker, the alphavantageprice:/fx:cases, andTSP_FUND_NAMES).cargo test -p rustledger --all-features --test bean_price_compat, gainssource_specs. It is a fixture with every source's spec form and^.bean-price -nandrledger price -nmust plan identical(symbol, currency, source, ticker)attempts.Verified locally:
cargo fmt --check,cargo clippy --all-features --all-targets -- -D warningsandRUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-depspass.cargo test -p rustledger --all-features --no-fail-fastpasses.Closes #2866
Review round 1
Commit
509ecc7740b. This round narrows where^inverts, compared with commit 2 above.^scope.^now inverts only inprice:metadata, the one place bean-price's grammar applies.PriceSourceRegistry::fetch_pricekeeps every ticker verbatim again, as on main. A[price.mapping]ticker,--mapping SPX:^GSPCand--sourcesend^GSPCas written.fetch_price_for_specreads the spec grammar.price_cmduses it for a mapping read fromprice:metadata.tests/price_caret_scope.rschecks each path end to end against a config-defined command source that answers by$RLEDGER_TICKER. The config mapping,--mappingand--sourceeach write the^GSPCprice, and metadataUSD:stub/^USDCHFwritesprice CHF 1.25 USD.docs/commands/price.mddocuments the scope.EUR-GBP, alphavantagefx:), the pair must be based in the declared currency.^. The repro (CHF price: "GBP:stub/^EUR-USD", quote in USD) is now a unit test and an end-to-end test.invert_pricecomputes10^(s+k) / min exactBigIntarithmetic and rounds once, half to even, on the exact remainder. An exact quotient is written in its shortest form.1E+28and1E+2, written out.rust_decimallimit stands. The doc now states it as k - 1 fewer digits near 10^-k.getcontext().prec = max(5, ...)leaks intoONE / price. A test pins the 28-digit inverse onecbrates(Python writes0.0890115), and the CHANGELOG notes the deviation. The "as bean-price" claim is corrected.DivisionByZero, is documented in code, docs and a test./assets/(top 100) where rledger uses?search=. A provider-returned ID must be lower-case letters, digits and-before it goes into the URL path, with a test.^^Xand a bare^are refused before any fetch.Re-verified:
cargo fmt --check,cargo clippy --all-features --all-targets -- -D warningsandRUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-depspass.cargo test -p rustledger --all-features price,--test bean_price_compatand--test price_caret_scopepass.Review round 2
Commit
74886778c41.Base check on every pair ticker. The check used to run only when
bean_price_pairrewrote the pair, so it missed oanda, coinbase and yahoo. A newPriceSource::pair_base(ticker)hook names the base of a ticker that names both sides of its pair.fetch_inversechecks it before any fetch.ratesapi,ecbEUR-GBPEURcoinmarketcapBTC-CHFBTCcoinbaseBTC-USDBTCoandaEUR_CHFEURyahooEURCHF=X, andBTC-USDwith a three-letter quoteEUR,BTCalphavantagefx:EUR:CHF,price:IBM:USD,EUR/CHFEUR,IBM,EURBRK-Bnames no pair.USD:oanda/^EUR_CHFandEUR:coinbase/^BTC-USD, refused) and the valid case for each (EUR:oanda/^EUR_CHFon CHF writes 1.25 EUR,BTC:coinbase/^BTC-USDon USD writes 0.00002 BTC), plus yahooEURCHF=X.test_pair_basecovers all seven sources.docs/commands/price.mdand section 2 above state the rule exactly.price: "USD:yahoo/^GSPC"changes meaning. It now reads as bean-price reads it, as an inversion, and I kept it that way.[price.mapping]or--mapping.price:spec,^Xis bean-price's inversion (fetchX, write its inverse); a ticker that itself starts with^, such as Yahoo's^GSPC, is kept literal in[price.mapping]or--mapping SYMBOL:^TICKER". It is asserted in the unit tests and inprice_caret_scope.Nits.
^^Xmoved out of the CHANGELOG's "Stricter than Python" list.price:-only scope and the k - 1 digits limit.-b.Re-verified:
cargo fmt --check,cargo clippy --all-features --all-targets -- -D warningsandRUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-depspass.cargo test -p rustledger --all-features pricepasses (lib 225), as do--test bean_price_compat(8/8) and--test price_caret_scope(5/5).Review round 3
Commits
f845cbbe6f3(fixes) and44f92923f93(merge of origin/main, a CHANGELOG-only conflict with #2874, both entries kept).A correction to round 2: the section 2 rewrite claimed there did not actually land. It is rewritten above in this round.
pair_basenow comes from the sameformat_instrumentthe fetch builds the instrument with. The base is read by a newinstrument_sides, which also labels the response's quote, so the two cannot disagree. CFDs are checked:NAS100_USDis based inNAS100, soUSD price: "EUR:oanda/^NAS100_USD"is refused.test_pair_basecoversSPX500_USD,NAS100_USD,DE30_EURandJP225_USD.XXX=X(JPY=X,EUR=X) is USD-based, soJPY price: "EUR:yahoo/^JPY=X"is refused andUSD:yahoo/^JPY=Xwrites the JPY price in USD. Tickers are uppercased before matching (eurchf=x,btc-usd). The test that pinnedNoneis fixed. Yahoo sends its ticker as it is, so these remain Yahoo's own conventions; there is no request parsing to share.pair_basefrom that same code:bean_price_pair;spot_pairits URL uses;routethat its fetch dispatches on.EUR:ratesapi/^GBP) is refused.Noneparse no pair from the ticker: coincap (always USD), quandl, tsp, eastmoneyfund and command sources. So are yahoo tickers outside its pair conventions (AAPL, share classBRK-B). For those, the quote check still applies.fetch_attempts, as a trailing(note: ...), distinct from the;attempt joiner. The^^Xrefusal carries it too.AlphaVantageSource's ticker reading coverprice:IBM:USDboth ways (IBM:writes 0.004 IBM,EUR:is refused). They also cover the note appearing exactly once.Re-verified after the merge:
cargo fmt --check,cargo clippy --all-features --all-targets -- -D warningsandRUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-depspass.cargo test -p rustledger --all-features pricepasses (lib 227), as do--test bean_price_compat(8/8) and--test price_caret_scope(5/5).Review round 4
Commit
77a2b53eb26, then590d0cff51f, which merges origin/main (#2884, a test baseline only, no conflict).coincapquotes every asset in USD, so itspair_baseis the ticker, upper-case.USD price: "EUR:coincap/^BTC"is now refused, with atest_pair_basecase and a registry-level refusal test.BTC:coincap/^BTCasks for BTC in BTC, which is the dispatch's identity pair.pair_basetrait doc now says whatNonemeans: the source cannot read a base, so only the quote is checked. The coinmarketcap doc example now usesBTC-CHF/BTC.docs/commands/price.mdlists coincap. It also says an inverted equity ticker is refused when its exchange-qualified base (alphavantageVOD.LON) differs from the declared currency.-D warningsand rustdoc-Dwarningspass.cargo test -p rustledger --all-features pricepasses (lib 229).bean_price_compat(8/8) andprice_caret_scope(5/5) pass.🤖 Generated with Claude Code