algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
metrics.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "./numeric.hpp"
4
5#include <cmath>
6#include <cstddef>
7#include <stdexcept>
8
9namespace algotradelib {
10namespace analytics {
11
19
20namespace metric_detail {
21
23struct Summary {
24 std::size_t count_{0};
25 Scalar mean_{0};
26 Scalar squared_{0};
27 // Whether at least two observations are present and all equal, as far as rounding can hide it
28 // (`constant_detail::rounded_constant`); an exactly zero deviation is the caller's own test.
29 bool constant_{false};
30};
31
39inline Summary summarize(math::SeriesView values) {
40 const auto parts = math::observed_parts(values);
41 Summary result;
42 const Scalar count = parts.present_.sum();
43 result.count_ = static_cast<std::size_t>(count);
44 if (result.count_ == 0) {
45 return result;
46 }
47 result.mean_ = parts.values_.sum() / count;
48 result.squared_ = (parts.values_ - result.mean_ * parts.present_).squaredNorm();
49 if (result.count_ >= 2) {
50 const Scalar deviation = std::sqrt(result.squared_ / static_cast<Scalar>(result.count_ - 1));
51 result.constant_ = constant_detail::rounded_constant(
52 deviation, result.mean_, result.count_, parts.values_, parts.present_, 0, parts.values_.size()
53 );
54 }
55 return result;
56}
57
58} // namespace metric_detail
59
69
83 MaxDrawdown result;
84 result.magnitude_ = missing();
85 Scalar peak{0};
86 math::Index peak_row = -1;
87 std::size_t observations = 0;
88 for (math::Index row = 0; row < levels.size(); ++row) {
89 if (!observed(levels[row])) {
90 continue;
91 }
92 ++observations;
93 if (peak_row < 0 || peak < levels[row]) {
94 peak = levels[row];
95 peak_row = row;
96 }
97 if (peak <= Scalar{0}) {
98 continue;
99 }
100 const Scalar decline = (peak - levels[row]) / peak;
101 if (!observed(result.magnitude_) || result.magnitude_ < decline) {
102 result.magnitude_ = decline;
103 result.peak_row_ = peak_row;
104 result.trough_row_ = row;
105 }
106 }
107 // Levels were present but no ratio could be formed from them -- every running peak was at or
108 // below zero. That is "undefined", not "no data".
109 if (observations > 0 && !observed(result.magnitude_)) {
110 result.magnitude_ = math::undefined();
111 }
112 return result;
113}
114
126inline Scalar sharpe(math::SeriesView period_returns, Scalar risk_free = Scalar{0}) {
127 const auto summary = metric_detail::summarize(period_returns);
128 if (summary.count_ < 2) {
129 return missing();
130 }
131 const Scalar deviation = std::sqrt(summary.squared_ / static_cast<Scalar>(summary.count_ - 1));
132 if (deviation == Scalar{0} || summary.constant_) {
133 // Returns were present and never varied. `undefined()` rather than `missing()`, because a
134 // caller ranking strategies should be able to tell this from "not enough history".
135 return math::undefined();
136 }
137 return (summary.mean_ - risk_free) / deviation;
138}
139
151inline Scalar sortino(math::SeriesView period_returns, Scalar target = Scalar{0}) {
152 std::size_t count = 0;
153 std::size_t below = 0;
154 Scalar sum{0};
155 Scalar shortfall{0};
156 for (math::Index row = 0; row < period_returns.size(); ++row) {
157 const Scalar value = period_returns[row];
158 if (!observed(value)) {
159 continue;
160 }
161 ++count;
162 sum += value;
163 if (value < target) {
164 ++below;
165 const Scalar gap = target - value;
166 shortfall += gap * gap;
167 }
168 }
169 if (count < 2) {
170 return missing();
171 }
172 if (below == 0) {
173 // Nothing fell short of the target. There is no downside risk to divide by, and an infinity
174 // would survive every later comparison as the best strategy ever measured. `undefined()`
175 // says "computed, and does not exist" rather than "no data", so a caller ranking strategies
176 // can treat the two differently.
177 return math::undefined();
178 }
179 // Divided by the whole count, not by `below`. That is the definition, and the difference
180 // is a systematic flattery of strategies with rare losses.
181 const Scalar downside = std::sqrt(shortfall / static_cast<Scalar>(count));
182 if (downside == Scalar{0}) {
183 return math::undefined();
184 }
185 return (sum / static_cast<Scalar>(count) - target) / downside;
186}
187
198inline Scalar annualize_ratio(Scalar ratio, Scalar periods_per_year) {
199 if (!(periods_per_year > Scalar{0})) {
200 throw std::invalid_argument("periods per year must be positive");
201 }
202 return observed(ratio) ? ratio * std::sqrt(periods_per_year) : ratio;
203}
204
205} // namespace analytics
206} // namespace algotradelib
Series buffers and frames, the conversions to and from exact decimals, and performance metrics.
bool observed(Scalar value)
Tests whether a value is an observation; see math::observed.
Definition scalar.hpp:38
Scalar sortino(math::SeriesView period_returns, Scalar target=Scalar{0})
Computes the per-period Sortino ratio, (mean(returns) - target) / downside_deviation.
Definition metrics.hpp:151
Scalar annualize_ratio(Scalar ratio, Scalar periods_per_year)
Annualizes a per-period ratio by multiplying it by sqrt(periods_per_year).
Definition metrics.hpp:198
MaxDrawdown max_drawdown(math::SeriesView levels)
Finds the worst peak-to-trough decline of a level series.
Definition metrics.hpp:82
Scalar missing()
Returns the value that stands for "no observation"; see math::missing.
Definition scalar.hpp:28
Scalar sharpe(math::SeriesView period_returns, Scalar risk_free=Scalar{0})
Computes the per-period Sharpe ratio, (mean(returns) - risk_free) / stdev(returns).
Definition metrics.hpp:126
Observed observed_parts(SeriesView values)
Splits a series into zero-filled values and a presence mask.
Definition eigen.hpp:95
double Scalar
The floating-point type the analytics and math layers compute in (double).
Definition scalar.hpp:18
Eigen::Index Index
The signed index type of rows and columns.
Definition eigen.hpp:47
Scalar undefined()
Returns the value that stands for "the data was there, but the statistic does not exist".
Definition scalar.hpp:55
Eigen::Ref< const Vector > SeriesView
A read-only reference to one series.
Definition eigen.hpp:38
The library: broker-neutral types (core), and the modules below.
Re-exports math::Scalar, math::missing and math::observed into analytics.
The worst peak-to-trough decline of a level series, and where it happened.
Definition metrics.hpp:61
math::Index peak_row_
The row of the peak the decline fell from, or -1 if there is none.
Definition metrics.hpp:65
math::Index trough_row_
The row of the low the decline reached, or -1 if there is none.
Definition metrics.hpp:67
Scalar magnitude_
The decline as a non-negative fraction of the peak (0.2 is 20% below it).
Definition metrics.hpp:63