book
Checkout our new book! Hands on AI Trading with Python, QuantConnect, and AWS Learn More arrow

Statistics

Runtime Statistics

Introduction

Runtime statistics show the performace of your algorithm at a single moment in time. Some of these statistics are a function of the risk free interest rate and the number of trading days per year.

Default Statistics

The following table describes the default runtime statistics:

StatisticDescription
EquityThe total portfolio value if all of the holdings were sold at current market rates.
FeesThe total quantity of fees paid for all the transactions.
HoldingsThe absolute sum of the items in the portfolio.
Net ProfitThe dollar-value return across the entire trading period.
PSRThe probability that the estimated Sharpe ratio of an algorithm is greater than a benchmark (1).
ReturnThe rate of return across the entire trading period.
UnrealizedThe amount of profit a portfolio would capture if it liquidated all open positions and paid the fees for transacting and crossing the spread.
VolumeThe total value of assets traded for all of an algorithm's transactions.

Add Statistics

To add a custom runtime statistic, call the set_runtime_statistic method with a name and value. The value argument can be a string or a number.

Select Language:
self.set_runtime_statistic(name, value)

Don't try to set a value for any of the preceding default runtime statistics. LEAN overwrites the value that you try to set.

Get Values

To get the value of a runtime statistic in an algorithm, index the runtime_statistics member of the algorithm class with the statistic name. The values of the runtime_statistics dictionary are strings, so you may need to cast the result to a different data type.

Select Language:
value = self.runtime_statistic[name]

The following table describe other ways to get the runtime statistics of your backtests and live algorithms:

Deployment TargetExecution ModeAccess Tools
QuantConnect CloudBacktest
QuantConnect CloudLive Trading
LocalBacktest
LocalLive Trading
  • Live results page on Local Platform
  • <organizationWorkspace> / <projectName> / live / <timeStamp> / / L-<deploymentId>.json

Examples

The following examples demonstrate common practices for setting runtime statistics.

Example 1: Display Banner

The following algorithm demonstrates how to put calculated runtime statistics in interest to the top display banner in the backtest interface and plot the data for analysis.

Select Language:
class RuntimeStatisticsAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 8, 12)
        self.set_end_date(2024, 9, 1)
        self.set_cash(1000000)

        # Request SPY data to trade.
        self.spy = self.add_equity("SPY").symbol
        # Create an EMA indicator to generate trade signals.
        self._ema = self.ema(self.spy, 20, Resolution.DAILY)
        # Warms up indicator for immediate readiness.
        self.warm_up_indicator(self.spy, self._ema, Resolution.DAILY)

    def on_data(self, slice: Slice) -> None:
        bar = slice.bars.get(self.spy)
        if bar:
            # Trend-following strategy using price and EMA.
            # If the price is above EMA, SPY is in an uptrend, and we buy it.
            if bar.close > self._ema.current.value and not self.portfolio[self.spy].is_long:
                self.set_holdings(self.spy, 1)
            elif bar.close < self._ema.current.value and not self.portfolio[self.spy].is_short:
                self.set_holdings(self.spy, -1)

    def on_end_of_day(self, symbol: Symbol) -> None:
        # Set the 95VaR and fee-to-profit ratio to the display banner.
        var = self.statistics.total_performance.portfolio_statistics.value_at_risk_95
        self.set_runtime_statistic("95VaR", var)
        fee_to_profit = self.statistics.total_performance.trade_statistics.total_fees /\
            self.statistics.total_performance.trade_statistics.total_profit_loss \
            if self.statistics.total_performance.trade_statistics.total_profit_loss != 0 else 0
        self.set_runtime_statistic("Fee-to-Profit", fee_to_profit)
    
        # Plot the calculated statistics.
        self.plot("Statistics", "95VaR", var)
        self.plot("Statistics", "fee-to-profit", fee_to_profit)

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: