Backtest Management
List Backtests
Request
Fetch the results for the project Id provided. The /backtests/list
API accepts requests in the following format:
ListBacktestRequest Model - Request to list the backtests from a project. | |
---|---|
projectId | integer Id of the project from which to read one or multiple backtests. |
includeStatistics | boolean If true, the backtests summaries from the response will contain the statistics with their corresponding values. |
Example |
{ "projectId": 23456789, "includeStatistics": True } |
Responses
The /backtests/list
API provides a response in the following format:
200 Success
BacktestSummaryResponse Model - Collection container for a list of backtest summaries for a project. | |
---|---|
backtest | BacktestSummaryResult Array Collection of backtest summaries for a project. |
count | integer Number of backtest summaries retrieved in the response. |
success | boolean Indicate if the API request was successful. |
errors | string Array List of errors with the API call. |
Example |
{ "backtest": [ { "backtestId": "26c7bb06b8487cff1c7b3c44652b30f1", "status": "Completed.", "name": "string", "created": "2021-11-26T15:18:27.693Z", "progress": 0, "optimizationId": "O-401d3d40b5a0e9f8c46c954a303f3ddd", "tradeableDates": 0, "parameterSet": { "name": "string", "value": 0 }, "snapshotId": 0, "tags": [ "string" ], "sharpeRatio": , "alpha": , "beta": , "compoundingAnnualReturn": , "drawdown": , "lossRate": , "netProfit": , "parameters": 0, "psr": , "securityTypes": "string", "sortinoRatio": , "trades": 0, "treynorRatio": , "winRate": } ], "count": 0, "success": true, "errors": [ "string" ] } |
BacktestSummaryResult Model - Result object class for the List Backtest response from the API. | |
---|---|
backtestId | string Assigned backtest ID. |
status | string Enum Status of the backtest. Options : ['Completed.', 'In Queue...', "'Running: _%'"] |
name | string Name of the backtest. |
created | string($date-time) Backtest creation date and time. |
progress | number Progress of the backtest in percent 0-1. |
optimizationId | string Optimization task ID, if the backtest is part of an optimization. |
tradeableDates | integer Number of traadeable days. |
parameterSet | ParameterSet object Parameters used in the backtest. |
snapshotId | integer Snapshot id of this backtest result. |
tags | string Array Collection of tags for the backtest. |
sharpeRatio | float Sharpe ratio with respect to risk free rate; measures excess of return per unit of risk. |
alpha | float Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns. |
beta | float Algorithm "beta" statistic - the covariance between the algorithm and benchmark performance, divided by benchmark's variance. |
compoundingAnnualReturn | float Annual compounded returns statistic based on the final-starting capital and years. |
drawdown | float Drawdown maximum percentage. |
lossRate | float The ratio of the number of losing trades to the total number of trades. |
netProfit | float Net profit percentage. |
parameters | integer Number of parameters in the backtest. |
psr | float Price-to-sales ratio. |
securityTypes | string SecurityTypes present in the backtest. |
sortinoRatio | float Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk. |
trades | integer Number of trades in the backtest. |
treynorRatio | float 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. |
winRate | float The ratio of the number of winning trades to the total number of trades. |
Example |
{ "backtestId": "26c7bb06b8487cff1c7b3c44652b30f1", "status": "Completed.", "name": "string", "created": "2021-11-26T15:18:27.693Z", "progress": 0, "optimizationId": "O-401d3d40b5a0e9f8c46c954a303f3ddd", "tradeableDates": 0, "parameterSet": { "name": "string", "value": 0 }, "snapshotId": 0, "tags": [ "string" ], "sharpeRatio": , "alpha": , "beta": , "compoundingAnnualReturn": , "drawdown": , "lossRate": , "netProfit": , "parameters": 0, "psr": , "securityTypes": "string", "sortinoRatio": , "trades": 0, "treynorRatio": , "winRate": } |
ParameterSet Model - Parameter set. | |
---|---|
name | string Name of parameter. |
value | number Value of parameter. |
Example |
{ "name": "string", "value": 0 } |
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)