algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
algotradelib::analytics Namespace Reference

Returns, rolling statistics, indicators and performance metrics over numeric series. More...

Classes

struct  BollingerBands
 The three lines of Bollinger bands, each as long as the input. More...
struct  MacdLines
 The three lines of a MACD, each as long as the input. More...
struct  MaxDrawdown
 The worst peak-to-trough decline of a level series, and where it happened. More...
class  Panel
 One bar field across many instruments: one row per instant, one column per instrument. More...
class  SeriesBuffer
 The most recent observations of a few fields, for a strategy fed one bar at a time. More...
class  SeriesFrame
 One instrument's bars as numeric columns: one row per bar, one column per BarField. More...
class  TimeIndex
 The instants a frame's rows correspond to, strictly ascending. More...

Typedefs

using Scalar
 The floating-point type analytics computes in; see math::Scalar.

Enumerations

enum class  BarField {
  OPEN , HIGH , LOW , CLOSE ,
  VOLUME , TRADED_VALUE
}
 A bar field, used as a column of a SeriesFrame. More...
enum class  TurnoverStart { FROM_CASH , SKIP }
 How turnover treats the first period. More...
enum class  Alignment { UNION_UNOBSERVED , INTERSECTION , FORWARD_FILL }
 How Panel::from_bars lines up instruments whose bars fall on different instants. More...

Functions

Scalar to_scalar (const Decimal64 &value)
 Converts an exact decimal to the nearest Scalar.
std::optional< Decimal64 > to_decimal (Scalar value, std::uint8_t scale)
 Converts a Scalar to an exact decimal with a given number of decimal places.
std::optional< Decimal64 > round_scalar_to_tick (Scalar value, const PriceRule &rule, OrderSide side, std::uint8_t scale=0)
 Converts a computed value into a price an order can carry.
constexpr std::size_t bar_field_index (BarField field) noexcept
 Returns the column position of a field in a SeriesFrame.
constexpr std::string_view bar_field_name (BarField field) noexcept
 Returns a lowercase display name for a field, such as "close".
SeriesFrame from_bars (const BarSeries &series)
 Converts a bar series into a frame of Scalar columns.
math::Vector zscore (math::SeriesView values, std::size_t window, std::size_t min_observed)
 Computes how many trailing sample standard deviations each value lies from its trailing mean.
math::Vector zscore (math::SeriesView values, std::size_t window)
 Computes the trailing z-score, requiring every row of the window.
BollingerBands bollinger (math::SeriesView values, std::size_t window, Scalar multiplier, std::size_t min_observed)
 Computes Bollinger bands: the trailing mean and bands multiplier sample standard deviations either side of it.
BollingerBands bollinger (math::SeriesView values, std::size_t window=20, Scalar multiplier=Scalar{2})
 Computes Bollinger bands, requiring every row of the window.
math::Vector rsi (math::SeriesView prices, std::size_t period=14)
 Computes Wilder's relative strength index.
math::Vector true_range (math::SeriesView highs, math::SeriesView lows, math::SeriesView closes)
 Computes each bar's true range, max(high - low, |high - prev close|, |low - prev close|).
math::Vector atr (math::SeriesView highs, math::SeriesView lows, math::SeriesView closes, std::size_t period=14)
 Computes the average true range with Wilder's smoothing.
MacdLines macd (math::SeriesView values, std::size_t fast=12, std::size_t slow=26, std::size_t signal_span=9)
 Computes the MACD (moving-average convergence/divergence) lines.
math::Vector rolling_cov (math::SeriesView left, math::SeriesView right, std::size_t window, std::size_t min_observed)
 Computes the trailing sample covariance of two series (divisor count - 1).
math::Vector rolling_cov (math::SeriesView left, math::SeriesView right, std::size_t window)
 Computes the trailing sample covariance, requiring both series on every row of the window.
math::Vector rolling_corr (math::SeriesView left, math::SeriesView right, std::size_t window, std::size_t min_observed)
 Computes the trailing Pearson correlation of two series.
math::Vector rolling_corr (math::SeriesView left, math::SeriesView right, std::size_t window)
 Computes the trailing correlation, requiring both series on every row of the window.
math::Vector beta (math::SeriesView asset, math::SeriesView market, std::size_t window, std::size_t min_observed)
 Computes the trailing beta of an asset against a market, cov(asset, market) / var(market).
math::Vector beta (math::SeriesView asset, math::SeriesView market, std::size_t window)
 Computes the trailing beta, requiring both series on every row of the window.
MaxDrawdown max_drawdown (math::SeriesView levels)
 Finds the worst peak-to-trough decline of a level series.
Scalar sharpe (math::SeriesView period_returns, Scalar risk_free=Scalar{0})
 Computes the per-period Sharpe ratio, (mean(returns) - risk_free) / stdev(returns).
Scalar sortino (math::SeriesView period_returns, Scalar target=Scalar{0})
 Computes the per-period Sortino ratio, (mean(returns) - target) / downside_deviation.
Scalar annualize_ratio (Scalar ratio, Scalar periods_per_year)
 Annualizes a per-period ratio by multiplying it by sqrt(periods_per_year).
math::Vector one_way_turnover (math::MatrixView weights, TurnoverStart start=TurnoverStart::FROM_CASH)
 Computes the one-way turnover of each period, 0.5 * sum(|w[i] - w[i - 1]|).
math::Vector two_way_turnover (math::MatrixView weights, TurnoverStart start=TurnoverStart::FROM_CASH)
 Computes the two-way turnover of each period, sum(|w[i] - w[i - 1]|).
constexpr std::string_view alignment_name (Alignment alignment) noexcept
 Returns a lowercase display name for an alignment, such as "intersection".
math::Vector returns (math::SeriesView prices)
 Computes simple period returns, p[i] / p[i - 1] - 1.
math::Vector log_returns (math::SeriesView prices)
 Computes log (continuously compounded) returns, log(p[i] / p[i - 1]).
math::Vector cumulative_returns (math::SeriesView period_returns)
 Compounds simple period returns into the cumulative return, prod(1 + r[0..i]) - 1.
math::Vector rolling_sum (math::SeriesView values, std::size_t window, std::size_t min_observed)
 Computes the trailing sum of the observed values.
math::Vector rolling_sum (math::SeriesView values, std::size_t window)
 Computes the trailing sum, requiring every row of the window.
math::Vector rolling_mean (math::SeriesView values, std::size_t window, std::size_t min_observed)
 Computes the trailing mean of the observed values.
math::Vector rolling_mean (math::SeriesView values, std::size_t window)
 Computes the trailing mean, requiring every row of the window.
math::Vector rolling_stdev (math::SeriesView values, std::size_t window, std::size_t min_observed)
 Computes the trailing sample standard deviation (divisor count - 1).
math::Vector rolling_stdev (math::SeriesView values, std::size_t window)
 Computes the trailing sample standard deviation, requiring every row of the window.
math::Vector rolling_min (math::SeriesView values, std::size_t window, std::size_t min_observed)
 Computes the trailing minimum of the observed values.
math::Vector rolling_min (math::SeriesView values, std::size_t window)
 Computes the trailing minimum, requiring every row of the window.
math::Vector rolling_max (math::SeriesView values, std::size_t window, std::size_t min_observed)
 Computes the trailing maximum of the observed values.
math::Vector rolling_max (math::SeriesView values, std::size_t window)
 Computes the trailing maximum, requiring every row of the window.
math::Vector sma (math::SeriesView values, std::size_t window, std::size_t min_observed)
 Computes the simple moving average; identical to rolling_mean.
math::Vector sma (math::SeriesView values, std::size_t window)
 Computes the simple moving average, requiring every row of the window.
math::Vector wma (math::SeriesView values, std::size_t window, std::size_t min_observed)
 Computes the linearly weighted moving average.
math::Vector wma (math::SeriesView values, std::size_t window)
 Computes the linearly weighted moving average, requiring every row of the window.
Scalar alpha_from_span (std::size_t span)
 Converts an EMA span to its smoothing factor, 2 / (span + 1).
Scalar ema_step (Scalar level, Scalar value, Scalar alpha)
 Advances an exponential moving average by one value.
Scalar ema_step (Scalar level, Scalar value, std::size_t span)=delete
 Deleted: an integer here would be a span. Pass alpha_from_span(span) instead.
math::Vector ema (math::SeriesView values, Scalar alpha, std::size_t min_observed=1)
 Computes the exponentially weighted moving average of a series.
math::Vector ema (math::SeriesView values, std::size_t span, std::size_t min_observed=1)=delete
 Deleted: an integer here would be a span. Write ema(values, alpha_from_span(span)).
Scalar missing ()
 Returns the value that stands for "no observation"; see math::missing.
bool observed (Scalar value)
 Tests whether a value is an observation; see math::observed.

Variables

constexpr std::array< BarField, 6 > all_bar_fields
 Every BarField, in declaration order.
constexpr std::size_t bar_field_count = all_bar_fields.size()
 The number of BarField values, and so of columns in a SeriesFrame.

Detailed Description

Returns, rolling statistics, indicators and performance metrics over numeric series.

Needs a build with a linear algebra backend (ATL_USE_EIGEN=ON).

Typedef Documentation

◆ Scalar

The floating-point type analytics computes in; see math::Scalar.

Definition at line 18 of file scalar.hpp.

Enumeration Type Documentation

◆ Alignment

How Panel::from_bars lines up instruments whose bars fall on different instants.

There is no default: each choice changes what a cross-sectional statistic means.

Enumerator
UNION_UNOBSERVED 

Every instant any instrument reported; an instrument with no bar there is missing().

No value is invented; reductions see fewer observations for instruments that did not trade.

INTERSECTION 

Only the instants every instrument reported.

Gives complete rows for cross-sectional work (covariance, ranking, weights), but drops much data when one instrument's history is short.

FORWARD_FILL 

Every instant any instrument reported; a gap repeats the instrument's last value.

Rows before an instrument's first bar stay missing().

Warning
A carried value is stale: a return across a filled gap is zero, then jumps when trading resumes.

Definition at line 25 of file panel.hpp.

◆ BarField

A bar field, used as a column of a SeriesFrame.

Definition at line 21 of file frame.hpp.

◆ TurnoverStart

How turnover treats the first period.

Enumerator
FROM_CASH 

Row 0 measures the first positions against an all-cash start. Use it to cost one strategy.

SKIP 

Row 0 is missing(). Use it to compare strategies whose histories start on different dates.

Definition at line 208 of file metrics.hpp.

Function Documentation

◆ alignment_name()

std::string_view algotradelib::analytics::alignment_name ( Alignment alignment)
inlineconstexprnoexcept

Returns a lowercase display name for an alignment, such as "intersection".

Parameters
alignmentThe alignment.
Returns
The name.

Definition at line 55 of file panel.hpp.

Referenced by alignment_name().

◆ alpha_from_span()

Scalar algotradelib::analytics::alpha_from_span ( std::size_t span)
inline

Converts an EMA span to its smoothing factor, 2 / (span + 1).

This is the convention charting packages and pandas.ewm(span=...) use: ema(closes, alpha_from_span(12)) is a "12-period EMA". Wilder's smoothing (alpha = 1 / n) is span 2n - 1.

Parameters
spanThe EMA period, at least 1.
Returns
The smoothing factor, in (0, 1].
Exceptions
std::invalid_argumentif span is zero.

Definition at line 415 of file rolling.hpp.

Referenced by alpha_from_span(), algotradelib::strategy::vanilla::exponential_line(), and macd().

◆ annualize_ratio()

Scalar algotradelib::analytics::annualize_ratio ( Scalar ratio,
Scalar periods_per_year )
inline

Annualizes a per-period ratio by multiplying it by sqrt(periods_per_year).

The square-root rule assumes serially uncorrelated returns.

Parameters
ratioA per-period ratio from sharpe or sortino.
periods_per_yearPeriods in a year, such as 252 for trading days or 12 for months.
Returns
The annualized ratio; ratio unchanged if it is not observed.
Exceptions
std::invalid_argumentif periods_per_year is not positive.

Definition at line 200 of file metrics.hpp.

Referenced by annualize_ratio().

◆ atr()

math::Vector algotradelib::analytics::atr ( math::SeriesView highs,
math::SeriesView lows,
math::SeriesView closes,
std::size_t period = 14 )
inline

Computes the average true range with Wilder's smoothing.

The first value is the simple mean of the first period true ranges; each later value is (previous * (period - 1) + range) / period. The result is in price units.

Parameters
highsThe bar highs.
lowsThe bar lows, as many rows as highs.
closesThe bar closes, as many rows as highs.
periodThe number of bars averaged; 14 is Wilder's.
Returns
The average true range, one per row; missing() until period true ranges are observed.
Exceptions
std::invalid_argumentif period is zero or the series differ in length.

Definition at line 362 of file indicators.hpp.

Referenced by atr().

◆ bar_field_index()

std::size_t algotradelib::analytics::bar_field_index ( BarField field)
inlineconstexprnoexcept

◆ bar_field_name()

std::string_view algotradelib::analytics::bar_field_name ( BarField field)
inlineconstexprnoexcept

Returns a lowercase display name for a field, such as "close".

Parameters
fieldThe field.
Returns
The name; empty for a value that is not a BarField.

Definition at line 57 of file frame.hpp.

Referenced by bar_field_name().

◆ beta() [1/2]

math::Vector algotradelib::analytics::beta ( math::SeriesView asset,
math::SeriesView market,
std::size_t window )
inline

Computes the trailing beta, requiring both series on every row of the window.

Parameters
assetThe asset's returns.
marketThe market's returns, as many rows as asset.
windowThe number of trailing rows.
Returns
The betas, one per row.
Exceptions
std::invalid_argumentif the series differ in length or window is zero.

Definition at line 633 of file indicators.hpp.

◆ beta() [2/2]

math::Vector algotradelib::analytics::beta ( math::SeriesView asset,
math::SeriesView market,
std::size_t window,
std::size_t min_observed )
inline

Computes the trailing beta of an asset against a market, cov(asset, market) / var(market).

Only rows on which both series are observed take part.

Parameters
assetThe asset's returns (not prices; a beta of price levels is meaningless).
marketThe market's returns, as many rows as asset.
windowThe number of trailing rows each result looks at, observed or not.
min_observedHow many of those rows must be observed for a result to be reported. Counts rows where both are observed.
Returns
The betas, one per row; missing() where fewer than max(min_observed, 2) rows are paired, and math::undefined() where the market does not move over the window.
Exceptions
std::invalid_argumentif the series differ in length, window or min_observed is zero, or min_observed > window.

Definition at line 581 of file indicators.hpp.

Referenced by beta(), and beta().

◆ bollinger() [1/2]

BollingerBands algotradelib::analytics::bollinger ( math::SeriesView values,
std::size_t window,
Scalar multiplier,
std::size_t min_observed )
inline

Computes Bollinger bands: the trailing mean and bands multiplier sample standard deviations either side of it.

Uses the sample deviation (as rolling_stdev); packages that use the population deviation draw bands narrower by a factor of sqrt((n - 1) / n) (about 2.5% at 20 rows). A window with no dispersion gives three equal lines.

Parameters
valuesThe series; NaN entries are unobserved.
windowThe number of trailing rows each result looks at, observed or not.
min_observedHow many of those rows must be observed for a result to be reported.
multiplierThe band width in standard deviations.
Returns
The three lines; each row is missing() where fewer than max(min_observed, 2) rows are observed.
Exceptions
std::invalid_argumentif window or min_observed is zero, or min_observed > window.

Definition at line 224 of file indicators.hpp.

Referenced by bollinger(), and bollinger().

◆ bollinger() [2/2]

BollingerBands algotradelib::analytics::bollinger ( math::SeriesView values,
std::size_t window = 20,
Scalar multiplier = Scalar{2} )
inline

Computes Bollinger bands, requiring every row of the window.

The defaults, 20 rows and 2 deviations, are Bollinger's own.

Parameters
valuesThe series; NaN entries are unobserved.
windowThe number of trailing rows; all must be observed.
multiplierThe band width in standard deviations.
Returns
The three lines; see the overload with min_observed.
Exceptions
std::invalid_argumentif window is zero.

Definition at line 258 of file indicators.hpp.

◆ cumulative_returns()

math::Vector algotradelib::analytics::cumulative_returns ( math::SeriesView period_returns)
inline

Compounds simple period returns into the cumulative return, prod(1 + r[0..i]) - 1.

Parameters
period_returnsSimple returns (as from returns), not log returns; the cumulative log return is their plain sum. NaN entries are skipped.
Returns
The cumulative return through each row. Rows before the first observed return are missing(); a later unobserved row repeats the running total.

Definition at line 76 of file returns.hpp.

Referenced by cumulative_returns().

◆ ema() [1/2]

math::Vector algotradelib::analytics::ema ( math::SeriesView values,
Scalar alpha,
std::size_t min_observed = 1 )
inline

Computes the exponentially weighted moving average of a series.

The level is seeded with the first observed value and then updated as alpha * value + (1 - alpha) * level (the update ema_step makes). An unobserved value is skipped: the level carries over it and that row is missing(). On observed rows the result equals pandas.Series.ewm(alpha=alpha, adjust=False, ignore_na=True, min_periods=min_observed) .mean() up to rounding.

Parameters
valuesThe series; NaN entries are unobserved.
alphaThe smoothing factor, in (0, 1]; for a period, pass alpha_from_span(span).
min_observedHow many values must have been observed before a level is reported; raise it to hide the rows where the seed still dominates.
Returns
The levels, one per row.
Exceptions
std::invalid_argumentunless 0 < alpha <= 1, or if min_observed is zero (even for an empty series).
Warning
In a live loop, keep the level yourself with ema_step. Running ema over a trailing SeriesBuffer view reseeds from the oldest row each time and gives different levels.

Definition at line 484 of file rolling.hpp.

Referenced by ema(), ema(), algotradelib::strategy::vanilla::exponential_line(), and macd().

◆ ema() [2/2]

math::Vector algotradelib::analytics::ema ( math::SeriesView values,
std::size_t span,
std::size_t min_observed = 1 )
delete

Deleted: an integer here would be a span. Write ema(values, alpha_from_span(span)).

A long double smoothing factor is ambiguous between the overloads; cast it to Scalar.

◆ ema_step() [1/2]

Scalar algotradelib::analytics::ema_step ( Scalar level,
Scalar value,
Scalar alpha )
inline

Advances an exponential moving average by one value.

Use it in a live strategy that keeps its own level from bar to bar; it computes the same levels as ema over the same bars:

Scalar level = missing();
level = ema_step(level, close, alpha);   // once per bar
Parameters
levelThe previous level, or missing() before the first observation.
valueThe new value; if unobserved, level is returned unchanged.
alphaThe smoothing factor, in (0, 1]; see alpha_from_span.
Returns
alpha * value + (1 - alpha) * level, or value itself if level is unobserved.
Exceptions
std::invalid_argumentunless 0 < alpha <= 1.
Note
If the arithmetic itself overflows to NaN (infinities of opposite sign), the next observed value reseeds the level, whereas ema keeps the NaN.

Definition at line 450 of file rolling.hpp.

Referenced by ema_step(), and ema_step().

◆ ema_step() [2/2]

Scalar algotradelib::analytics::ema_step ( Scalar level,
Scalar value,
std::size_t span )
delete

Deleted: an integer here would be a span. Pass alpha_from_span(span) instead.

A long double smoothing factor is ambiguous between the overloads; cast it to Scalar.

◆ from_bars()

SeriesFrame algotradelib::analytics::from_bars ( const BarSeries & series)
inline

Converts a bar series into a frame of Scalar columns.

A bar with no open or no traded value leaves that cell missing().

Parameters
seriesThe bars, strictly ascending in time.
Returns
A frame with one row per bar.
Exceptions
std::invalid_argumentif series is not strictly ascending in time; check BarSeries::ascending() first to avoid the exception.

Definition at line 228 of file frame.hpp.

Referenced by from_bars(), and algotradelib::analytics::Panel::from_bars().

◆ log_returns()

math::Vector algotradelib::analytics::log_returns ( math::SeriesView prices)
inline

Computes log (continuously compounded) returns, log(p[i] / p[i - 1]).

Log returns add over time; simple returns, unlike log returns, add across instruments at one instant.

Parameters
pricesThe price series; NaN entries are unobserved.
Returns
The returns, one per row. Row 0 is missing(), as is any row where either price is unobserved or not positive.

Definition at line 53 of file returns.hpp.

Referenced by log_returns().

◆ macd()

MacdLines algotradelib::analytics::macd ( math::SeriesView values,
std::size_t fast = 12,
std::size_t slow = 26,
std::size_t signal_span = 9 )
inline

Computes the MACD (moving-average convergence/divergence) lines.

macd = ema(fast) - ema(slow), signal = ema(macd), and histogram = macd - signal, each EMA with the smoothing factor alpha_from_span(span).

Parameters
valuesThe series; NaN entries are unobserved.
fastThe fast EMA span.
slowThe slow EMA span; must be greater than fast.
signal_spanThe signal EMA span.
Returns
The three lines.
Exceptions
std::invalid_argumentif fast >= slow, or a span is zero.
Warning
As with ema, recomputing a MACD over a trailing window gives different values from one kept bar by bar over the whole history.

Definition at line 399 of file indicators.hpp.

Referenced by macd().

◆ max_drawdown()

MaxDrawdown algotradelib::analytics::max_drawdown ( math::SeriesView levels)
inline

Finds the worst peak-to-trough decline of a level series.

Rows where the running peak is at or below zero are not measured, since no percentage decline exists there.

Parameters
levelsA level series (an equity curve, a growth factor, a price), not returns. NaN entries are skipped.
Returns
The decline and its rows. With no observed level, magnitude_ is missing() and both rows are -1; if levels exist but every running peak is at or below zero, magnitude_ is math::undefined(). A series that never declines gives 0.

Definition at line 83 of file metrics.hpp.

Referenced by max_drawdown().

◆ missing()

Returns the value that stands for "no observation"; see math::missing.

Returns
A quiet NaN.

Definition at line 28 of file scalar.hpp.

Referenced by algotradelib::analytics::Panel::from_bars(), log_returns(), max_drawdown(), and returns().

◆ observed()

bool algotradelib::math::observed ( Scalar value)
inline

Tests whether a value is an observation; see math::observed.

Parameters
valueThe value to test.
Returns
false for any NaN; true otherwise.

Definition at line 36 of file scalar.hpp.

Referenced by annualize_ratio(), cumulative_returns(), ema(), ema_step(), macd(), max_drawdown(), rsi(), true_range(), and zscore().

◆ one_way_turnover()

math::Vector algotradelib::analytics::one_way_turnover ( math::MatrixView weights,
TurnoverStart start = TurnoverStart::FROM_CASH )
inline

Computes the one-way turnover of each period, 0.5 * sum(|w[i] - w[i - 1]|).

One-way: moving the whole portfolio from one instrument to another is 1.

Parameters
weightsPortfolio weights, one row per period and one column per instrument. A NaN weight counts as no position.
startHow row 0 is treated.
Returns
The turnover, one value per row.
See also
two_way_turnover for the convention that counts both sides (twice this).

Definition at line 226 of file metrics.hpp.

Referenced by one_way_turnover(), and two_way_turnover().

◆ returns()

math::Vector algotradelib::analytics::returns ( math::SeriesView prices)
inline

Computes simple period returns, p[i] / p[i - 1] - 1.

Parameters
pricesThe price series; NaN entries are unobserved.
Returns
The returns, one per row. Row 0 is missing(), as is any row whose price or previous price is unobserved, or whose previous price is zero or negative (from a negative base the ratio's sign is reversed, so a further fall would read as a gain).

Definition at line 27 of file returns.hpp.

Referenced by algotradelib::strategy::vanilla::VolatilityTargetSizing::on_bar(), and returns().

◆ rolling_corr() [1/2]

math::Vector algotradelib::analytics::rolling_corr ( math::SeriesView left,
math::SeriesView right,
std::size_t window )
inline

Computes the trailing correlation, requiring both series on every row of the window.

Parameters
leftThe first series.
rightThe second series, with as many rows as left.
windowThe number of trailing rows.
Returns
The correlations, one per row.
Exceptions
std::invalid_argumentif the series differ in length or window is zero.

Definition at line 559 of file indicators.hpp.

◆ rolling_corr() [2/2]

math::Vector algotradelib::analytics::rolling_corr ( math::SeriesView left,
math::SeriesView right,
std::size_t window,
std::size_t min_observed )
inline

Computes the trailing Pearson correlation of two series.

Only rows on which both series are observed take part, so the result stays in [-1, 1] when the series have different gaps.

Parameters
leftThe first series.
rightThe second series, with as many rows as left.
windowThe number of trailing rows each result looks at, observed or not.
min_observedHow many of those rows must be observed for a result to be reported. Counts rows where both are observed.
Returns
The correlations, one per row; missing() where fewer than max(min_observed, 2) rows are paired, and math::undefined() where either series is constant over the window.
Exceptions
std::invalid_argumentif the series differ in length, window or min_observed is zero, or min_observed > window.

Definition at line 501 of file indicators.hpp.

Referenced by rolling_corr(), and rolling_corr().

◆ rolling_cov() [1/2]

math::Vector algotradelib::analytics::rolling_cov ( math::SeriesView left,
math::SeriesView right,
std::size_t window )
inline

Computes the trailing sample covariance, requiring both series on every row of the window.

Parameters
leftThe first series.
rightThe second series, with as many rows as left.
windowThe number of trailing rows.
Returns
The covariances, one per row.
Exceptions
std::invalid_argumentif the series differ in length or window is zero.

Definition at line 478 of file indicators.hpp.

◆ rolling_cov() [2/2]

math::Vector algotradelib::analytics::rolling_cov ( math::SeriesView left,
math::SeriesView right,
std::size_t window,
std::size_t min_observed )
inline

Computes the trailing sample covariance of two series (divisor count - 1).

Only rows on which both series are observed take part.

Parameters
leftThe first series.
rightThe second series, with as many rows as left.
windowThe number of trailing rows each result looks at, observed or not.
min_observedHow many of those rows must be observed for a result to be reported. Counts rows where both are observed.
Returns
The covariances, one per row; missing() where fewer than max(min_observed, 2) rows are paired.
Exceptions
std::invalid_argumentif the series differ in length, window or min_observed is zero, or min_observed > window.

Definition at line 441 of file indicators.hpp.

Referenced by rolling_cov(), and rolling_cov().

◆ rolling_max() [1/2]

math::Vector algotradelib::analytics::rolling_max ( math::SeriesView values,
std::size_t window )
inline

Computes the trailing maximum, requiring every row of the window.

Parameters
valuesThe series; NaN entries are unobserved.
windowThe number of trailing rows each result looks at; all must be observed.
Returns
The maxima, one per row; missing() where any row of the window is unobserved.
Exceptions
std::invalid_argumentif window is zero.

Definition at line 323 of file rolling.hpp.

◆ rolling_max() [2/2]

math::Vector algotradelib::analytics::rolling_max ( math::SeriesView values,
std::size_t window,
std::size_t min_observed )
inline

Computes the trailing maximum of the observed values.

Parameters
valuesThe series; NaN entries are unobserved and skipped.
windowThe number of trailing rows each result looks at, observed or not.
min_observedHow many of those rows must be observed for a result to be reported.
Returns
The maxima, one per row; missing() where fewer than min_observed rows are observed.
Exceptions
std::invalid_argumentif window or min_observed is zero, or min_observed > window.

Definition at line 295 of file rolling.hpp.

Referenced by algotradelib::strategy::vanilla::DonchianBreakout::on_bar(), rolling_max(), and rolling_max().

◆ rolling_mean() [1/2]

math::Vector algotradelib::analytics::rolling_mean ( math::SeriesView values,
std::size_t window )
inline

Computes the trailing mean, requiring every row of the window.

Parameters
valuesThe series; NaN entries are unobserved.
windowThe number of trailing rows each result looks at; all must be observed.
Returns
The means, one per row; missing() where any row of the window is unobserved.
Exceptions
std::invalid_argumentif window is zero.

Definition at line 195 of file rolling.hpp.

◆ rolling_mean() [2/2]

math::Vector algotradelib::analytics::rolling_mean ( math::SeriesView values,
std::size_t window,
std::size_t min_observed )
inline

Computes the trailing mean of the observed values.

Divides by the number of observed values in the window, not by window.

Parameters
valuesThe series; NaN entries are unobserved and skipped.
windowThe number of trailing rows each result looks at, observed or not.
min_observedHow many of those rows must be observed for a result to be reported.
Returns
The means, one per row; missing() where fewer than min_observed rows are observed.
Exceptions
std::invalid_argumentif window or min_observed is zero, or min_observed > window.

Definition at line 169 of file rolling.hpp.

Referenced by rolling_mean(), rolling_mean(), sma(), and sma().

◆ rolling_min() [1/2]

math::Vector algotradelib::analytics::rolling_min ( math::SeriesView values,
std::size_t window )
inline

Computes the trailing minimum, requiring every row of the window.

Parameters
valuesThe series; NaN entries are unobserved.
windowThe number of trailing rows each result looks at; all must be observed.
Returns
The minima, one per row; missing() where any row of the window is unobserved.
Exceptions
std::invalid_argumentif window is zero.

Definition at line 282 of file rolling.hpp.

◆ rolling_min() [2/2]

math::Vector algotradelib::analytics::rolling_min ( math::SeriesView values,
std::size_t window,
std::size_t min_observed )
inline

Computes the trailing minimum of the observed values.

Parameters
valuesThe series; NaN entries are unobserved and skipped.
windowThe number of trailing rows each result looks at, observed or not.
min_observedHow many of those rows must be observed for a result to be reported.
Returns
The minima, one per row; missing() where fewer than min_observed rows are observed.
Exceptions
std::invalid_argumentif window or min_observed is zero, or min_observed > window.

Definition at line 252 of file rolling.hpp.

Referenced by algotradelib::strategy::vanilla::DonchianBreakout::on_bar(), rolling_min(), and rolling_min().

◆ rolling_stdev() [1/2]

math::Vector algotradelib::analytics::rolling_stdev ( math::SeriesView values,
std::size_t window )
inline

Computes the trailing sample standard deviation, requiring every row of the window.

Parameters
valuesThe series; NaN entries are unobserved.
windowThe number of trailing rows each result looks at; all must be observed.
Returns
The deviations, one per row; missing() where any row of the window is unobserved, and everywhere if window is 1.
Exceptions
std::invalid_argumentif window is zero.

Definition at line 239 of file rolling.hpp.

◆ rolling_stdev() [2/2]

math::Vector algotradelib::analytics::rolling_stdev ( math::SeriesView values,
std::size_t window,
std::size_t min_observed )
inline

Computes the trailing sample standard deviation (divisor count - 1).

A window with fewer than two observed values reports missing(), whatever min_observed says.

Parameters
valuesThe series; NaN entries are unobserved and skipped.
windowThe number of trailing rows each result looks at, observed or not.
min_observedHow many of those rows must be observed for a result to be reported.
Returns
The deviations, one per row; missing() where fewer than max(min_observed, 2) rows are observed.
Exceptions
std::invalid_argumentif window or min_observed is zero, or min_observed > window.

Definition at line 211 of file rolling.hpp.

Referenced by algotradelib::strategy::vanilla::VolatilityTargetSizing::on_bar(), rolling_stdev(), and rolling_stdev().

◆ rolling_sum() [1/2]

math::Vector algotradelib::analytics::rolling_sum ( math::SeriesView values,
std::size_t window )
inline

Computes the trailing sum, requiring every row of the window.

Parameters
valuesThe series; NaN entries are unobserved.
windowThe number of trailing rows each result looks at; all must be observed.
Returns
The sums, one per row; missing() where any row of the window is unobserved.
Exceptions
std::invalid_argumentif window is zero.

Definition at line 154 of file rolling.hpp.

◆ rolling_sum() [2/2]

math::Vector algotradelib::analytics::rolling_sum ( math::SeriesView values,
std::size_t window,
std::size_t min_observed )
inline

Computes the trailing sum of the observed values.

Parameters
valuesThe series; NaN entries are unobserved and skipped.
windowThe number of trailing rows each result looks at, observed or not.
min_observedHow many of those rows must be observed for a result to be reported.
Returns
The sums, one per row; missing() where fewer than min_observed rows are observed.
Exceptions
std::invalid_argumentif window or min_observed is zero, or min_observed > window.

Definition at line 128 of file rolling.hpp.

Referenced by rolling_sum(), and rolling_sum().

◆ round_scalar_to_tick()

std::optional< Decimal64 > algotradelib::analytics::round_scalar_to_tick ( Scalar value,
const PriceRule & rule,
OrderSide side,
std::uint8_t scale = 0 )
inline

Converts a computed value into a price an order can carry.

The value is rounded to a decimal at scale in the order's favour (a buy down, a sell up), then onto the tick grid the same way, so a buy is never above the computed value (by more than floating-point noise) and a sell never below it: with the KRX grid and scale = 0, a buy at 1999.8 gives 1999 and a sell at 2000.2 gives 2005. A value within floating-point noise of a decimal counts as that decimal, so a market price converted from a Decimal64 comes back unchanged (a coefficient beyond 2^52 may not).

Parameters
valueThe computed price.
ruleThe instrument's tick rule.
sideThe side of the order the price is for.
scaleThe number of decimal places the market quotes in (0 for KRW).
Returns
The price, or std::nullopt if value is not finite (such as an indicator's warm-up missing()), does not fit a Decimal64, or rule has no grid (PriceRule::Kind::UNKNOWN).

Definition at line 99 of file conversion.hpp.

Referenced by round_scalar_to_tick().

◆ rsi()

math::Vector algotradelib::analytics::rsi ( math::SeriesView prices,
std::size_t period = 14 )
inline

Computes Wilder's relative strength index.

Average gains and losses use Wilder's smoothing (alpha = 1 / period, seeded with the simple mean of the first period changes), and the index is 100 - 100 / (1 + gain / loss). Only gains gives 100, only losses gives 0, and no movement at all gives 50.

Parameters
pricesThe price series; NaN entries are unobserved, and a change needs both prices.
periodThe number of price changes averaged; 14 is Wilder's.
Returns
The index, in [0, 100], one per row; the first period rows (and more after gaps) are missing().
Exceptions
std::invalid_argumentif period is zero.

Definition at line 279 of file indicators.hpp.

Referenced by algotradelib::strategy::vanilla::RsiThreshold::on_bar(), and rsi().

◆ sharpe()

Scalar algotradelib::analytics::sharpe ( math::SeriesView period_returns,
Scalar risk_free = Scalar{0} )
inline

Computes the per-period Sharpe ratio, (mean(returns) - risk_free) / stdev(returns).

Uses the sample standard deviation. The result is not annualized; use annualize_ratio.

Parameters
period_returnsThe period returns; NaN entries are skipped.
risk_freeThe risk-free rate per period, in the units of the returns (a daily rate for daily returns).
Returns
The ratio; missing() with fewer than two observations, and math::undefined() if the returns never vary.

Definition at line 127 of file metrics.hpp.

Referenced by sharpe().

◆ sma() [1/2]

math::Vector algotradelib::analytics::sma ( math::SeriesView values,
std::size_t window )
inline

Computes the simple moving average, requiring every row of the window.

Parameters
valuesThe series; NaN entries are unobserved.
windowThe number of trailing rows each result looks at; all must be observed.
Returns
The averages, one per row; missing() where any row of the window is unobserved.
Exceptions
std::invalid_argumentif window is zero.

Definition at line 348 of file rolling.hpp.

◆ sma() [2/2]

math::Vector algotradelib::analytics::sma ( math::SeriesView values,
std::size_t window,
std::size_t min_observed )
inline

Computes the simple moving average; identical to rolling_mean.

Parameters
valuesThe series; NaN entries are unobserved and skipped.
windowThe number of trailing rows each result looks at, observed or not.
min_observedHow many of those rows must be observed for a result to be reported.
Returns
The averages, one per row; missing() where fewer than min_observed rows are observed.
Exceptions
std::invalid_argumentif window or min_observed is zero, or min_observed > window.

Definition at line 336 of file rolling.hpp.

Referenced by sma(), and sma().

◆ sortino()

Scalar algotradelib::analytics::sortino ( math::SeriesView period_returns,
Scalar target = Scalar{0} )
inline

Computes the per-period Sortino ratio, (mean(returns) - target) / downside_deviation.

The downside deviation is sqrt(sum(min(r - target, 0)^2) / n), where n counts every observation, not only those below target (Sortino's definition). Not annualized.

Parameters
period_returnsThe period returns; NaN entries are skipped.
targetThe minimum acceptable return per period.
Returns
The ratio; missing() with fewer than two observations, and math::undefined() if no return falls below target.

Definition at line 153 of file metrics.hpp.

Referenced by sortino().

◆ to_decimal()

std::optional< Decimal64 > algotradelib::analytics::to_decimal ( Scalar value,
std::uint8_t scale )
inline

Converts a Scalar to an exact decimal with a given number of decimal places.

Rounds half away from zero. The result keeps exactly scale decimal places, trailing zeros included: to_decimal(1.5, 3) is 1.500, which is numerically equal to Decimal64::parse("1.5") but not == to it, because == also compares the scale.

Parameters
valueThe value to convert.
scaleThe number of decimal places of the result.
Returns
The decimal, or std::nullopt if value is not finite (for example missing()) or too large for Decimal64.
Note
For an order price use round_scalar_to_tick, which also puts the price on the exchange's tick grid.

Definition at line 60 of file conversion.hpp.

Referenced by algotradelib::strategy::vanilla::VolatilityTargetSizing::on_bar(), round_scalar_to_tick(), and to_decimal().

◆ to_scalar()

Scalar algotradelib::analytics::to_scalar ( const Decimal64 & value)
inline

Converts an exact decimal to the nearest Scalar.

The coefficient is divided once by 10^scale. Within 53 bits of coefficient (every price and quantity the bundled brokers quote) and 22 decimal places, both operands are exact, so in IEEE double arithmetic's default round-to-nearest mode the result is the nearest double: the same value std::strtod or Python's float gives for the decimal's text (Decimal64(7, 2) gives 0.07). Beyond either bound it is an approximation.

Parameters
valueThe decimal to convert.
Returns
The nearest Scalar to value, within the bounds above.
Warning
Do not send the result back to a broker as is; use round_scalar_to_tick.

Definition at line 37 of file conversion.hpp.

Referenced by from_bars(), algotradelib::analytics::SeriesBuffer::push(), and to_scalar().

◆ true_range()

math::Vector algotradelib::analytics::true_range ( math::SeriesView highs,
math::SeriesView lows,
math::SeriesView closes )
inline

Computes each bar's true range, max(high - low, |high - prev close|, |low - prev close|).

Where the previous close is unavailable (row 0, or an unobserved close), the range is high - low.

Parameters
highsThe bar highs.
lowsThe bar lows, as many rows as highs.
closesThe bar closes, as many rows as highs.
Returns
The true ranges, one per row; missing() where the high or low is unobserved.
Exceptions
std::invalid_argumentif the three series differ in length.

Definition at line 325 of file indicators.hpp.

Referenced by atr(), and true_range().

◆ two_way_turnover()

math::Vector algotradelib::analytics::two_way_turnover ( math::MatrixView weights,
TurnoverStart start = TurnoverStart::FROM_CASH )
inline

Computes the two-way turnover of each period, sum(|w[i] - w[i - 1]|).

Exactly twice one_way_turnover: moving the whole portfolio from one instrument to another is 2.

Parameters
weightsPortfolio weights, one row per period and one column per instrument. A NaN weight counts as no position.
startHow row 0 is treated.
Returns
The turnover, one value per row.

Definition at line 257 of file metrics.hpp.

Referenced by two_way_turnover().

◆ wma() [1/2]

math::Vector algotradelib::analytics::wma ( math::SeriesView values,
std::size_t window )
inline

Computes the linearly weighted moving average, requiring every row of the window.

Parameters
valuesThe series; NaN entries are unobserved.
windowThe number of trailing rows each result looks at; all must be observed.
Returns
The averages, one per row; missing() where any row of the window is unobserved.
Exceptions
std::invalid_argumentif window is zero.

Definition at line 400 of file rolling.hpp.

◆ wma() [2/2]

math::Vector algotradelib::analytics::wma ( math::SeriesView values,
std::size_t window,
std::size_t min_observed )
inline

Computes the linearly weighted moving average.

Weights rise 1, 2, ..., n across the window, the most recent row heaviest. The result is divided by the sum of the weights of the observed rows only.

Parameters
valuesThe series; NaN entries are unobserved and skipped.
windowThe number of trailing rows each result looks at, observed or not.
min_observedHow many of those rows must be observed for a result to be reported.
Returns
The averages, one per row; missing() where fewer than min_observed rows are observed.
Exceptions
std::invalid_argumentif window or min_observed is zero, or min_observed > window.

Definition at line 364 of file rolling.hpp.

Referenced by wma(), and wma().

◆ zscore() [1/2]

math::Vector algotradelib::analytics::zscore ( math::SeriesView values,
std::size_t window )
inline

Computes the trailing z-score, requiring every row of the window.

Parameters
valuesThe series; NaN entries are unobserved.
windowThe number of trailing rows; all must be observed.
Returns
The z-scores, one per row; see the overload with min_observed.
Exceptions
std::invalid_argumentif window is zero.

Definition at line 194 of file indicators.hpp.

◆ zscore() [2/2]

math::Vector algotradelib::analytics::zscore ( math::SeriesView values,
std::size_t window,
std::size_t min_observed )
inline

Computes how many trailing sample standard deviations each value lies from its trailing mean.

Parameters
valuesThe series; NaN entries are unobserved.
windowThe number of trailing rows each result looks at, observed or not.
min_observedHow many of those rows must be observed for a result to be reported.
Returns
The z-scores, one per row. A row is missing() if its own value is unobserved or the window has fewer than max(min_observed, 2) observations, and math::undefined() if every observation in the window is equal (no dispersion; common for a halted instrument).
Exceptions
std::invalid_argumentif window or min_observed is zero, or min_observed > window.

Definition at line 154 of file indicators.hpp.

Referenced by algotradelib::strategy::vanilla::ZScoreReversion::on_bar(), zscore(), and zscore().

Variable Documentation

◆ all_bar_fields

std::array<BarField, 6> algotradelib::analytics::all_bar_fields
inlineconstexpr
Initial value:
{
BarField::OPEN,
BarField::HIGH,
BarField::LOW,
BarField::CLOSE,
BarField::VOLUME,
BarField::TRADED_VALUE,
}

Every BarField, in declaration order.

Definition at line 31 of file frame.hpp.

◆ bar_field_count

std::size_t algotradelib::analytics::bar_field_count = all_bar_fields.size()
inlineconstexpr