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

Series buffers and frames, the conversions to and from exact decimals, and performance metrics. More...

Classes

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  Alignment { UNION_UNOBSERVED , INTERSECTION , FORWARD_FILL }
 How Panel::from_bars lines up instruments whose bars fall on different instants. More...
enum class  BlockScheme { MOVING , CIRCULAR , STATIONARY }
 How a block bootstrap draws its blocks of consecutive returns. 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.
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).
constexpr std::string_view alignment_name (Alignment alignment) noexcept
 Returns a lowercase display name for an alignment, such as "intersection".
std::vector< std::size_t > bootstrap_indices (std::size_t count, BlockScheme scheme, std::size_t block, std::uint64_t seed, std::uint64_t path)
 Draws the steps of one bootstrap path: entry k names the step from close j to close j + 1, as j, the path takes at step k.
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

Series buffers and frames, the conversions to and from exact decimals, and performance metrics.

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.

◆ BlockScheme

How a block bootstrap draws its blocks of consecutive returns.

Enumerator
MOVING 

Blocks of block returns that never wrap past the last.

CIRCULAR 

Blocks of block returns that wrap from the last to the first.

STATIONARY 

Wrapping blocks whose lengths are geometric with mean block (Politis and Romano).

Definition at line 18 of file resample.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().

◆ 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 198 of file metrics.hpp.

Referenced by annualize_ratio().

◆ 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().

◆ bootstrap_indices()

std::vector< std::size_t > algotradelib::analytics::bootstrap_indices ( std::size_t count,
BlockScheme scheme,
std::size_t block,
std::uint64_t seed,
std::uint64_t path )
inline

Draws the steps of one bootstrap path: entry k names the step from close j to close j + 1, as j, the path takes at step k.

Path path of seed comes from its own std::mt19937_64, seeded by std::seed_seq with the low and high 32 bits of seed and then of path, so it is reproducible alone, on any thread and in any order. Draws use only the engine's integers (no standard distribution, whose algorithm the standard leaves open), so a path is the same on every standard library. A stationary block restarts with probability exactly 1 / block; block 1 is the plain bootstrap.

Parameters
countThe number of returns (closes minus one); the path has as many entries, each below it.
schemeHow blocks are drawn.
blockThe block length, or the mean block length for STATIONARY.
seedThe seed.
pathThe path's number.
Returns
The indices.
Exceptions
std::invalid_argumentif count or block is zero, or block exceeds count for MOVING or CIRCULAR.

Definition at line 46 of file resample.hpp.

Referenced by bootstrap_indices().

◆ 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 247 of file frame.hpp.

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

◆ 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 82 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(), and max_drawdown().

◆ 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 38 of file scalar.hpp.

Referenced by annualize_ratio(), and max_drawdown().

◆ 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().

◆ 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 126 of file metrics.hpp.

Referenced by sharpe().

◆ 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 151 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::backtest::chain_results(), 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 algotradelib::backtest::chain_results(), from_bars(), algotradelib::analytics::SeriesBuffer::push(), and to_scalar().

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