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

Read Backtest

Insights

Introduction

Read out the insights of a backtest.

Request

Fetch the insights of a backtest for the project Id, backtest Id and steps provided. The /backtests/read/insights API accepts requests in the following format:

ReadBacktestInsightsRequest Model - Request to read insights from a backtest.
start integer
required
example: 0

Starting index of the insights to be fetched. Required if end > 100.
end integer
required
example: 100

Last index of the insights to be fetched. Note that end - start must be less than 100.
projectId integer
required
example: 23456789

Id of the project from which to read the backtest.
backtestId string
required
example: 26c7bb06b8487cff1c7b3c44652b30f1

Id of the backtest from which to read the insights.
Example
{
  "start": 0,
  "end": 100,
  "projectId": 23456789,
  "backtestId": "26c7bb06b8487cff1c7b3c44652b30f1"
}

Responses

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

200 Success

BacktestInsightsResponse Model - Contains insights and the number of insights of the backtest in the request criteria.
insights Insight Array
Collection of insights.
length integer
Total number of returned insights.
success boolean
Indicate if the API request was successful.
Example
{
  "insights": [
    {
      "id": "string",
      "groupId": "string",
      "sourceModel": "string",
      "generatedTime": "string",
      "createdTime": 0,
      "closeTime": 0,
      "symbol": "string",
      "ticker": "string",
      "type": "price",
      "reference": "string",
      "referenceValueFinal": "string",
      "direction": "down",
      "period": 0,
      "magnitude": 0,
      "confidence": 0,
      "weight": 0,
      "scoreIsFinal": true,
      "scoreDirection": 0,
      "scoreMagnitude": 0,
      "estimatedValue": 0,
      "tag": "2021-11-26T15:18:27.693Z"
    }
  ],
  "length": 0,
  "success": true
}
Insight Model - Insight struct for emitting new prediction.
id string
Insight ID.
groupId string
ID of the group of insights.
sourceModel string
Name of the model that sourced the insight.
generatedTime string
Gets the utc unixtime this insight was generated.
createdTime number
Gets the utc unixtime this insight was created.
closeTime number
Gets the utc unixtime this insight was closed.
symbol string
Gets the symbol ID this insight is for.
ticker string
Gets the symbol ticker this insight is for.
type string Enum
Gets the type of insight, for example, price or volatility. Options : ['price', 'volatility']
reference string
Gets the initial reference value this insight is predicting against.
referenceValueFinal string
Gets the final reference value, used for scoring, this insight is predicting against.
direction string Enum
Gets the predicted direction, down, flat or up. Options : ['down', 'flat', 'up']
period number
Gets the period, in seconds, over which this insight is expected to come to fruition.
magnitude number
Gets the predicted percent change in the insight type (price/volatility). This value can be null.
confidence number
Gets the confidence in this insight. This value can be null.
weight number
Gets the portfolio weight of this insight. This value can be null.
scoreIsFinal boolean
Gets whether or not this is the insight's final score.
scoreDirection number
Gets the direction score.
scoreMagnitude number
Gets the magnitude score.
estimatedValue number
Gets the estimated value of this insight in the account currency.
tag string($float)
The insight's tag containing additional information.
Example
{
  "id": "string",
  "groupId": "string",
  "sourceModel": "string",
  "generatedTime": "string",
  "createdTime": 0,
  "closeTime": 0,
  "symbol": "string",
  "ticker": "string",
  "type": "price",
  "reference": "string",
  "referenceValueFinal": "string",
  "direction": "down",
  "period": 0,
  "magnitude": 0,
  "confidence": 0,
  "weight": 0,
  "scoreIsFinal": true,
  "scoreDirection": 0,
  "scoreMagnitude": 0,
  "estimatedValue": 0,
  "tag": "2021-11-26T15:18:27.693Z"
}

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: