# 12. Statistics

## What the surface is

`tse_statistics.h` exports the engine's own statistics subsystem: the sixty-five entry points behind which stand the measures the engine itself uses to score a run — the averages, the moments, the robust estimators of location and scale, the rank correlations, the Student distribution, the trend tests and the correlograms. The surface carries no handles and no state. Every call takes the caller's array, computes one measure, and writes it into the caller's output; nothing is created, nothing has to be released, and two calls with the same input produce the same number.

Three deliberate restrictions shape the whole header.

**Everything is `double`.** The engine's internal monetary type is fixed-point and currency-parameterized; statistics are not. A measure of dispersion over prices in two currencies is not a monetary quantity, and making the surface currency-aware would have forced a currency on quantities that have none. The caller converts once, at the boundary, through `tse_finvalue_to_double` if the numbers came from engine records.

**Observations arrive either as plain doubles or as ticks plus a kind and a field.** The plain family takes `double const* values` and a count. The tick family takes the tick array as `void const*`, its count, a `TseTickKind` that names the record shape and a `TseTickField` that names the member — so one function serves all five record shapes, and a field that does not belong to the named kind is refused before anything is read.

**No argument has a default on this surface.** Where a measure admits more than one accepted definition — which quantile, which treatment of ties, which variant of $\tau$ — the choice is a parameter, and the conventional answer is reached by passing the enumeration's `undefined` guard. The two wrappers put the guard in a default argument so the choice can be omitted; C spells it out.

## Absence, refusal and error text

The header distinguishes three outcomes, and the distinction is the same everywhere.

| Outcome | How it is expressed |
| --- | --- |
| a value | `tse_ok`, `*hasValue` non-zero, `*out` written |
| no value | `tse_ok`, `*hasValue` zero, `*out` untouched |
| refusal | `tse_error`, text from `tse_statistics_last_error()` |

The middle row is the one worth dwelling on. A measure that is undefined for its input is not an error: the mean of an empty sample, the geometric mean of a sample containing a non-positive number, the skewness of two observations, the coefficient of variation of a zero-mean sample, a rank correlation or a forecast error over two ranges of unequal length — each of these is a legitimate question with no answer, and the surface says so without failing. A refusal is reserved for a malformed call: a null pointer, a field that does not belong to the named record kind, a record kind outside its enumeration, an enumeration value outside its range, a buffer shorter than the call requires.

`tse_statistics_last_error` returns thread-local text and stays valid until the next refusal on the same thread. It is the only error channel of this header: there is no per-call handle to hang it on, because there is no handle at all.

Array-returning calls follow the count-then-buffer protocol of the library: a `NULL` output with zero capacity writes the required element count into `written` and touches nothing else; a second call with a buffer fills it and writes the number of elements actually written. A short buffer is **refused** where the required length is fixed by the input — the two buffered trend functions, the three correlograms — and truncated where truncation is meaningful.

## Addressing a field of a tick

Every call that reads ticks is told two things: the kind of record it has been handed, as a `TseTickKind`, and the member it is to project, as a `TseTickField`. The two must agree. A call whose field does not belong to the named kind is refused with text, and so is a kind outside the enumeration — neither reaches a single record.

`TseTickField` repeats the kind in the high half of the byte and names the member in the low half: `0x1_` is OHLCV, `0x2_` bid/ask, `0x3_` trade, `0x4_` an executed trade, `0x5_` a book message. That repetition is what makes the agreement checkable: the surface compares the high half of the field against the kind before it reads anything, so `tse_field_ohlcv_close` under `tse_tick_kind_bidask` is refused rather than read as a candle. The kind is required; it has no value by default.

| Record | Kind | Fields |
| --- | --- | --- |
| `TseTickOHLCV` | `tse_tick_kind_ohlcv` | `tse_field_ohlcv_open`, `_high`, `_low`, `_close`, `_volume` |
| `TseTickBidAsk` | `tse_tick_kind_bidask` | `tse_field_bidask_bid`, `_bid_volume`, `_ask`, `_ask_volume`, `_last` |
| `TseTickTrade` | `tse_tick_kind_trade` | `tse_field_trade_price`, `_volume` |
| `TseRetained` | `tse_tick_kind_executed` | `tse_field_executed_price`, `_quantity`, `_fee`, `_booked_pl` |
| `TseBookMessage` | `tse_tick_kind_book` | `tse_field_book_price`, `_quantity` |

`tse_statistics_extract` projects one field of a tick array into a flat double array — the bridge between the engine's records and the plain family. `tse_statistics_extract_timestamps` is its counterpart for the three timestamps an executed trade carries, selected by `TseTimestampSelector`: `tse_timestamp_record`, `tse_timestamp_market_event` or `tse_timestamp_execution`. Timestamps come out as `int64_t` nanoseconds, never as doubles.

```c
TSE_API TseStatus tse_statistics_extract(void const* ticks, size_t count, TseTickKind kind, TseTickField field, double* out, size_t capacity, size_t* written);
TSE_API TseStatus tse_statistics_extract_timestamps(TseRetained const* trades, size_t count, TseTimestampSelector which, int64_t* out, size_t capacity, size_t* written);
```

## The generalized metric

`tse_statistics_metric` takes a `TseMetric` and serves, over one tick range, the thirteen measures that need nothing but the range: the four averages, the median, the mode, the variance, the standard deviation, the coefficient of variation, the skewness, the kurtosis and the median absolute deviation. It exists so that a strategy can select a measure at run time — from a configuration file, from a grid search, from a user's choice — without a switch of its own.

| Value | Metric | Where it is served |
| --- | --- | --- |
| 1, 3, 4, 5 | `av_arithmetic`, `av_harmonic`, `av_quadratic`, `av_geometric` | `tse_statistics_metric`, and the named centre calls |
| 6, 7 | `median`, `mode` | the same |
| 11, 12, 13 | `variance`, `sd`, `cv` | the same |
| 14, 15 | `skewness`, `kurtosis` | the same |
| 21 | `mad` | the same |
| 2, 18, 19, 20 | `av_weighted`, `covariance`, `correlation`, `ols` | two-range calls of their own |
| 8 | `frequency` | `tse_statistics_frequency_table`, two output arrays |
| 10 | `moments` | `tse_statistics_moments`, a structure |
| 16, 17 | `z_score`, `t_score` | not over a range at all |
| 22…35 | the new metrics | the six family calls |
| 36, 37 | `confidence_interval`, `autocorrelation` | their own calls, two outputs and an array |
| 9 | — | no metric: the value is skipped in the enumeration |
| 0 | `undefined` | the guard; refused by `tse_statistics_metric` |

A `TseMetric` the generalized call does not serve is refused with text naming the fact, not silently ignored.

## Centre

Eight entry points, all over a plain double array except the two-range weighted mean.

`tse_statistics_mean`, `tse_statistics_root_mean_square`, `tse_statistics_geometric_mean`, `tse_statistics_harmonic_mean`, `tse_statistics_median`, `tse_statistics_median_in_place`, `tse_statistics_mode`, `tse_statistics_weighted_mean`.

Two of them deserve a note. The geometric and harmonic means have no value when the sample contains a non-positive number — a product of signed numbers has no real root of its order, and a reciprocal of zero has no value — so they answer with `hasValue` zero rather than with a refusal. `tse_statistics_median_in_place` takes a **mutable** array and reorders it: it is the allocation-free form, and the caller's buffer comes back as a permutation of the sample, which is exactly the price of avoiding a copy. `tse_statistics_median` leaves its input untouched.

```c
TSE_API TseStatus tse_statistics_mean(double const* values, size_t count, double* out, int* hasValue);
TSE_API TseStatus tse_statistics_median_in_place(double* values, size_t count, double* out, int* hasValue);
TSE_API TseStatus tse_statistics_weighted_mean(double const* values, size_t count, double const* weights, size_t weightCount, double* out, int* hasValue);
```

## Dispersion

Five entry points: `tse_statistics_variance`, `tse_statistics_standard_deviation`, `tse_statistics_coefficient_of_variation`, `tse_statistics_median_absolute_deviation` and `tse_statistics_moments`, the last of which computes the whole family in one pass and fills a structure.

| Field | Type |
| --- | --- |
| structSize | `size_t` |
| n | `uint64_t` |
| mean | `double` |
| variance | `double` |
| sd | `double` |
| cv | `double` |
| skewness | `double` |
| kurtosis | `double` |
| min | `double` |
| max | `double` |
| range | `double` |

The variance is the sample variance, divided by $n - 1$; a single observation therefore yields zero rather than no value. The coefficient of variation has no value on a zero-mean sample, because it is a ratio to that mean. `TseMoments` is also the input of `tse_statistics_z_score`, which is why the structure is worth filling even when only one of its fields is wanted.

## Shape

Six entry points: `tse_statistics_skewness` and `tse_statistics_kurtosis` over a sample; `tse_statistics_z_score` over a filled `TseMoments` and a point; `tse_statistics_normal_z_score` and `tse_statistics_normal_critical_value` over the normal distribution; and `tse_statistics_frequency_table`, which fills two parallel output arrays — the distinct values in ascending order and their multiplicities — under the count-then-buffer protocol.

The skewness needs more than two observations and the kurtosis more than three; below that they have no value. `tse_statistics_normal_z_score` answers the two-sided quantile of the standard normal at a `TseConfidenceLevel` — $1{,}645$, $1{,}960$, $2{,}576$ for the three levels — and the guard level `tse_confidence_undefined` yields no value rather than a refusal, while a level outside the enumeration is refused.

```c
TSE_API TseStatus tse_statistics_z_score(TseMoments const* moments, double x, double* out, int* hasValue);
TSE_API TseStatus tse_statistics_frequency_table(double const* values, size_t count, double* outValues, uint64_t* outCounts, size_t capacity, size_t* written);
```

## Student

Four entry points over the Student distribution, whose table the engine carries internally for sixty-four degrees of freedom and which it continues with the normal quantile beyond that.

`tse_statistics_student_t_critical` gives the critical value for a number of degrees of freedom and a confidence level. `tse_statistics_student_is_significant` compares a $t$ statistic against that critical value for a sample size. `tse_statistics_student_test` fills `TseSignificance` with the verdict and the critical value it used. `tse_statistics_confidence_interval` builds the interval for the mean of a tick range and fills `TseConfidenceInterval`.

| Field | Type |
| --- | --- |
| structSize | `size_t` |
| at90 | `int` |
| at95 | `int` |
| at99 | `int` |

| Field | Type |
| --- | --- |
| structSize | `size_t` |
| lower | `double` |
| upper | `double` |

Zero degrees of freedom, and a sample of one observation, have no answer and are reported as such — the exception-free form of what the core reaches by throwing. The confidence interval is always built on the Student distribution, never on the normal: the engine's table already degenerates into the normal where it should, and choosing between the two was deliberately not made a parameter.

## Trend and comparison

Nine entry points. Six of them read a serie and report a property of its direction; two come in a buffered and an allocating form; one compares two windows by an arbitrary metric.

| Entry point | What it answers |
| --- | --- |
| `tse_statistics_direction_ratio` | the share of negative increments, given their count |
| `tse_statistics_stable_under_shift` | whether two slopes agree within a tolerance |
| `tse_statistics_is_step_change` / `_allocating` | whether the largest increment exceeds three times the median increment |
| `tse_statistics_theil_sen_slope` / `_allocating` | the median of pairwise slopes |
| `tse_statistics_mann_kendall_s` | the Mann–Kendall statistic $S$, as `int64_t` |
| `tse_statistics_cox_stuart` | the Cox–Stuart sign count and the number of pairs |
| `tse_statistics_compare_scores` | the same metric over two windows, as a signed comparison |

The buffered forms take scratch space from the caller and state its required length in the header: $n - 1$ elements for the step-change test, $n(n-1)/2$ for the Theil–Sen slope. A buffer shorter than that is refused rather than truncated, because a partial set of pairwise slopes is not a slope of anything. The `_allocating` forms obtain that scratch space themselves and are the convenient form; the buffered forms are the one that can be used on a hot path. `tse_statistics_stable_under_shift` is the single entry point of the header that takes a tolerance, and the one place where the two wrappers carry a numeric default — $0{,}25$, the value the core uses.

```c
TSE_API TseStatus tse_statistics_is_step_change(double const* values, size_t count, double* buffer, size_t bufferCapacity, int* out, int* hasValue);
TSE_API TseStatus tse_statistics_theil_sen_slope_allocating(double const* values, size_t count, double* out, int* hasValue);
TSE_API TseStatus tse_statistics_compare_scores(TseMetric metric, double const* previous, size_t previousCount, double const* current, size_t currentCount, double* out, int* hasValue);
```

## The new metrics

Thirty entry points cover the measures a strategy needs once the simple averages stop being enough: the quantile family, robust location and scale, concentration, rank correlation, forecast error, the two Hodges–Lehmann estimators, the confidence interval, the three correlograms and scaling.

Each of them admits more than one accepted definition, and the surface refuses to choose for the caller. Seven enumerations carry those choices, and each one's `undefined` guard means "the conventional form", resolved inside the library so that all three languages behave identically.

| Enumeration | Values | What `undefined` resolves to |
| --- | --- | --- |
| `TseQuantileDefinition` | `inverted_cdf`, `averaged_inverted_cdf`, `closest_observation`, `interpolated_inverted_cdf`, `hazen`, `weibull`, `linear`, `median_unbiased`, `normal_unbiased` (1…9, the numbering of the Hyndman–Fan classification) | `tse_quantile_linear` (7), the form numpy uses |
| `TseRankTies` | `average`, `ordinal` | `tse_rank_ties_average` |
| `TseKendallVariant` | `tau_a`, `tau_b`, `tau_c` | `tse_kendall_tau_b` |
| `TseLogarithmBase` | `binary`, `natural`, `decimal` | `tse_logarithm_binary` |
| `TseSampleCorrection` | `none`, `finite_sample` | `tse_sample_correction_finite_sample` |
| `TseEstimationMethod` | `selection`, `direct` | `tse_estimation_selection` |
| `TseRoundingRule` | `down`, `up` | `tse_rounding_down` |

Three quantities are **not** enumerations and have no conventional value, so they are always passed explicitly: the number of bins of the entropy, the trimming fraction of the trimmed and winsorized means, and the tuning constant of the biweight midvariance. The last has a named constant in the core, `aggregate::scale::biweightTuningStandard` ($9{,}0$), and the caller is free to pass it or another.

Metrics that share a set of settings share one function, so that an impossible pairing of a metric and a setting cannot be written down. Six families cover the thirteen settings-bearing metrics:

| Family | Metrics | Settings in the signature |
| --- | --- | --- |
| `tse_statistics_metric_order_statistic` | `quantile`, `interquartile_range` | `double level`, `TseQuantileDefinition` |
| `tse_statistics_metric_robust_location` | `trimmed_mean`, `winsorized_mean` | `double trimFraction`, `TseRoundingRule` |
| `tse_statistics_metric_robust_scale` | `rousseeuw_croux_qn`, `rousseeuw_croux_sn`, `biweight_midvariance` | `TseSampleCorrection`, `double tuningConstant` |
| `tse_statistics_metric_concentration` | `entropy`, `gini` | `size_t binCount`, `TseLogarithmBase`, `TseSampleCorrection` |
| `tse_statistics_metric_rank_correlation` | `spearman`, `kendall` | `TseRankTies`, `TseKendallVariant` |
| `tse_statistics_metric_forecast_error` | `rmse`, `mae` | none; it takes two ranges |

Four measures do not fit a family, because their output is not one number: `tse_statistics_hodges_lehmann_one_sample` and `tse_statistics_hodges_lehmann_two_sample` are the two argument forms of one estimator, `tse_statistics_confidence_interval` fills a structure of two bounds, and `tse_statistics_autocorrelation` fills an array of one value per lag. None of the four takes a `TseMetric`: each computes exactly one measure.

The two-sample Hodges–Lehmann form estimates the shift of the second sample relative to the first. It is the median of all pairwise differences taken as second minus first, $\operatorname{med}\{y_j - x_i\}$, so a positive answer says the second sample lies above the first. Swapping the two arguments flips the sign.

Every metric of the six families also exists as a named call over a plain double array — `tse_statistics_quantile`, `tse_statistics_trimmed_mean`, `tse_statistics_rousseeuw_croux_qn` and the rest — with the same settings and the same semantics. The family call is for a tick range and a run-time metric; the named call is for an array of numbers already in hand.

A level outside $[0;1]$, a trimming fraction outside $[0;0{,}5)$ and a bin count of zero have no answer: they report `hasValue` zero, not a refusal. An enumeration value outside its range is a refusal.

```c
TSE_API TseStatus tse_statistics_metric_order_statistic(TseMetric metric, void const* ticks, size_t count, TseTickKind kind, TseTickField field, double level, TseQuantileDefinition definition, double* out, int* hasValue);
TSE_API TseStatus tse_statistics_quantile(double const* values, size_t count, double level, TseQuantileDefinition definition, double* out, int* hasValue);
```

## Correlograms and scaling

`tse_statistics_acf`, `tse_statistics_pacf` and `tse_statistics_ccf` compute the autocorrelation function, the partial autocorrelation function and the cross-correlation function of two series. Their output lengths are fixed by the lag count and stated in the header: $k + 1$ elements for `acf` (lag zero included, where the value is always one), $k$ for `pacf`, and $2k + 1$ for `ccf` (negative lags, zero, positive lags, in that order). A lag count of zero, or one not smaller than the number of observations, is refused; a buffer shorter than the fixed length is refused as well.

`tse_statistics_scale` transforms a serie rather than reducing it: it writes exactly as many values as it reads, centring by the mean, dividing by the standard deviation, or both, according to `TseScalingMode`. Here the guard value `tse_scaling_undefined` resolves to `tse_scaling_to_center_to_scale`, the form the core itself defaults to.

```c
TSE_API TseStatus tse_statistics_acf(double const* values, size_t count, size_t lagCount, double* out, size_t capacity, size_t* written);
TSE_API TseStatus tse_statistics_ccf(double const* x, size_t countX, double const* y, size_t countY, size_t lagCount, double* out, size_t capacity, size_t* written);
TSE_API TseStatus tse_statistics_scale(double const* values, size_t count, TseScalingMode mode, double* out, size_t capacity, size_t* written);
```

## C++ and Python

### C++

The whole surface arrives as free functions in `namespace tse`, and the three outcomes of the C header become three C++ idioms: a measure that may have no value returns `std::optional<double>` (or `std::optional<StatMoments>`, `std::optional<Ols>`, `std::optional<Significance>`, `std::optional<Interval>`), an array-valued measure returns `std::vector<double>` with the two-phase protocol performed internally, and a refusal throws `tse::Error` carrying the text of `tse_statistics_last_error`. There is no `tse::statisticsLastError`: the text is in the exception, which is where C++ keeps it.

Names follow the wrapper's convention — `rootMeanSquare`, `medianAbsoluteDeviation`, `coefficientOfVariation`, `interquartileRange`, `rousseeuwCrouxQn`, `biweightMidvariance`, `metricOrderStatistic`, `hodgesLehmann` (overloaded for one and two samples), `theilSenSlope` (overloaded for the buffered and allocating forms), `timestampParts`. The settings enumerations become `enum class` types with the same names minus the prefix — `QuantileDefinition`, `RankTies`, `KendallVariant`, `LogarithmBase`, `SampleCorrection`, `EstimationMethod`, `RoundingRule` — together with `Metric`, `TickField`, `ConfidenceLevel` (`P90`, `P95`, `P99`), `ScalingMode` and `TimestampSelector`, and each settings parameter carries a default argument equal to its `undefined` guard, so the conventional form is reached by omitting the argument. `stableUnderShift` defaults its tolerance to $0{,}25$. Nothing else on this surface carries a default.

The tick path takes `std::vector<OhlcvTick>` and its siblings together with a `tse::TickField` — the wrapper's own `enum class` mirror of `TseTickField`, so the field is spelled `TickField::ohlcvClose` rather than with the C prefix; `tse::extract` returns the projected `std::vector<double>`. The kind is deduced from the tick type, so the C++ form takes no kind argument of its own. Two ranges of unequal length are not an error: a rank correlation and a forecast error over them have no value and return an empty `std::optional`, while the two-sample Hodges–Lehmann estimator serves them.

```cpp
std::vector<double> const closes {tse::extract(bars, tse::TickField::ohlcvClose)};

std::optional<double> const average {tse::mean(closes)};
std::optional<double> const spread {tse::standardDeviation(closes)};
std::optional<tse::StatMoments> const all {tse::moments(closes)};

std::optional<double> const q90 {tse::quantile(closes, 0.9)};
std::optional<double> const robust {tse::rousseeuwCrouxQn(closes)};
std::optional<double> const tau {tse::kendall(closes, volumes, tse::KendallVariant::tau_c)};

std::vector<double> const correlogram {tse::acf(closes, 5u)};
std::vector<double> const standardized {tse::scale(closes)};

std::optional<double> const q
	{tse::metricOrderStatistic(tse::Metric::quantile, bars, tse::TickField::ohlcvClose, 0.9)};
std::optional<tse::Interval> const band
	{tse::confidenceInterval(bars, tse::TickField::ohlcvClose, tse::ConfidenceLevel::P95)};
```

### Python

The module mirrors the same surface as module-level functions. A measure with no value returns `None`; an array-valued measure returns the module's array form — a numpy array when numpy is installed, a plain list otherwise, numpy being an optional dependency throughout; a refusal raises `tse.TseError` with the boundary's text. `tse.statistics_last_error()` is exported as well, for symmetry with the C surface.

Names are the C names without the `tse_statistics_` prefix: `mean`, `root_mean_square`, `median_in_place`, `weighted_mean`, `frequency_table`, `student_t_critical`, `theil_sen_slope`, `metric_order_statistic`, `hodges_lehmann_one_sample`. The enumerations are `IntEnum` classes — `Metric`, `TickField`, `ConfidenceLevel`, `ScalingMode`, `QuantileDefinition`, `RankTies`, `KendallVariant`, `LogarithmBase`, `SampleCorrection`, `EstimationMethod`, `RoundingRule`, `TimestampSelector` — whose members are spelled in upper case with underscores (`Metric.QUANTILE`, `TickField.OHLCV_CLOSE`, `ConfidenceLevel.P95`, `KendallVariant.TAU_C`), and every settings parameter defaults to that enumeration's `UNDEFINED`, exactly as in C++. `stable_under_shift` defaults `tolerance=0.25`.

On the tick path a scenario passes the list of mirrored tick structures and the kind as one of the strings `"ohlcv"`, `"bidask"`, `"trade"`, `"executed"`, `"book"`, because Python has no overload set to resolve the record shape by; the field is passed as before. `moments` returns the mirrored structure, `ols` and `student_test` likewise, and `confidence_interval` returns a `(lower, upper)` tuple or `None`.

```python
closes = tse.extract(bars, "ohlcv", tse.TickField.OHLCV_CLOSE)

average = tse.mean(closes)
spread = tse.standard_deviation(closes)
all_moments = tse.moments(closes)

q90 = tse.quantile(closes, 0.9)
robust = tse.rousseeuw_croux_qn(closes)
tau = tse.kendall(closes, volumes, variant=tse.KendallVariant.TAU_C)

correlogram = tse.acf(closes, 5)
standardized = tse.scale(closes)

q = tse.metric_order_statistic(
    tse.Metric.QUANTILE, bars, "ohlcv", tse.TickField.OHLCV_CLOSE, 0.9
)
band = tse.confidence_interval(bars, "ohlcv", tse.TickField.OHLCV_CLOSE, tse.ConfidenceLevel.P95)
```
