Statistics

class Stats[source]

Example

import numpy as np
from hftbacktest.stats import LinearAssetRecord

asset0_record = np.load('backtest_result.npz')['0']
stats = (
    LinearAssetRecord(asset0_record)
        .resample('10s')
        .monthly()
        .stats(book_size=100000)
)
stats.summary()
stats.plot()
Parameters:
summary(pretty=False)[source]

Displays the statistics summary.

Parameters:

pretty (bool) – Returns the statistics in a pretty-printed format.

plot(price_as_ret=False, backend='matplotlib')[source]

Plots the equity curves and positions over time along with the price chart.

Parameters:
  • price_as_ret (bool) – Plots the price chart in cumulative returns if set to True; otherwise, it plots the price chart in raw price terms.

  • backend (Literal['matplotlib', 'holoviews']) – Specifies which plotting library is used to plot the charts. The default is ‘matplotlib’.

class LinearAssetRecord(data)[source]
Parameters:

data (ndarray[Any, dtype[_ScalarType_co]] | DataFrame)

contract_size(contract_size)

Sets the contract size. The default value is 1.0.

Parameters:

contract_size (float) – The asset’s contract size.

Return type:

Self

daily()

Generates daily statistics.

Return type:

Self

monthly()

Generates monthly statistics.

Return type:

Self

resample(frequency)

Sets the resampling frequency for downsampling the record. This could affect the calculation of the metrics related to the sampling interval. Additionally, it reduces the time required for computing the metrics and plotting the charts. The default value is 10s.

Parameters:

frequency (str) – Interval of the window. This internally uses Polars, please see polars.DataFrame.group_by_dynamic for more details.

Return type:

Self

stats(metrics=None, **kwargs)

Examples

stats = record.stats([SR('SR365', trading_days_per_year=365), AnnualRet(trading_days_per_year=365)]
Parameters:
Returns:

The statistics for the specified metrics of the record.

Return type:

Stats

time_unit(time_unit)

Sets the time unit for converting timestamps in the records to datetime. The default value is ns.

Parameters:

time_unit (str) – The unit of time of the timesteps since epoch time. This internally uses Polars, please see polars.from_epoch for more details.

Return type:

Self

class InverseAssetRecord(data)[source]
Parameters:

data (ndarray[Any, dtype[_ScalarType_co]] | DataFrame)

contract_size(contract_size)

Sets the contract size. The default value is 1.0.

Parameters:

contract_size (float) – The asset’s contract size.

Return type:

Self

daily()

Generates daily statistics.

Return type:

Self

monthly()

Generates monthly statistics.

Return type:

Self

resample(frequency)

Sets the resampling frequency for downsampling the record. This could affect the calculation of the metrics related to the sampling interval. Additionally, it reduces the time required for computing the metrics and plotting the charts. The default value is 10s.

Parameters:

frequency (str) –

Interval of the window. This internally uses Polars, please see polars.DataFrame.group_by_dynamic for more details.

Return type:

Self

stats(metrics=None, **kwargs)

Examples

stats = record.stats([SR('SR365', trading_days_per_year=365), AnnualRet(trading_days_per_year=365)]
Parameters:
Returns:

The statistics for the specified metrics of the record.

Return type:

Stats

time_unit(time_unit)

Sets the time unit for converting timestamps in the records to datetime. The default value is ns.

Parameters:

time_unit (str) –

The unit of time of the timesteps since epoch time. This internally uses Polars, please see polars.from_epoch for more details.

Return type:

Self

Metrics

class Metric[source]

A base class for computing a strategy’s performance metrics. Implementing a custom metric class derived from this base class enables the computation of the custom metric in the Stats and displays the summary.

class Ret(name=None, book_size=None)[source]

Return

Parameters:
  • name (str) – Name of this metric. The default value is Return.

  • book_size (float | None) – If the book size, or capital allocation, is set, the metric is divided by the book size to express it as a percentage ratio of the book size; otherwise, the metric is in raw units.

class AnnualRet(name=None, book_size=None, trading_days_per_year=252)[source]

Annualised return

Parameters:
  • name (str) – Name of this metric. The default value is AnnualReturn.

  • book_size (float | None) – If the book size, or capital allocation, is set, the metric is divided by the book size to express it as a percentage ratio of the book size; otherwise, the metric is in raw units.

  • trading_days_per_year (float) – The number of trading days per year to annualise. Commonly, 252 is used in trad-fi, so the default value is 252 to match that scale. However, you can use 365 instead of 252 for crypto markets, which run 24/7.

class SR(name=None, trading_days_per_year=252)[source]

Sharpe Ratio without considering a benchmark.

Parameters:
  • name (str) – Name of this metric. The default value is SR.

  • trading_days_per_year (float) – Trading days per year to annualise. Commonly, 252 is used in trad-fi, so the default value is 252 to match that scale. However, you can use 365 instead of 252 for crypto markets, which run 24/7. Additionally, be aware that to compute the daily Sharpe Ratio, it also multiplies by sqrt(the sample number per day), so the computed Sharpe Ratio is affected by the sampling interval.

class Sortino(name=None, trading_days_per_year=252)[source]

Sortino Ratio without considering a benchmark.

Parameters:
  • name – Name of this metric. The default value is Sortino.

  • trading_days_per_year (float) – Trading days per year to annualise. Commonly, 252 is used in trad-fi, so the default value is 252 to match that scale. However, you can use 365 instead of 252 for crypto markets, which run 24/7. Additionally, be aware that to compute the daily Sharpe Ratio, it also multiplies by sqrt(the sample number per day), so the computed Sharpe Ratio is affected by the sampling interval.

class MaxDrawdown(name=None, book_size=None)[source]

Maximum Drawdown

Parameters:
  • name (str) – Name of this metric. The default value is MaxDrawdown.

  • book_size (float | None) – If the book size, or capital allocation, is set, the metric is divided by the book size to express it as a percentage ratio of the book size; otherwise, the metric is in raw units.

class ReturnOverMDD(name=None)[source]

Return over Maximum Drawdown

Parameters:

name (str) – Name of this metric. The default value is ReturnOverMDD.

class ReturnOverTrade(name=None)[source]

Return over Trade value, which represents the profit made per unit of trading value, for instance, $profit / $trading_value.

Parameters:

name (str) – Name of this metric. The default value is ReturnOverTrade.

class NumberOfTrades(name=None)[source]
Parameters:

name (str)

class DailyNumberOfTrades(name=None)[source]
Parameters:

name (str)

class TradingVolume(name=None)[source]
Parameters:

name (str)

class DailyTradingVolume(name=None)[source]
Parameters:

name (str)

class TradingValue(name=None, book_size=None)[source]
Parameters:
class DailyTradingValue(name=None, book_size=None)[source]
Parameters:
class MaxPositionValue(name=None)[source]
Parameters:

name (str)

class MeanPositionValue(name=None)[source]
Parameters:

name (str)

class MedianPositionValue(name=None)[source]
Parameters:

name (str)

class MaxLeverage(name=None, book_size=0.0)[source]
Parameters: