Backtest Management

Create Backtest

Introduction

Create a new backtest request and get the backtest Id.

Request

Create a new backtest given a project Id and compile Id. The /backtests/create API accepts requests in the following format:

CreateBacktestRequest Model - Request to create a new backtest.
projectId integer
required
example: 23456789

Id of the project to backtest.
compileId string
required
example: 5d1f2cba3a0ec7407c566614300502b5-173e0419674daf4144ce7c9931155ca8

Compile Id for the project to backtest.
backtestName string
required
example: New Backtest

Name for the new backtest.
parameters string/number/integer object
Parameters to use for the backtest.
Example
{
  "projectId": 23456789,
  "compileId": "5d1f2cba3a0ec7407c566614300502b5-173e0419674daf4144ce7c9931155ca8",
  "backtestName": "New Backtest",
  "parameters": {
    "key": 0
  }
}

Responses

The /backtests/create API provides a response in the following format:

200 Success

BacktestResponse Model - Collection container for a list of backtests for a project.
backtest BacktestResult object
Results object class. Results are exhaust from backtest or live algorithms running in LEAN.
debugging boolean
Indicates if the backtest is run under debugging mode.
success boolean
Indicate if the API request was successful.
errors string Array
List of errors with the API call.
Example
{
  "backtest": {
    "note": "string",
    "name": "string",
    "organizationId": "d6d62db48592c72e67b534553413b602",
    "projectId": 23456789,
    "completed": true,
    "optimizationId": "O-401d3d40b5a0e9f8c46c954a303f3ddd",
    "backtestId": "26c7bb06b8487cff1c7b3c44652b30f1",
    "tradeableDates": 0,
    "researchGuide": {
      "minutes": 0,
      "backtestCount": 0,
      "parameters": 0
    },
    "backtestStart": "2021-11-26T15:18:27.693Z",
    "backtestEnd": "2021-11-26T15:18:27.693Z",
    "created": "2021-11-26T15:18:27.693Z",
    "snapshotId": 0,
    "status": "Completed.",
    "error": "string",
    "stacktrace": "string",
    "progress": 0,
    "hasInitializeError": true,
    "charts": {
      "name": "string"
    },
    "parameterSet": ,
    "rollingWindow": {
  },
    "runtimeStatistics": {
      "Equity": "$100.00",
      "Fees": "-$100.00",
      "Holdings": "$100.00",
      "Net Profit": "$100.00",
      "Probabilistic Sharpe Ratio": "50.00%",
      "Return": "50.00%",
      "Unrealized": "$100.00",
      "Volume": "$100.00"
    },
    "statistics": {
      "Total Orders": "string",
      "Average Win": "string",
      "Average Loss": "string",
      "Compounding Annual Return": "string",
      "Drawdown": "string",
      "Expectancy": "string",
      "Start Equity": "string",
      "End Equity": "string",
      "Net Profit": "string",
      "Sharpe Ratio": "string",
      "Sortino Ratio": "string",
      "Probabilistic Sharpe Ratio": "string",
      "Loss Rate": "string",
      "Win Rate": "string",
      "Profit-Loss Ratio": "string",
      "Alpha": "string",
      "Beta": "string",
      "Annual Standard Deviation": "string",
      "Annual Variance": "string",
      "Information Ratio": "string",
      "Tracking Error": "string",
      "Treynor Ratio": "string",
      "Total Fees": "string",
      "Estimated Strategy Capacity": "string",
      "Lowest Capacity Asset": "string",
      "Portfolio Turnover": "string",
      "Drawdown Recovery": "string"
    },
    "totalPerformance": {
      "tradeStatistics": {
        "startDateTime": "2021-11-26T15:18:27.693Z",
        "endDateTime": "2021-11-26T15:18:27.693Z",
        "totalNumberOfTrades": 0,
        "numberOfWinningTrades": 0,
        "numberOfLosingTrades": 0,
        "totalProfitLoss": "string",
        "totalProfit": "string",
        "totalLoss": "string",
        "largestProfit": "string",
        "largestLoss": "string",
        "averageProfitLoss": "string",
        "averageProfit": "string",
        "averageLoss": "string",
        "averageTradeDuration": "string",
        "averageWinningTradeDuration": "string",
        "averageLosingTradeDuration": "string",
        "medianTradeDuration": "string",
        "medianWinningTradeDuration": "string",
        "medianLosingTradeDuration": "string",
        "maxConsecutiveWinningTrades": 0,
        "maxConsecutiveLosingTrades": 0,
        "profitLossRatio": "string",
        "winLossRatio": "string",
        "winRate": "string",
        "lossRate": "string",
        "averageMAE": "string",
        "averageMFE": "string",
        "largestMAE": "string",
        "largestMFE": "string",
        "maximumClosedTradeDrawdown": "string",
        "maximumIntraTradeDrawdown": "string",
        "profitLossStandardDeviation": "string",
        "profitLossDownsideDeviation": "string",
        "profitFactor": "string",
        "sharpeRatio": "string",
        "sortinoRatio": "string",
        "profitToMaxDrawdownRatio": "string",
        "maximumEndTradeDrawdown": "string",
        "averageEndTradeDrawdown": "string",
        "maximumDrawdownDuration": "string",
        "totalFees": "string"
      },
      "portfolioStatistics": {
        "averageWinRate": "string",
        "averageLossRate": "string",
        "profitLossRatio": "string",
        "winRate": "string",
        "lossRate": "string",
        "expectancy": "string",
        "startEquity": "string",
        "endEquity": "string",
        "compoundingAnnualReturn": "string",
        "drawdown": "string",
        "totalNetProfit": "string",
        "sharpeRatio": "string",
        "probabilisticSharpeRatio": "string",
        "sortinoRatio": "string",
        "alpha": "string",
        "beta": "string",
        "annualStandardDeviation": "string",
        "annualVariance": "string",
        "informationRatio": "string",
        "trackingError": "string",
        "treynorRatio": "string",
        "portfolioTurnover": "string",
        "valueAtRisk99": "string",
        "valueAtRisk95": "string",
        "drawdownRecovery": "string"
      },
      "closedTrades": [
        {
          "symbol": {
            "value": "string",
            "id": "string",
            "permtick": "string"
          },
          "entryTime": "2021-11-26T15:18:27.693Z",
          "entryPrice": 0,
          "direction": 0,
          "quantity": 0,
          "exitTime": "2021-11-26T15:18:27.693Z",
          "exitPrice": 0,
          "profitLoss": 0,
          "totalFees": 0,
          "mae": 0,
          "mfe": 0,
          "duration": "string",
          "endTradeDrawdown": 0
        }
      ]
    },
    "nodeName": "string",
    "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z",
    "outOfSampleDays": 0,
    "analysis": [
      {
        "name": "PerformanceRelativeToBenchmarkAnalysis",
        "issue": "The strategy has a lower Sharpe ratio than the benchmark.",
        "sample": {
          "backtestSharpe": -0.2281345806218534,
          "benchmarkSharpe": -0.22182175736916387
        },
        "count": 5,
        "solutions": [
          "Try adjusting the trading rules and/or the universe to get a strategy that outperforms the benchmark."
        ]
      }
    ]
  },
  "debugging": true,
  "success": true,
  "errors": [
    "string"
  ]
}
BacktestResult Model - Results object class. Results are exhaust from backtest or live algorithms running in LEAN.
note string
Note on the backtest attached by the user.
name string
required

Name of the backtest.
organizationId string
required
example: d6d62db48592c72e67b534553413b602

The Id of the organization.
projectId integer
required
example: 23456789

Id of the project.
completed boolean
required

Boolean true when the backtest is completed.
optimizationId string
example: O-401d3d40b5a0e9f8c46c954a303f3ddd

Optimization task ID, if the backtest is part of an optimization.
backtestId string
required
example: 26c7bb06b8487cff1c7b3c44652b30f1

Assigned backtest ID.
tradeableDates integer
required

Number of tradeable days in the backtest.
researchGuide ResearchGuide object
A power gauge for backtests, time and parameters to estimate the overfitting risk.
backtestStart string($date-time)
required

The starting time of the backtest.
backtestEnd string($date-time)
required

The ending time of the backtest.
created string($date-time)
required

Backtest creation date and time.
snapshotId integer
required

Snapshot Id of this backtest result.
status string Enum
required

Status of the backtest. Options : ['Completed.', 'In Queue...', 'In Progress...', 'Runtime Error']
error string
required

Backtest error message.
stacktrace string
required

Backtest error stacktrace.
progress number
required

Progress of the backtest in percent 0-1.
hasInitializeError boolean
Indicates if the backtest has error during initialization.
charts ChartSummary object
required

Charts updates for the live algorithm since the last result packet.
parameterSet ParameterSet object
required

Parameters used in the backtest.
rollingWindow object
Rolling window detailed statistics.
runtimeStatistics RuntimeStatistics object
required

Runtime banner/updating statistics in the title banner of the live algorithm GUI.
statistics StatisticsResult object
required

Statistics information sent during the algorithm operations.
totalPerformance AlgorithmPerformance object
required

The AlgorithmPerformance class is a wrapper for TradeStatistics and PortfolioStatistics.
nodeName string
required

The backtest node name.
outOfSampleMaxEndDate string($date-time)
End date of out of sample data.
outOfSampleDays integer
Number of days of out of sample days.
analysis AnalysisResult Array
/.
Example
{
  "note": "string",
  "name": "string",
  "organizationId": "d6d62db48592c72e67b534553413b602",
  "projectId": 23456789,
  "completed": true,
  "optimizationId": "O-401d3d40b5a0e9f8c46c954a303f3ddd",
  "backtestId": "26c7bb06b8487cff1c7b3c44652b30f1",
  "tradeableDates": 0,
  "researchGuide": {
    "minutes": 0,
    "backtestCount": 0,
    "parameters": 0
  },
  "backtestStart": "2021-11-26T15:18:27.693Z",
  "backtestEnd": "2021-11-26T15:18:27.693Z",
  "created": "2021-11-26T15:18:27.693Z",
  "snapshotId": 0,
  "status": "Completed.",
  "error": "string",
  "stacktrace": "string",
  "progress": 0,
  "hasInitializeError": true,
  "charts": {
    "name": "string"
  },
  "parameterSet": ,
  "rollingWindow": {
},
  "runtimeStatistics": {
    "Equity": "$100.00",
    "Fees": "-$100.00",
    "Holdings": "$100.00",
    "Net Profit": "$100.00",
    "Probabilistic Sharpe Ratio": "50.00%",
    "Return": "50.00%",
    "Unrealized": "$100.00",
    "Volume": "$100.00"
  },
  "statistics": {
    "Total Orders": "string",
    "Average Win": "string",
    "Average Loss": "string",
    "Compounding Annual Return": "string",
    "Drawdown": "string",
    "Expectancy": "string",
    "Start Equity": "string",
    "End Equity": "string",
    "Net Profit": "string",
    "Sharpe Ratio": "string",
    "Sortino Ratio": "string",
    "Probabilistic Sharpe Ratio": "string",
    "Loss Rate": "string",
    "Win Rate": "string",
    "Profit-Loss Ratio": "string",
    "Alpha": "string",
    "Beta": "string",
    "Annual Standard Deviation": "string",
    "Annual Variance": "string",
    "Information Ratio": "string",
    "Tracking Error": "string",
    "Treynor Ratio": "string",
    "Total Fees": "string",
    "Estimated Strategy Capacity": "string",
    "Lowest Capacity Asset": "string",
    "Portfolio Turnover": "string",
    "Drawdown Recovery": "string"
  },
  "totalPerformance": {
    "tradeStatistics": {
      "startDateTime": "2021-11-26T15:18:27.693Z",
      "endDateTime": "2021-11-26T15:18:27.693Z",
      "totalNumberOfTrades": 0,
      "numberOfWinningTrades": 0,
      "numberOfLosingTrades": 0,
      "totalProfitLoss": "string",
      "totalProfit": "string",
      "totalLoss": "string",
      "largestProfit": "string",
      "largestLoss": "string",
      "averageProfitLoss": "string",
      "averageProfit": "string",
      "averageLoss": "string",
      "averageTradeDuration": "string",
      "averageWinningTradeDuration": "string",
      "averageLosingTradeDuration": "string",
      "medianTradeDuration": "string",
      "medianWinningTradeDuration": "string",
      "medianLosingTradeDuration": "string",
      "maxConsecutiveWinningTrades": 0,
      "maxConsecutiveLosingTrades": 0,
      "profitLossRatio": "string",
      "winLossRatio": "string",
      "winRate": "string",
      "lossRate": "string",
      "averageMAE": "string",
      "averageMFE": "string",
      "largestMAE": "string",
      "largestMFE": "string",
      "maximumClosedTradeDrawdown": "string",
      "maximumIntraTradeDrawdown": "string",
      "profitLossStandardDeviation": "string",
      "profitLossDownsideDeviation": "string",
      "profitFactor": "string",
      "sharpeRatio": "string",
      "sortinoRatio": "string",
      "profitToMaxDrawdownRatio": "string",
      "maximumEndTradeDrawdown": "string",
      "averageEndTradeDrawdown": "string",
      "maximumDrawdownDuration": "string",
      "totalFees": "string"
    },
    "portfolioStatistics": {
      "averageWinRate": "string",
      "averageLossRate": "string",
      "profitLossRatio": "string",
      "winRate": "string",
      "lossRate": "string",
      "expectancy": "string",
      "startEquity": "string",
      "endEquity": "string",
      "compoundingAnnualReturn": "string",
      "drawdown": "string",
      "totalNetProfit": "string",
      "sharpeRatio": "string",
      "probabilisticSharpeRatio": "string",
      "sortinoRatio": "string",
      "alpha": "string",
      "beta": "string",
      "annualStandardDeviation": "string",
      "annualVariance": "string",
      "informationRatio": "string",
      "trackingError": "string",
      "treynorRatio": "string",
      "portfolioTurnover": "string",
      "valueAtRisk99": "string",
      "valueAtRisk95": "string",
      "drawdownRecovery": "string"
    },
    "closedTrades": [
      {
        "symbol": {
          "value": "string",
          "id": "string",
          "permtick": "string"
        },
        "entryTime": "2021-11-26T15:18:27.693Z",
        "entryPrice": 0,
        "direction": 0,
        "quantity": 0,
        "exitTime": "2021-11-26T15:18:27.693Z",
        "exitPrice": 0,
        "profitLoss": 0,
        "totalFees": 0,
        "mae": 0,
        "mfe": 0,
        "duration": "string",
        "endTradeDrawdown": 0
      }
    ]
  },
  "nodeName": "string",
  "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z",
  "outOfSampleDays": 0,
  "analysis": [
    {
      "name": "PerformanceRelativeToBenchmarkAnalysis",
      "issue": "The strategy has a lower Sharpe ratio than the benchmark.",
      "sample": {
        "backtestSharpe": -0.2281345806218534,
        "benchmarkSharpe": -0.22182175736916387
      },
      "count": 5,
      "solutions": [
        "Try adjusting the trading rules and/or the universe to get a strategy that outperforms the benchmark."
      ]
    }
  ]
}
ResearchGuide Model - A power gauge for backtests, time and parameters to estimate the overfitting risk.
minutes integer
Number of minutes used in developing the current backtest.
backtestCount integer
The quantity of backtests run in the project.
parameters integer
Number of parameters detected.
Example
{
  "minutes": 0,
  "backtestCount": 0,
  "parameters": 0
}
ChartSummary Model - Contains the names of all charts
name string
Name of the Chart.
Example
{
  "name": "string"
}
RuntimeStatistics Model
Equity string
example: $100.00

Total portfolio value.
Fees string
example: -$100.00

Transaction fee.
Holdings string
example: $100.00

Equity value of security holdings.
Net Profit string
example: $100.00

Net profit.
Probabilistic Sharpe Ratio string
example: 50.00%

Probabilistic Sharpe Ratio.
Return string
example: 50.00%

Return.
Unrealized string
example: $100.00

Unrealized profit/loss.
Volume string
example: $100.00

Total transaction volume.
Example
{
  "Equity": "$100.00",
  "Fees": "-$100.00",
  "Holdings": "$100.00",
  "Net Profit": "$100.00",
  "Probabilistic Sharpe Ratio": "50.00%",
  "Return": "50.00%",
  "Unrealized": "$100.00",
  "Volume": "$100.00"
}
StatisticsResult Model - Statistics information sent during the algorithm operations.
Total Orders string
Total nuber of orders.
Average Win string
The average rate of return for winning trades.
Average Loss string
The average rate of return for losing trades.
Compounding Annual Return string
Annual compounded returns statistic based on the final-starting capital and years.
Drawdown string
Drawdown maximum percentage.
Expectancy string
The expected value of the rate of return.
Start Equity string
Initial Equity Total Value.
End Equity string
Final Equity Total Value.
Net Profit string
The total net profit percentage.
Sharpe Ratio string
Sharpe ratio with respect to risk free rate; measures excess of return per unit of risk.
Sortino Ratio string
Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk.
Probabilistic Sharpe Ratio string
Is a probability measure associated with the Sharpe ratio. It informs us of the probability that the estimated Sharpe ratio is greater than a chosen benchmark.
Loss Rate string
The ratio of the number of losing trades to the total number of trades.
Win Rate string
The ratio of the number of winning trades to the total number of trades.
Profit-Loss Ratio string
The ratio of the average win rate to the average loss rate.
Alpha string
Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns.
Beta string
Algorithm "beta" statistic - the covariance between the algorithm and benchmark performance, divided by benchmark's variance.
Annual Standard Deviation string
Annualized standard deviation.
Annual Variance string
Annualized variance statistic calculation using the daily performance variance and trading days per year.
Information Ratio string
Information ratio - risk adjusted return.
Tracking Error string
Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked.
Treynor Ratio string
Treynor ratio statistic is a measurement of the returns earned in excess of that which could have been earned on an investment that has no diversifiable risk.
Total Fees string
Total amount of fees.
Estimated Strategy Capacity string
The estimated total capacity of the strategy at a point in time.
Lowest Capacity Asset string
Provide a reference to the lowest capacity symbol used in scaling down the capacity for debugging.
Portfolio Turnover string
The average Portfolio Turnover.
Drawdown Recovery string
/.
Example
{
  "Total Orders": "string",
  "Average Win": "string",
  "Average Loss": "string",
  "Compounding Annual Return": "string",
  "Drawdown": "string",
  "Expectancy": "string",
  "Start Equity": "string",
  "End Equity": "string",
  "Net Profit": "string",
  "Sharpe Ratio": "string",
  "Sortino Ratio": "string",
  "Probabilistic Sharpe Ratio": "string",
  "Loss Rate": "string",
  "Win Rate": "string",
  "Profit-Loss Ratio": "string",
  "Alpha": "string",
  "Beta": "string",
  "Annual Standard Deviation": "string",
  "Annual Variance": "string",
  "Information Ratio": "string",
  "Tracking Error": "string",
  "Treynor Ratio": "string",
  "Total Fees": "string",
  "Estimated Strategy Capacity": "string",
  "Lowest Capacity Asset": "string",
  "Portfolio Turnover": "string",
  "Drawdown Recovery": "string"
}
AlgorithmPerformance Model - The AlgorithmPerformance class is a wrapper for TradeStatistics and PortfolioStatistics.
tradeStatistics TradeStatistics object
A set of statistics calculated from a list of closed trades.
portfolioStatistics PortfolioStatistics object
Represents a set of statistics calculated from equity and benchmark samples.
closedTrades Trade Array
The algorithm statistics on portfolio.
Example
{
  "tradeStatistics": {
    "startDateTime": "2021-11-26T15:18:27.693Z",
    "endDateTime": "2021-11-26T15:18:27.693Z",
    "totalNumberOfTrades": 0,
    "numberOfWinningTrades": 0,
    "numberOfLosingTrades": 0,
    "totalProfitLoss": "string",
    "totalProfit": "string",
    "totalLoss": "string",
    "largestProfit": "string",
    "largestLoss": "string",
    "averageProfitLoss": "string",
    "averageProfit": "string",
    "averageLoss": "string",
    "averageTradeDuration": "string",
    "averageWinningTradeDuration": "string",
    "averageLosingTradeDuration": "string",
    "medianTradeDuration": "string",
    "medianWinningTradeDuration": "string",
    "medianLosingTradeDuration": "string",
    "maxConsecutiveWinningTrades": 0,
    "maxConsecutiveLosingTrades": 0,
    "profitLossRatio": "string",
    "winLossRatio": "string",
    "winRate": "string",
    "lossRate": "string",
    "averageMAE": "string",
    "averageMFE": "string",
    "largestMAE": "string",
    "largestMFE": "string",
    "maximumClosedTradeDrawdown": "string",
    "maximumIntraTradeDrawdown": "string",
    "profitLossStandardDeviation": "string",
    "profitLossDownsideDeviation": "string",
    "profitFactor": "string",
    "sharpeRatio": "string",
    "sortinoRatio": "string",
    "profitToMaxDrawdownRatio": "string",
    "maximumEndTradeDrawdown": "string",
    "averageEndTradeDrawdown": "string",
    "maximumDrawdownDuration": "string",
    "totalFees": "string"
  },
  "portfolioStatistics": {
    "averageWinRate": "string",
    "averageLossRate": "string",
    "profitLossRatio": "string",
    "winRate": "string",
    "lossRate": "string",
    "expectancy": "string",
    "startEquity": "string",
    "endEquity": "string",
    "compoundingAnnualReturn": "string",
    "drawdown": "string",
    "totalNetProfit": "string",
    "sharpeRatio": "string",
    "probabilisticSharpeRatio": "string",
    "sortinoRatio": "string",
    "alpha": "string",
    "beta": "string",
    "annualStandardDeviation": "string",
    "annualVariance": "string",
    "informationRatio": "string",
    "trackingError": "string",
    "treynorRatio": "string",
    "portfolioTurnover": "string",
    "valueAtRisk99": "string",
    "valueAtRisk95": "string",
    "drawdownRecovery": "string"
  },
  "closedTrades": [
    {
      "symbol": {
        "value": "string",
        "id": "string",
        "permtick": "string"
      },
      "entryTime": "2021-11-26T15:18:27.693Z",
      "entryPrice": 0,
      "direction": 0,
      "quantity": 0,
      "exitTime": "2021-11-26T15:18:27.693Z",
      "exitPrice": 0,
      "profitLoss": 0,
      "totalFees": 0,
      "mae": 0,
      "mfe": 0,
      "duration": "string",
      "endTradeDrawdown": 0
    }
  ]
}
TradeStatistics Model - A set of statistics calculated from a list of closed trades.
startDateTime string($date-time)
The entry date/time of the first trade.
endDateTime string($date-time)
The exit date/time of the first trade.
totalNumberOfTrades integer
The total number of trades.
numberOfWinningTrades integer
The total number of winning trades.
numberOfLosingTrades integer
The total number of losing trades.
totalProfitLoss string
The total profit/loss for all trades (as symbol currency).
totalProfit string
The total profit for all winning trades (as symbol currency).
totalLoss string
The total loss for all losing trades (as symbol currency).
largestProfit string
The largest profit in a single trade (as symbol currency).
largestLoss string
The largest loss in a single trade (as symbol currency).
averageProfitLoss string
The average profit/loss (a.k.a. Expectancy or Average Trade) for all trades (as symbol currency).
averageProfit string
The average profit for all winning trades (as symbol currency).
averageLoss string
The average loss for all winning trades (as symbol currency).
averageTradeDuration string
The average duration for all trades.
averageWinningTradeDuration string
The average duration for all winning trades.
averageLosingTradeDuration string
The average duration for all losing trades.
medianTradeDuration string
The median duration for all trades.
medianWinningTradeDuration string
The median duration for all winning trades.
medianLosingTradeDuration string
The median duration for all losing trades.
maxConsecutiveWinningTrades integer
The maximum number of consecutive winning trades.
maxConsecutiveLosingTrades integer
The maximum number of consecutive losing trades.
profitLossRatio string
The ratio of the average profit per trade to the average loss per trade.
winLossRatio string
The ratio of the number of winning trades to the number of losing trades.
winRate string
The ratio of the number of winning trades to the total number of trades.
lossRate string
The ratio of the number of losing trades to the total number of trades.
averageMAE string
The average Maximum Adverse Excursion for all trades.
averageMFE string
The average Maximum Adverse Excursion for all trades.
largestMAE string
The average Maximum Favorable Excursion for all trades.
largestMFE string
The largest Maximum Adverse Excursion in a single trade (as symbol currency).
maximumClosedTradeDrawdown string
The maximum closed-trade drawdown for all trades (as symbol currency).
maximumIntraTradeDrawdown string
The maximum intra-trade drawdown for all trades (as symbol currency).
profitLossStandardDeviation string
The standard deviation of the profits/losses for all trades (as symbol currency).
profitLossDownsideDeviation string
The downside deviation of the profits/losses for all trades (as symbol currency).
profitFactor string
The ratio of the total profit to the total loss.
sharpeRatio string
The ratio of the average profit/loss to the standard deviation.
sortinoRatio string
The ratio of the average profit/loss to the downside deviation.
profitToMaxDrawdownRatio string
The ratio of the total profit/loss to the maximum closed trade drawdown.
maximumEndTradeDrawdown string
The maximum amount of profit given back by a single trade before exit (as symbol currency).
averageEndTradeDrawdown string
The average amount of profit given back by all trades before exit (as symbol currency).
maximumDrawdownDuration string
The maximum amount of time to recover from a drawdown (longest time between new equity highs or peaks).
totalFees string
The sum of fees for all trades.
Example
{
  "startDateTime": "2021-11-26T15:18:27.693Z",
  "endDateTime": "2021-11-26T15:18:27.693Z",
  "totalNumberOfTrades": 0,
  "numberOfWinningTrades": 0,
  "numberOfLosingTrades": 0,
  "totalProfitLoss": "string",
  "totalProfit": "string",
  "totalLoss": "string",
  "largestProfit": "string",
  "largestLoss": "string",
  "averageProfitLoss": "string",
  "averageProfit": "string",
  "averageLoss": "string",
  "averageTradeDuration": "string",
  "averageWinningTradeDuration": "string",
  "averageLosingTradeDuration": "string",
  "medianTradeDuration": "string",
  "medianWinningTradeDuration": "string",
  "medianLosingTradeDuration": "string",
  "maxConsecutiveWinningTrades": 0,
  "maxConsecutiveLosingTrades": 0,
  "profitLossRatio": "string",
  "winLossRatio": "string",
  "winRate": "string",
  "lossRate": "string",
  "averageMAE": "string",
  "averageMFE": "string",
  "largestMAE": "string",
  "largestMFE": "string",
  "maximumClosedTradeDrawdown": "string",
  "maximumIntraTradeDrawdown": "string",
  "profitLossStandardDeviation": "string",
  "profitLossDownsideDeviation": "string",
  "profitFactor": "string",
  "sharpeRatio": "string",
  "sortinoRatio": "string",
  "profitToMaxDrawdownRatio": "string",
  "maximumEndTradeDrawdown": "string",
  "averageEndTradeDrawdown": "string",
  "maximumDrawdownDuration": "string",
  "totalFees": "string"
}
PortfolioStatistics Model - Represents a set of statistics calculated from equity and benchmark samples.
averageWinRate string
The average rate of return for winning trades.
averageLossRate string
The average rate of return for losing trades.
profitLossRatio string
The ratio of the average win rate to the average loss rate.
winRate string
The ratio of the number of winning trades to the total number of trades.
lossRate string
The ratio of the number of losing trades to the total number of trades.
expectancy string
The expected value of the rate of return.
startEquity string
Initial Equity Total Value.
endEquity string
Final Equity Total Value.
compoundingAnnualReturn string
Annual compounded returns statistic based on the final-starting capital and years.
drawdown string
Drawdown maximum percentage.
totalNetProfit string
The total net profit percentage.
sharpeRatio string
Sharpe ratio with respect to risk free rate: measures excess of return per unit of risk.
probabilisticSharpeRatio string
Probabilistic Sharpe Ratio is a probability measure associated with the Sharpe ratio. It informs us of the probability that the estimated Sharpe ratio is greater than a chosen benchmark.
sortinoRatio string
Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk.
alpha string
Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns.
beta string
Algorithm beta statistic - the covariance between the algorithm and benchmark performance, divided by benchmark variance.
annualStandardDeviation string
Annualized standard deviation.
annualVariance string
Annualized variance statistic calculation using the daily performance variance and trading days per year.
informationRatio string
Information ratio - risk adjusted return.
trackingError string
Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked.
treynorRatio string
Treynor ratio statistic is a measurement of the returns earned in excess of that which could have been earned on an investment that has no diversifiable risk.
portfolioTurnover string
The average Portfolio Turnover.
valueAtRisk99 string
The 1-day VaR for the portfolio, using the Variance-covariance approach. Assumes a 99% confidence level, 1 year lookback period, and that the returns are normally distributed.
valueAtRisk95 string
The 1-day VaR for the portfolio, using the Variance-covariance approach. Assumes a 95% confidence level, 1 year lookback period, and that the returns are normally distributed.
drawdownRecovery string
/.
Example
{
  "averageWinRate": "string",
  "averageLossRate": "string",
  "profitLossRatio": "string",
  "winRate": "string",
  "lossRate": "string",
  "expectancy": "string",
  "startEquity": "string",
  "endEquity": "string",
  "compoundingAnnualReturn": "string",
  "drawdown": "string",
  "totalNetProfit": "string",
  "sharpeRatio": "string",
  "probabilisticSharpeRatio": "string",
  "sortinoRatio": "string",
  "alpha": "string",
  "beta": "string",
  "annualStandardDeviation": "string",
  "annualVariance": "string",
  "informationRatio": "string",
  "trackingError": "string",
  "treynorRatio": "string",
  "portfolioTurnover": "string",
  "valueAtRisk99": "string",
  "valueAtRisk95": "string",
  "drawdownRecovery": "string"
}
Trade Model - Represents a closed trade.
symbol Symbol object
Represents a unique security identifier. This is made of two components, the unique SID and the Value. The value is the current ticker symbol while the SID is constant over the life of a security.
entryTime string($date-time)
The date and time the trade was opened.
entryPrice number
The price at which the trade was opened (or the average price if multiple entries).
direction integer Enum
Direction of a trade. 0=Long, 1=Short. Options : [0, 1]
quantity number
The total unsigned quantity of the trade.
exitTime string($date-time)
The date and time the trade was closed.
exitPrice number
The price at which the trade was closed (or the average price if multiple exits).
profitLoss number
The gross profit/loss of the trade (as account currency).
totalFees number
The total fees associated with the trade (always positive value) (as account currency).
mae number
The Maximum Adverse Excursion (as account currency).
mfe number
The Maximum Favorable Excursion (as account currency).
duration string
The duration of the trade.
endTradeDrawdown number
The amount of profit given back before the trade was closed.
Example
{
  "symbol": {
    "value": "string",
    "id": "string",
    "permtick": "string"
  },
  "entryTime": "2021-11-26T15:18:27.693Z",
  "entryPrice": 0,
  "direction": 0,
  "quantity": 0,
  "exitTime": "2021-11-26T15:18:27.693Z",
  "exitPrice": 0,
  "profitLoss": 0,
  "totalFees": 0,
  "mae": 0,
  "mfe": 0,
  "duration": "string",
  "endTradeDrawdown": 0
}
Symbol Model - Represents a unique security identifier. This is made of two components, the unique SID and the Value. The value is the current ticker symbol while the SID is constant over the life of a security.
value string
The current symbol for this ticker.
id string
The security identifier for this symbol.
permtick string
The ticker at IPO for this security.
Example
{
  "value": "string",
  "id": "string",
  "permtick": "string"
}
AnalysisResult Model - The result of an analysis performed on a result.
name string
required
example: PerformanceRelativeToBenchmarkAnalysis

The name of the analysis that produced this result.
issue string
required
example: The strategy has a lower Sharpe ratio than the benchmark.

A short description of why the analysis was triggered.
sample object
required
example: {'backtestSharpe': -0.2281345806218534, 'benchmarkSharpe': -0.22182175736916387}

A representative sample value of the issue detected by the analysis.
count integer
example: 5

The total number of matching occurrences found by the analysis. If not present, it should be assumed that there is only one occurrence.
solutions string Array
required

Human-readable suggestions for resolving the detected issue.
Example
{
  "name": "PerformanceRelativeToBenchmarkAnalysis",
  "issue": "The strategy has a lower Sharpe ratio than the benchmark.",
  "sample": {
    "backtestSharpe": -0.2281345806218534,
    "benchmarkSharpe": -0.22182175736916387
  },
  "count": 5,
  "solutions": [
    "Try adjusting the trading rules and/or the universe to get a strategy that outperforms the benchmark."
  ]
}

401 Authentication Error

UnauthorizedError Model - Unauthorized response from the API. Key is missing, invalid, or timestamp is too old for hash.
www_authenticate string
Header

Examples

The following example demonstates creating, reading, updating, deleting, and listing backtests of a project through the cloud API.

from base64 import b64encode
from hashlib import sha256
from time import time
from requests import get, post
BASE_URL = 'https://www.quantconnect.com/api/v2/'

# You need to replace these with your actual credentials.
# You can request your credentials at https://www.quantconnect.com/settings/
# You can find our organization ID at https://www.quantconnect.com/organization/ 
USER_ID = 0
API_TOKEN = '____'
ORGANIZATION_ID = '____'

def get_headers():
    # Get timestamp
    timestamp = f'{int(time())}'
    time_stamped_token = f'{API_TOKEN}:{timestamp}'.encode('utf-8')

    # Get hased API token
    hashed_token = sha256(time_stamped_token).hexdigest()
    authentication = f'{USER_ID}:{hashed_token}'.encode('utf-8')
    authentication = b64encode(authentication).decode('ascii')

    # Create headers dictionary.
    return {
        'Authorization': f'Basic {authentication}',
        'Timestamp': timestamp
    }

# Authenticate to verify credentials
response = post(f'{BASE_URL}/authenticate', headers = get_headers())
print(response.json())

# --------------------


### Create Backtest
# Define placeholder compilation ID (replace with actual value)
compile_id = "compile_id..."
# Send a POST request to the /backtests/create endpoint to create a backtest
response = post(f'{BASE_URL}/backtests/create', headers=get_headers(), json={
    "projectId": project_id,  # ID of the project to backtest
    "compileId": compile_id,  # Compilation ID for the backtest
    "backtestName": f"Backtest {int(time())}"  # Unique name for the backtest using current timestamp
})
# Parse the JSON response into python managable dict
result = response.json()
# Extract the backtest ID from the response
backtest_id = result['backtest']['backtestId']
# Check if the request was successful and print the result
if result['success']:
    print("Backtest Created Successfully:")
    print(result)

### Read Backtest Statistics
# Prepare data payload to read backtest statistics
payload = {
    "projectId": project_id,  # ID of the project
    "backtestId": backtest_id  # ID of the backtest to read
}
# Send a POST request to the /backtests/read endpoint to get statistics
response = post(f'{BASE_URL}/backtests/read', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the statistics
if result['success']:
    print("Backtest Statistics:")
    print(result)

### Update Backtest
# Send a POST request to the /backtests/update endpoint to update backtest details
response = post(f'{BASE_URL}/backtests/update', headers=get_headers(), json={
    "projectId": project_id,  # ID of the project
    "backtestId": backtest_id,  # ID of the backtest to update
    "name": f"Backtest_{backtest_id}",  # New name for the backtest
    "note": "The new backtest name is awesome!"  # Additional note
})
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the result
if result['success']:
    print("Backtest Updated Successfully:")
    print(result)

### Delete Backtest
# Prepare data payload to delete the backtest
payload = {
    "projectId": project_id,  # ID of the project
    "backtestId": backtest_id  # ID of the backtest to delete
}
# Send a POST request to the /backtests/delete endpoint to delete the backtest
response = post(f'{BASE_URL}/backtests/delete', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the result
if result['success']:
    print("Backtest Deleted Successfully:")
    print(result)

### List Backtests
# Prepare data payload to list backtests with statistics
payload = {
    "projectId": project_id,  # ID of the project
    "includeStatistics": True  # Include statistics in the response
}
# Send a POST request to the /backtests/list endpoint to list backtests
response = post(f'{BASE_URL}/backtests/list', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the list
if result['success']:
    print("List of Backtests:")
    print(result)

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: