algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
bootstrap.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <algotradelib/core>
4
5#include <algorithm>
6#include <cmath>
7#include <cstddef>
8#include <cstdint>
9#include <stdexcept>
10#include <string>
11#include <type_traits>
12#include <utility>
13#include <vector>
14
15namespace algotradelib {
16namespace backtest {
17
23
24namespace bootstrap_detail {
25
26// A refusal naming the function.
27inline std::invalid_argument refusal(const char* who, const char* why) {
28 return std::invalid_argument(std::string(who) + ": " + why);
29}
30
31// The checks before the identity draw: two prices or more (`few`), the indices, and without `any_sign` every price
32// above zero (`sign`). Returns whether `indices` is the identity draw.
33inline bool identity_draw(
34 std::size_t count, const std::vector<std::size_t>& indices, const std::vector<Decimal64>& prices, bool any_sign,
35 const char* who, const char* few, const char* sign
36) {
37 if (count < 2 || indices.size() > count - 1) {
38 throw refusal(who, few);
39 }
40 bool identity = indices.size() == count - 1;
41 for (std::size_t k = 0; k < indices.size(); ++k) {
42 identity = identity && indices[k] == k;
43 if (indices[k] >= count - 1) {
44 throw refusal(who, "an index names no return");
45 }
46 }
47 for (const auto& price : prices) {
48 if (!any_sign && price.coefficient() <= 0) {
49 throw refusal(who, sign);
50 }
51 }
52 return identity;
53}
54
55// A price grid in whole units of `10^-scale_`, checked aligned, and the rounding of a path's level onto it.
56class Grid {
57public:
58 // A value in grid units is refused at or beyond 2^53, where a double would no longer hold every integer.
59 static constexpr std::int64_t LIMIT = std::int64_t{1} << 53;
60
61 // The bands at their own scale; `rule` must outlive the grid.
62 Grid(const PriceRule& rule, bool any_sign, const char* who) : rule_(rule), any_sign_(any_sign), who_(who) {
63 if (!rule.grid_known()) {
64 throw refusal(who_, "the price grid is unknown");
65 }
66 build();
67 }
68
69 // The bands again, at a scale covering the values'.
70 void widen(const std::vector<Decimal64>& values) {
71 for (const auto& value : values) {
72 scale_ = std::max(scale_, value.scale());
73 }
74 build();
75 }
76
77 std::int64_t units(const Decimal64& value) const {
78 std::int64_t out = value.coefficient();
79 for (auto step = value.scale();; ++step) {
80 if (out >= LIMIT || out <= -LIMIT) {
81 throw refusal(who_, "a value at or beyond 2^53 grid units");
82 }
83 if (step >= scale_) {
84 return out;
85 }
86 out *= 10;
87 }
88 }
89
90 // The nearest grid price, a tie going up; below the first band only unconstrained with `any_sign`.
91 Decimal64 round(double level, const char* zero) const {
92 constexpr auto limit = static_cast<double>(LIMIT);
93 std::size_t band = 0;
94 while (band + 1 < grid_.size() && static_cast<double>(grid_[band + 1].first) <= level) {
95 ++band;
96 }
97 const bool floored = !any_sign_ || rule_.kind_ != PriceRule::Kind::UNCONSTRAINED;
98 if (
99 !(level < limit) || !(level > -limit) || grid_.empty() ||
100 (floored && static_cast<double>(grid_[band].first) > level)
101 ) {
102 throw refusal(who_, "a level at or beyond 2^53 grid units, or below the first band");
103 }
104 const auto tick = grid_[band].second;
105 auto lower = static_cast<std::int64_t>(std::floor(level / static_cast<double>(tick)));
106 for (;;) {
107 const std::int64_t lo = lower * tick;
108 const std::int64_t hi = lo + tick;
109 if (hi >= LIMIT || lo <= -LIMIT) {
110 throw refusal(who_, "a grid neighbour at or beyond 2^53 grid units");
111 }
112 if (static_cast<double>(lo) > level) {
113 --lower;
114 } else if (static_cast<double>(hi) <= level) {
115 ++lower;
116 } else {
117 const auto nearest = level - static_cast<double>(lo) < static_cast<double>(hi) - level ? lo : hi;
118 if (nearest == 0 && !any_sign_) {
119 throw refusal(who_, zero);
120 }
121 return Decimal64(nearest, scale_);
122 }
123 }
124 }
125
126private:
127 // The bands in units, checked aligned; one unit unconstrained.
128 void build() {
129 grid_.clear();
130 if (rule_.kind_ == PriceRule::Kind::UNCONSTRAINED) {
131 grid_.emplace_back(0, 1);
132 return;
133 }
134 for (const auto& band : rule_.bands_) {
135 scale_ = std::max({scale_, band.from_.scale(), band.tick_.scale()});
136 }
137 for (const auto& band : rule_.bands_) {
138 const auto start = units(band.from_);
139 const auto tick = units(band.tick_);
140 if (tick <= 0 || start % tick != 0 || (!grid_.empty() && start % grid_.back().second != 0)) {
141 throw refusal(who_, "a band's start is not a multiple of its tick and of the previous band's");
142 }
143 grid_.emplace_back(start, tick);
144 }
145 }
146
147 const PriceRule& rule_;
148 bool any_sign_;
149 const char* who_;
150 std::uint8_t scale_{0};
151 std::vector<std::pair<std::int64_t, std::int64_t>> grid_;
152};
153
154// Whether a join declares `static constexpr bool any_sign = true`; `false` when it declares nothing.
155template <typename Join, typename = void>
156struct has_any_sign : std::false_type {};
157
158template <typename Join>
159struct has_any_sign<Join, std::void_t<decltype(Join::any_sign)>> : std::bool_constant<Join::any_sign> {};
160
161} // namespace bootstrap_detail
162
164struct Returns {
172 double join(double level, double from, double value) const {
173 return level * (value / from);
174 }
175};
176
180 static constexpr bool any_sign = true;
181
190 double join(double level, double from, double value) const {
191 constexpr auto limit = static_cast<double>(bootstrap_detail::Grid::LIMIT);
192 const double step = value - from;
193 if (!(step < limit && step > -limit)) {
194 throw std::invalid_argument("Differences: a step at or beyond 2^53 grid units");
195 }
196 return level + step;
197 }
198};
199
204struct Levels {
206 static constexpr bool any_sign = true;
207
215 double join([[maybe_unused]] double level, [[maybe_unused]] double from, double value) const {
216 return value;
217 }
218};
219
225template <typename Join, typename = void>
226struct is_price_join : std::false_type {};
227
229template <typename Join>
231 Join,
232 std::enable_if_t<
233 std::is_convertible_v<decltype(std::declval<const Join&>().join(double{}, double{}, double{})), double>
234 >
235> : std::true_type {};
236
268template <typename Join = Returns>
269std::vector<Decimal64> resample_closes(
270 const std::vector<Decimal64>& closes, const PriceRule& rule, const std::vector<std::size_t>& indices,
271 const Join& join = Join{}
272) {
273 static_assert(
274 is_price_join<Join>::value,
275 "a bootstrap join needs the member double join(double level, double from, double value) const"
276 );
277 constexpr bool any_sign = bootstrap_detail::has_any_sign<Join>::value;
278 const bool identity = bootstrap_detail::identity_draw(
279 closes.size(), indices, closes, any_sign, "resample_closes",
280 "needs two closes or more, and at most one index per return", "a close at or below zero"
281 );
282 // The bands checked aligned at their own scale, then at the closes'.
283 bootstrap_detail::Grid grid(rule, any_sign, "resample_closes");
284 if (identity) {
285 return closes;
286 }
287 grid.widen(closes);
288 std::vector<double> in;
289 for (const auto& close : closes) {
290 in.push_back(static_cast<double>(grid.units(close)));
291 }
292 std::vector<Decimal64> out;
293 double level = in.front();
294 for (std::size_t k = 0; k <= indices.size(); ++k) {
295 if (k > 0) {
296 level = join.join(level, in[indices[k - 1]], in[indices[k - 1] + 1]);
297 }
298 out.push_back(grid.round(level, "a close rounded to zero"));
299 }
300 return out;
301}
302
330template <typename Join = Returns>
331std::vector<Bar> resample_bars(
332 const std::vector<Bar>& bars, const PriceRule& rule, const std::vector<std::size_t>& indices,
333 const Join& join = Join{}
334) {
335 static_assert(
336 is_price_join<Join>::value,
337 "a bootstrap join needs the member double join(double level, double from, double value) const"
338 );
339 constexpr bool any_sign = bootstrap_detail::has_any_sign<Join>::value;
340 std::vector<Decimal64> prices;
341 for (const auto& bar : bars) {
342 if (bar.open_) {
343 prices.push_back(*bar.open_);
344 }
345 prices.insert(prices.end(), {bar.high_, bar.low_, bar.close_});
346 }
347 const bool identity = bootstrap_detail::identity_draw(
348 bars.size(), indices, prices, any_sign, "resample_bars", "needs two bars or more, and at most one index per return",
349 "a price at or below zero"
350 );
351 bootstrap_detail::Grid grid(rule, any_sign, "resample_bars");
352 if (identity) {
353 return bars;
354 }
355 grid.widen(prices);
356 // Every price in bounds, drawn or not, as `resample_closes` reads every close.
357 for (const auto& price : prices) {
358 grid.units(price);
359 }
360 const auto units = [&grid](const Decimal64& value) {
361 return static_cast<double>(grid.units(value));
362 };
363 std::vector<Bar> out;
364 double level = units(bars.front().close_);
365 for (std::size_t k = 0; k <= indices.size(); ++k) {
366 // Bar 0 is the first bar on the grid; bar `k` is day `j + 1` joined from close `j`.
367 const auto& drawn = k == 0 ? bars.front() : bars[indices[k - 1] + 1];
368 const double from = k == 0 ? 0.0 : units(bars[indices[k - 1]].close_);
369 const auto price = [&](const Decimal64& value) {
370 return grid.round(k == 0 ? units(value) : join.join(level, from, units(value)), "a price rounded to zero");
371 };
372 Bar bar = drawn;
373 bar.timestamp_ = bars[k].timestamp_;
374 if (drawn.open_) {
375 bar.open_ = price(*drawn.open_);
376 }
377 bar.high_ = price(drawn.high_);
378 bar.low_ = price(drawn.low_);
379 bar.close_ = price(drawn.close_);
380 if (k > 0) {
381 level = join.join(level, from, units(drawn.close_));
382 bar.traded_value_.reset();
383 }
384 out.push_back(bar);
385 }
386 return out;
387}
388
389} // namespace backtest
390} // namespace algotradelib
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
std::uint8_t scale() const noexcept
Returns the scale.
Definition types.hpp:549
std::int64_t coefficient() const noexcept
Returns the coefficient.
Definition types.hpp:541
Decimal64()=default
Constructs zero.
Replays a strategy over stored bars: fill and cost models, the replay ledger, and the report.
Definition bootstrap.hpp:16
std::vector< Decimal64 > resample_closes(const std::vector< Decimal64 > &closes, const PriceRule &rule, const std::vector< std::size_t > &indices, const Join &join=Join{})
Rebuilds one instrument's closes along a bootstrap path (analytics::bootstrap_indices),...
std::vector< Bar > resample_bars(const std::vector< Bar > &bars, const PriceRule &rule, const std::vector< std::size_t > &indices, const Join &join=Join{})
Rebuilds one instrument's bars along a bootstrap path (analytics::bootstrap_indices): each drawn day'...
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
Definition concept.hpp:282
void bars(S &strategy, Ctx &context, const BarSlice &slice)
Calls strategy.on_bars(context, slice) if the strategy declares on_bars; otherwise does nothing.
Definition concept.hpp:309
The library: broker-neutral types (core), and the modules below.
@ LIMIT
지정가: fills at the stated price or better.
Definition types.hpp:2001
The price grid (tick sizes) an instrument's order prices must sit on.
@ UNCONSTRAINED
The market imposes no grid (free decimals).
constexpr bool grid_known() const noexcept
Tests whether the rule says anything about the grid: a stated one, or none at all.
Chains the drawn changes (Paparoditis and Politis): the path's previous close plus value - from.
static constexpr bool any_sign
Prices at or below zero are joined, not refused.
double join(double level, double from, double value) const
Returns the path's price for a drawn price.
Joins the drawn prices as they are (Künsch; Politis and Romano): for a stationary series,...
static constexpr bool any_sign
Prices at or below zero are joined, not refused.
double join(double level, double from, double value) const
Returns the drawn price.
Chains the drawn returns: a path price is the path's previous close times value / from.
double join(double level, double from, double value) const
Returns the path's price for a drawn price.
Whether Join can join drawn blocks: true when a const Join has a member join(double,...