Search Framework:
Backtester
Namespace: WealthLab.Backtest
Parent: Object

The Backtester class is responsible for performing backtest runs in WL8, and returning information about those runs. This document will focus on the Backtester properties that provide performance information about backtest runs, typically for use in the development of ScoreCard or Performance Visualizer extensions.

Backtest Result Properties
BenchmarkBacktestResults
public Backtester BenchmarkBacktestResults

Returns the Backtester instance for the benchmark comparison backtest run. This property might contain null, in which case it is most likely the benchmark backtest itself that is running.


CashCurve
public TimeSeries CashCurve

Returns a TimeSeries instance that represents how much simulated cash was available during the backtest.


CashInterestEarned
public double CashInterestEarned

Returns the total simulated cash interest earned during the backtest.


CommissionPaid
public double CommissionsPaid

Returns the total amount of simulated commission paid in the backtest.


CurrentCash
public double CurrentCash

Returns the simulated cash available at the end of the backtest.


CurrentEquity
public double CurrentEquity

Returns the total equity (capital) at the end of the backtest.


DailyReturns
public TimeSeries DailyReturns

Returns a TimeSeries containing the daily percentage returns of backtest equity curve.


DividendsPaid
public double DividendsPaid

Returns the amount of simulated dividends collected in the backtest. Dividends are captured from EventDataPoint instances in the BarHistory EventDataPoints property with "dividend" in the instance's Name property. Deduping logic is used to ensure that only a single dividend is accounted for each day, even if multiple Event Data Providers that return dividends are enabled.


DrawdownCurve
public TimeSeries DrawdownCurve

Returns a TimeSeries instance of the backtest drawdown, which is the largest peak to trough decline of the equity over time. Drawdown is calculated on a closing price basis, and does not consider highs and lows.


DrawdownPctCurve
public TimeSeries DrawdownPctCurve

Returns a TimeSeries instance of the backtest drawdown percentage, which is the largest peak to trough percentage decline of the equity over time. Drawdown is calculated on a closing price basis, and does not consider highs and lows.


EquityCurve
public TimeSeries EquityCurve

Returns a TimeSeries instance that represents the equity curve of the backtest.


LiveAccount
public BrokerAccout LiveAccount

Returns a read-only Live BrokerAccount instance in the Strategy Monitor or Streaming Strategy Window when the Trading Preference Use Live Positions is enabled. Use it to access the selected broker account and obtain account's value, cash, or broker position data.

Remarks

  • LiveAccount is null if the Backtester is not operating with the Live Positions preference.
  • The Dummy Broker is also considered a live broker account.
Example Code
using WealthLab.Backtest;
using System;
using WealthLab.Core;
using WealthLab.Data;
using WealthLab.Indicators;
using System.Collections.Generic;

namespace WealthScript123
{
    public class LiveAccountDemo : UserStrategyBase
    {   
        public override void Initialize(BarHistory bars)
        {
			double curreq = CurrentEquity;
			string acctName = "Backtester";
						
			if (Backtester.LiveAccount != null)
			{
				// we're running in the S. Monitor or Streaming Chart with "Use Live Positions"
				acctName = Backtester.LiveAccount.AccountID;
				curreq = Backtester.LiveAccount.AccountValue;
				
				DrawHeaderText($"{acctName}: {curreq:N2}", WLColor.NeonGreen, 14);
				foreach(BrokerPosition bp in Backtester.LiveAccount.Positions)
					DrawHeaderText($"{bp.Quantity} {bp.Symbol}", WLColor.NeonGreen, 10);
			}
			else
	        	DrawHeaderText($"{acctName}: {curreq:N2}", WLColor.Gold, 14);
		}

        
        public override void Execute(BarHistory bars, int idx)
        {
        }
    }
}

LosingPositions
public PositionList LosingPositions

Returns a PositionList instance containing Position instances for the positions with a net profit less than zero.


MarginInterestPaid
public double MarginInterestPaid

Returns the amount of simulated interest paid for going on margin in the backtest.


MonthlyNegativeReturns
public TimeSeries MonthlyNegativeReturns

Returns a TimeSeries containing the negative monthly percentage returns of the backtest. The negative returns are used when calculating the Sortino Ratio.


MonthlyReturns
public TimeSeries MonthlyReturns

Returns a TimeSeries containing the monthly percentage returns of backtest equity curve.


NetProfit
public double NetProfit

Returns the net profit of the backtest.


NetProfitPct
public double NetProfitPct

Returns the percentage net profit of the backtest.


NSFPositions
public PositionList NSFPositions

Returns a PositionList instance that contains Position instances representing the positions that were flagged as NSF (non-sufficient funds) and thus not included in the performance results. The Backtest still tracks these NSF positions during a backtest so the Strategy's integrity can be maintained. It also issues exit signals for NSF positions, since you might have initiated an entry into an NSF position in your live trading account, even if the Backtester did not have enough simulated capital to enter the trade.


OpenPositionCount
public int OpenPositionCount

Returns the number of currently open position in the backtest, excluding Position instances that were flagged NSF (non-sufficient funds).


OpenPositionCountHistory
public TimeSeries OpenPositionCountHistory

Returns a TimeSeries instance containing the number of open positions over time during the backtest.


OpenPositions
public PositionList OpenPositions

Returns a PositionList instance containing the Position instances for the open positions remaining in backtest. This contains positions that were flagged as NSF (non-sufficient funds) so not included in the performance results.


Orders
public List<Transaction> Orders

Returns a List that contains Transaction instances that represent the orders, or signals, that need to be placed for the Strategy at the next market session.


PositionMetricNames
public List<string> PositionMetricNames

Returns a list of all available Position Metrics for this backtest run. This includes all of the default Position Metrics, such as Profit and BarsHeld, as well as any Strategy assigned PositionMetrics that were the result of calls to Position.SetMetric or Transaction.SetPositionMetric. Typically used by certain Performance Visualizers that deal with Positions, such as the Position Metrics Visualizer in the Power Pack Extension.


Positions
public PositionList Positions

Returns a PositionList instance containing the Position instances for the positions taken during the backtest.


RiskFreeRateOfReturn
public double RiskFreeRateOfReturn

Returns the average percentage return of the 1-year US Treasury yield for the time span of the backtest. Used in calculating Sharpe Ratio and Sortino Ratio in the Basic Scorecard.


TradeHistoryCount
public TimeSeries TradeCountHistory

Returns a TimeSeries instance containing the number of trades at each point in time for the backtest.


TransactionLog
public List<Transaction> TransactionLog

Returns a list of the Transaction instances that represent all of the buy, sell, short, and cover trades that were placed.


WinningPositions
public PositionList WinningPositions

Returns a PositionList instance containing Position instances for the positions with a net profit greater than or equal to zero.


YearlyReturns
public TimeSeries YearlyReturns

Returns a TimeSeries containing the yearly percentage returns of backtest equity curve.



Informational Properties
BacktestSettings
public BacktestSettings BacktestSettings

Returns the backtest settings (instance of the BacktestSettings class) used in the backtest.


ExecutionMode
public StrategyExecutionMode ExecutionMode

Returns the context in which the Strategy is being executed. Possible values are:

  • Strategy
  • Optimization
  • StreamingChart
  • StrategyMonitor
  • Rankings
  • Evolver

PositionSize
public PositionSize PositionSize

Returns the positing sizing method (instance of the PositionSize class) used in the backtest.


StartingCapital
public double StartingCapital

Returns the starting capital that was used for the backtest.


Strategy
public Strategy Strategy

Returns the instance of the Strategy class.


Symbols
public List<BarHistory> Symbols

Returns a List containing the BarHistory instances for the symbols that were backtested.



Metrics
Metrics
public dynamic Metrics

The Metrics property returns an instance of the dynamic class that contains various performance metrics from the ScoreCards available in WL8. ScoreCards assign named property values to the Metrics propety for the performance metrics that they calculate. For example, the net profit of the backtest run is assigned to the Metrics.NetProfit property, and the APR to the Metrics.APR property. Performance Visualizers typically access these metrics values when depicting the backtest performance in an individual way.



Trading Control
CancelationCode
public int? CancelationCode

Assign a value to Backtester.CancelationCode in your Strategy to cause separate exit orders that occur after the assignment to be grouped into one logical unit. When one of the exit orders fills, any other open exit orders with the same CancelationCode will be canceled. The Backtester assigns the CancelationCode to the exit orders at the time of their creation behind the scenes (while processing PlaceTrade or ClosePosition.)

CancelationCode is unique by symbol - you can use the same CancelationCode for different symbols. This menans that a group of orders for 'SPY' using CancelationCode 123 won't affect orders for 'QQQ' (or any other symbol) also using CancelationCode 123.

Example Code
using WealthLab.Backtest;
using System;
using WealthLab.Core;
using WealthLab.Data;
using WealthLab.Indicators;
using System.Collections.Generic;

namespace WealthScript123
{
    public class MyStrategy : UserStrategyBase
    {
		public MyStrategy()
		{
			_period = AddParameter("Period", ParameterType.Int32, 10, 5, 20, 1);
		}
        
        public override void Initialize(BarHistory bars)
        {			
			_ma = SMA.Series(bars.Close, _period.AsInt);
			PlotIndicator(_ma);
			
			PlotStopsAndLimits(3); 
			StartIndex = _period.AsInt;
        }

        
        public override void Execute(BarHistory bars, int idx)
        {
            if (!HasOpenPosition(bars, PositionType.Long))
            {
				if (bars.Close.CrossesOver(_ma, idx))
				{
					Transaction t = PlaceTrade(bars, TransactionType.Buy, OrderType.Market); 					
				}                
            }
            else
            {
				Position p = LastPosition;

				// sell at 8% Stop Loss
				Backtester.CancelationCode = 12;
				ClosePosition(p, OrderType.Stop, p.EntryPrice * 0.92, "8% S/L");

				// sell at a 4% Trailing Stop once 5% Profit is achieved
				if (p.MFEPctAsOf(idx) >= 5)
				{
					Backtester.CancelationCode = 12;
					CloseAtTrailingStop(p, TrailingStopType.PercentC, 4.0, "Tstop");
				}
				
				// sell at 10% Profit Target
				Backtester.CancelationCode = 12;
				ClosePosition(p, OrderType.Limit, p.EntryPrice * 1.10, "10% Tgt");
            }
        }

		Parameter _period;
		SMA _ma; 
    }
}