4#include "../strategy/portfolio.hpp"
7#include <algotradelib/core>
33 static constexpr std::string_view
name =
"backtest";
88 : history_(
history), own_(currency) {
89 cash_.push_back(
Money{std::move(cash), std::move(currency)});
104 : positions_(std::move(other.positions_)),
105 index_(std::move(other.index_)),
106 cash_(std::move(other.cash_)),
107 realized_(std::move(other.realized_)),
108 executions_(std::move(other.executions_)),
109 history_(other.history_),
110 held_(std::move(other.held_)),
111 lots_(std::move(other.lots_)),
112 changed_(std::move(other.changed_)),
113 changed_count_(other.changed_count_),
115 running_(other.running_) {
116 other.forget_tracking();
126 if (
this != &other) {
127 positions_ = std::move(other.positions_);
128 index_ = std::move(other.index_);
129 cash_ = std::move(other.cash_);
130 realized_ = std::move(other.realized_);
131 executions_ = std::move(other.executions_);
132 history_ = other.history_;
133 held_ = std::move(other.held_);
134 lots_ = std::move(other.lots_);
135 changed_ = std::move(other.changed_);
136 changed_count_ = other.changed_count_;
138 running_ = other.running_;
139 other.forget_tracking();
151 if (
this != &other) {
153 *
this = std::move(copy);
164 for (
const auto& amount : cash_) {
165 if (amount.currency_ == currency) {
166 return amount.amount_;
178 if (
const auto* lot = find(instrument)) {
179 return lot->quantity_;
190 if (
const auto* lot = find(instrument); lot && lot->quantity_.coefficient() != 0) {
191 return lot->average_purchase_price_;
202 for (
const auto& entry : realized_) {
203 if (entry.currency_ == currency) {
204 return entry.amount_;
218 const std::vector<HoldingPosition>&
positions() const noexcept {
238 throw std::logic_error(
239 "this ledger keeps no executions (ExecutionHistory::NONE); "
240 "a Backtester's are in ReplayResult::executions_"
257 std::optional<Decimal64>
equity()
const {
258 if (!running_.valid_ || !fits_at(running_.bound_, running_.scale_)) {
262 if (running_.counted_ == 0) {
265 return running_.total_;
287 std::optional<Execution> recorded;
289 recorded.emplace(execution_in);
291 const auto currency = currency_in;
292 const auto& execution = recorded ? *recorded : execution_in;
293 const auto& fill = execution.fill_;
297 const auto signed_quantity =
298 fill.side_ == OrderSide::BUY ? std::optional<Decimal64>(fill.quantity_) :
decimal_subtract(zero, fill.quantity_);
299 if (!signed_quantity) {
308 const auto cash_change =
309 fill.side_ == OrderSide::BUY ?
decimal_subtract(zero, *gross) : std::optional<Decimal64>(*gross);
313 const auto after_commission =
decimal_subtract(*cash_change, execution.commission_);
314 if (!after_commission) {
318 const auto after_fees =
319 execution.institution_fee_ ?
decimal_subtract(*after_commission, *execution.institution_fee_) : after_commission;
329 const auto* existing = find(fill.instrument_);
330 const auto held = existing !=
nullptr ? existing->quantity_ : zero;
331 const auto average = existing !=
nullptr ? existing->average_purchase_price_ : zero;
334 if (existing !=
nullptr && held.coefficient() != 0 && !(existing->market_value_.currency_ == currency)) {
338 const auto closing = closed_quantity(held, *signed_quantity);
344 std::optional<Decimal64> realized_total;
345 if (closing->coefficient() != 0) {
362 if (!realized_total) {
367 const auto resulting =
decimal_add(held, *signed_quantity);
379 auto new_average = average;
380 if (resulting->coefficient() == 0) {
382 }
else if (crossed_or_opened(held, *resulting)) {
383 new_average = fill.price_;
384 }
else if (adding(held, *signed_quantity)) {
385 const auto blended = weighted_average(held, average, *signed_quantity, fill.price_);
389 new_average = *blended;
401 if (resulting->coefficient() != 0 && held_.size() == held_.capacity()) {
402 held_.reserve(std::max<std::size_t>(8, 2 * held_.capacity()));
407 reserve_entry(cash_, currency);
408 if (realized_total) {
409 reserve_entry(realized_, currency);
411 if (recorded && executions_.size() == executions_.capacity()) {
412 executions_.reserve(std::max<std::size_t>(8, 2 * executions_.capacity()));
416 auto* lot = find_or_open(fill.instrument_);
417 if ((lot->quantity_.coefficient() != 0) != (resulting->coefficient() != 0)) {
418 const auto at =
static_cast<std::size_t
>(lot - positions_.data());
419 const auto where = std::lower_bound(held_.begin(), held_.end(), at);
420 if (resulting->coefficient() != 0) {
421 held_.insert(where, at);
426 lot->average_purchase_price_ = new_average;
427 lot->quantity_ = *resulting;
428 lot->last_price_ = fill.price_;
435 lot->market_value_ =
Money{*valued, currency};
436 set_amount(cash_, currency, *cash_total);
437 if (realized_total) {
438 set_amount(realized_, currency, *realized_total);
441 std::is_nothrow_move_constructible<Execution>::value,
442 "the execution is moved into room made for it, which must not throw"
445 executions_.push_back(std::move(*recorded));
447 const auto at =
static_cast<std::size_t
>(lot - positions_.data());
450 if (currency == own_) {
451 retrack_cash(*cash_total);
466 const auto slot = slot_of(instrument);
467 return slot ?
mark_lot(*slot, price) :
true;
480 return slot_of(instrument);
490 auto& position = positions_[lot];
501 position.last_price_ = price;
502 position.market_value_ =
Money{*valued, position.market_value_.currency_};
519 template <
typename BrokerTag>
526 position.sellable_quantity_ = position.quantity_;
534 portfolio.
cash_ = cash_;
538 for (
const auto& amount : cash_) {
562 template <
typename BrokerTag>
565 for (std::size_t k = 0; k < changed_count_; ++k) {
566 const auto at = changed_[k];
567 if (at >= rows.size()) {
571 const auto& lot = positions_[at];
572 auto& row = rows[at];
573 row.quantity_ = lot.quantity_;
574 row.sellable_quantity_ = lot.quantity_;
575 row.average_purchase_price_ = lot.average_purchase_price_;
576 row.last_price_ = lot.last_price_;
577 row.market_value_ = lot.market_value_;
579 if (rows.size() < positions_.size()) {
580 rows.reserve(positions_.size());
581 while (rows.size() < positions_.size()) {
582 rows.push_back(positions_[rows.size()]);
583 rows.back().sellable_quantity_ = rows.back().quantity_;
591 portfolio.
cash_ = cash_;
594 for (
const auto& amount : cash_) {
605 for (std::size_t k = 0; k < changed_count_; ++k) {
606 lots_[changed_[k]].changed_ =
false;
622 for (
const auto at : held_) {
623 const auto& lot = positions_[at];
625 if (!(lot.market_value_.currency_ == currency)) {
645 const auto slot = slot_of(instrument);
646 return slot ? &positions_[*slot] :
nullptr;
651 std::optional<std::size_t> slot_of(
const InstrumentId& instrument)
const {
652 if (!index_.empty()) {
653 return index_.find(instrument, lot_ids());
655 for (std::size_t at = 0; at < positions_.size(); ++at) {
656 if (positions_[at].instrument_ == instrument) {
665 const std::vector<HoldingPosition>* positions_;
666 const InstrumentId& operator()(std::size_t at)
const noexcept {
667 return (*positions_)[at].instrument_;
670 LotIds lot_ids() const noexcept {
671 return LotIds{&positions_};
674 HoldingPosition* find_or_open(
const InstrumentId& instrument) {
675 if (
const auto slot = slot_of(instrument)) {
676 return &positions_[*slot];
678 HoldingPosition opened;
679 opened.instrument_ = instrument;
681 opened.average_purchase_price_ =
Decimal64(0, 0);
685 grow_for(lots_, positions_.size() + 1);
686 grow_for(changed_, positions_.size() + 1);
687 positions_.push_back(std::move(opened));
688 lots_.emplace_back();
689 changed_.push_back(0);
690 if (index_.empty() && positions_.size() <= id_detail::scan_limit) {
691 return &positions_.back();
697 if (index_.empty()) {
698 id_detail::PositionTable built;
699 for (std::size_t at = 0; at < positions_.size(); ++at) {
700 built.insert(positions_[at].instrument_, at, lot_ids());
702 index_ = std::move(built);
704 index_.insert(instrument, positions_.size() - 1, lot_ids());
707 positions_.pop_back();
712 return &positions_.back();
716 static std::optional<Decimal64> closed_quantity(
const Decimal64& held,
const Decimal64& traded) {
721 if ((long_held && buying) || (short_held && !buying) || held.coefficient() == 0) {
724 const auto magnitude_held = long_held ? held :
decimal_subtract(zero, held);
725 const auto magnitude_traded = buying ? traded :
decimal_subtract(zero, traded);
726 if (!magnitude_held || !magnitude_traded) {
729 return decimal_less(*magnitude_held, *magnitude_traded) ? *magnitude_held : *magnitude_traded;
733 static bool crossed_or_opened(
const Decimal64& held,
const Decimal64& resulting) {
735 if (held.coefficient() == 0) {
742 static bool adding(
const Decimal64& held,
const Decimal64& traded) {
748 static std::optional<Decimal64> weighted_average(
749 const Decimal64& held,
const Decimal64& held_price,
const Decimal64& traded,
const Decimal64& traded_price
754 if (!held_magnitude || !traded_magnitude) {
759 if (!held_cost || !traded_cost) {
762 const auto total_cost =
decimal_add(*held_cost, *traded_cost);
763 const auto total_quantity =
decimal_add(*held_magnitude, *traded_magnitude);
764 if (!total_cost || !total_quantity || total_quantity->coefficient() == 0) {
776 static void set_amount(std::vector<Money>& amounts,
const Currency& currency,
const Decimal64& total) {
777 for (
auto& amount : amounts) {
778 if (amount.currency_ == currency) {
779 amount.amount_ = total;
783 amounts.push_back(Money{total, currency});
786 std::vector<HoldingPosition> positions_;
789 id_detail::PositionTable index_;
790 std::vector<Money> cash_;
791 std::vector<Money> realized_;
792 std::vector<Execution> executions_;
795 std::vector<std::size_t> held_;
800 bool changed_{
false};
802 std::optional<Decimal64> counted_;
804 std::vector<LotTrack> lots_;
807 std::vector<std::size_t> changed_;
808 std::size_t changed_count_{0};
819 std::uint8_t scale_{0};
823 std::size_t counted_{0};
830 static void reserve_entry(std::vector<Money>& amounts,
const Currency& currency) {
831 for (
const auto& amount : amounts) {
832 if (amount.currency_ == currency) {
836 amounts.reserve(amounts.size() + 1);
840 template <
typename T>
841 static void grow_for(std::vector<T>& list, std::size_t size) {
842 if (list.capacity() < size) {
843 list.reserve(std::max<std::size_t>(size, 2 * list.capacity()));
848 void note_changed(std::size_t at)
noexcept {
849 if (!lots_[at].changed_) {
850 lots_[at].changed_ =
true;
851 changed_[changed_count_++] = at;
855 static std::optional<Decimal64> magnitude(
const Decimal64& value) {
860 static bool fits_at(
const Decimal64& value, std::uint8_t scale)
noexcept {
861 auto coefficient = value.coefficient();
862 for (
auto step = value.scale(); step < scale; ++step) {
863 if (coefficient > std::numeric_limits<std::int64_t>::max() / 10) {
872 void replace_counted(
const std::optional<Decimal64>& before,
const std::optional<Decimal64>& after)
noexcept {
873 std::optional<Decimal64> total = running_.total_;
874 std::optional<Decimal64> bound = running_.bound_;
876 const auto size = magnitude(*before);
880 if (after && total && bound) {
881 const auto size = magnitude(*after);
883 bound = size ?
decimal_add(*bound, *size) : std::nullopt;
884 running_.scale_ = std::max(running_.scale_, after->scale());
886 if (!total || !bound) {
887 running_.valid_ =
false;
890 running_.total_ = *total;
891 running_.bound_ = *bound;
895 void retrack(std::size_t at)
noexcept {
896 const auto& lot = positions_[at];
897 std::optional<Decimal64> value;
898 if (lot.quantity_.coefficient() != 0 && lot.market_value_.currency_ == own_) {
899 value = lot.market_value_.amount_;
901 auto& counted = lots_[at].counted_;
902 if (counted == value) {
905 if (counted.has_value() != value.has_value()) {
906 running_.counted_ = value ? running_.counted_ + 1 : running_.counted_ - 1;
908 if (running_.valid_) {
909 replace_counted(counted, value);
912 if (!running_.valid_) {
918 void retrack_cash(
const Decimal64& cash)
noexcept {
919 if (running_.valid_) {
920 replace_counted(running_.cash_, cash);
922 running_.cash_ = cash;
923 if (!running_.valid_) {
930 void forget_tracking() noexcept {
938 void recount() noexcept {
941 fresh.total_ = fresh.cash_;
942 fresh.scale_ = fresh.cash_.scale();
943 const auto cash_size = magnitude(fresh.cash_);
944 fresh.valid_ = cash_size.has_value();
946 fresh.bound_ = *cash_size;
948 for (
const auto at : held_) {
949 const auto& value = lots_[at].counted_;
954 fresh.scale_ = std::max(fresh.scale_, value->scale());
958 const auto size = magnitude(*value);
959 const auto total =
decimal_add(fresh.total_, *value);
960 const auto bound = size ?
decimal_add(fresh.bound_, *size) : std::nullopt;
961 if (!total || !bound) {
962 fresh.valid_ =
false;
965 fresh.total_ = *total;
966 fresh.bound_ = *bound;
A three-letter currency code, such as KRW or USD (ISO 4217 style).
An exact signed decimal: an int64 coefficient times 10^-scale.
Decimal64()=default
Constructs zero.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
void clear_changed() noexcept
Forgets which lots changed, after a snapshot that already shows them.
ReplayLedger(const ReplayLedger &other)=default
Copies a ledger.
bool mark_lot(std::size_t lot, const Decimal64 &price)
Marks the lot at a place lot_of returned to a price, as mark does for its instrument.
std::optional< Decimal64 > equity() const
Returns total equity in the ledger's own currency (the constructor's), as equity_in would.
ReplayLedger & operator=(ReplayLedger &&other) noexcept
Replaces this ledger with a move of another; moving a ledger into itself leaves it unchanged.
ReplayLedger(ReplayLedger &&other) noexcept
Moves a ledger.
ExecutionHistory history() const noexcept
Returns whether the ledger keeps the executions it applies.
std::optional< Decimal64 > quantity_of(const InstrumentId &instrument) const
Returns the quantity held of an instrument.
std::optional< std::size_t > lot_of(const InstrumentId &instrument) const
Returns where an instrument's lot is in positions(), if a fill ever opened one.
const std::vector< Execution > & executions() const
Returns every execution applied.
ReplayLedger(Decimal64 cash, Currency currency, ExecutionHistory history=ExecutionHistory::KEEP)
Constructs a ledger holding only cash.
std::optional< Decimal64 > average_price_of(const InstrumentId &instrument) const
Returns the average price of the position in an instrument.
const std::vector< HoldingPosition > & positions() const noexcept
Returns every position, including ones that went flat.
std::optional< Decimal64 > equity_in(const Currency ¤cy) const
Returns total equity in a currency: cash plus positions at their last marks.
ReplayLedger & operator=(const ReplayLedger &other)
Replaces this ledger with a copy of another, entirely or not at all.
void update(strategy::Portfolio< BrokerTag > &portfolio, std::chrono::system_clock::time_point as_of)
Brings a portfolio built by snapshot up to date, changing only what changed since.
bool mark(const InstrumentId &instrument, const Decimal64 &price)
Marks positions in an instrument to a price, updating their market value.
Decimal64 realized_in(const Currency ¤cy) const
Returns the profit realized by closing positions, in a currency (fees excluded).
strategy::Portfolio< BrokerTag > snapshot(std::chrono::system_clock::time_point as_of) const
Returns the portfolio a strategy sees.
bool apply(const Execution &execution_in, const Currency ¤cy_in)
Applies one execution to the position, cash and realized profit.
std::optional< Decimal64 > cash_in(const Currency ¤cy) const
Returns the cash held in a currency.
Trading costs for a backtest: commission (CommissionModel, CommissionPolicy), slippage (SlippageModel...
The events a runner delivers to a strategy's handlers, and the market phase.
Replays a strategy over stored bars: fill and cost models, the replay ledger, and the report.
@ NONE
No points, for a run that does not read the curve; summarize then reports no ratio.
ExecutionHistory
Whether a ReplayLedger keeps the executions it applies.
@ KEEP
Keep every execution, readable through ReplayLedger::executions().
@ NONE
Keep none, for an owner that records them itself (a Backtester, in ReplayResult::executions_).
The library: broker-neutral types (core), and the modules below.
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
std::optional< Decimal64 > decimal_divide(const Decimal64 &lhs, const Decimal64 &rhs, std::uint8_t scale)
Divides two decimals, truncating toward zero at a given scale.
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
std::optional< Decimal64 > decimal_multiply(const Decimal64 &lhs, const Decimal64 &rhs)
Multiplies two decimals exactly; the scales add.
What the broker says may be spent, in one currency.
One position row in a holdings snapshot.
Identifies an instrument: its country, venue and symbol.
An exact amount of money in one currency.
What a sellable quantity covers, and how RiskGuard must treat resting sells against it.
@ WHOLE_HOLDING
Every share held of the instrument, whatever venue or lot.
@ DEDUCT
Subtract every resting sell from the figure.
The commission rate that charged an execution, as the backtest report lists it.
The broker tag of a replay's order references (they reach no broker).
static constexpr std::string_view name
The name an order reference prints: "backtest".
One execution a backtest produced, and what it cost.
std::optional< Decimal64 > institution_fee_
The institution fee (유관기관제비용), if the rate was split; empty is not zero.
Decimal64 commission_
The broker's commission; includes the institution fee when institution_fee_ is empty.
AppliedRate applied_
The commission rate that charged this execution.
Decimal64 slippage_
The price given up to slippage (already included in the fill price).
strategy::Fill fill_
The fill, as on_fill receives it.
Decimal64 tax_
The sale tax charged; zero unless a sell tax applies (NextBarFillModel::with_sell_tax).
Currency currency_
The currency of the cost figures.
One execution of an order the strategy placed, delivered to on_fill.
What the account holds and which orders are still working, as a strategy sees it.
SellableBasis sellable_basis_
What the sellable_quantity_ figures on positions_ cover.
std::vector< Money > cash_
Cash per currency, in a backtest only.
std::vector< BuyingPower > buying_power_
What may be spent, per currency.
std::chrono::system_clock::time_point as_of_
When the holdings were received, on this machine's clock.
std::vector< HoldingPosition > positions_
Every position row the broker reported.