Read Backtest

Export Insights

Introduction

Download the insights of a backtest as a JSON file.

Description

The JSON file contains all the insights of the backtest. To read a page of insights, call the /backtests/read/insights endpoint. The response is a file download named after the backtest.

Request

Download the insights of the backtest Id provided. The /backtests/export/insights API accepts requests in the following format:

ExportBacktestInsightsRequest Model - Request to download the insights of a backtest.
backtestId string
required
example: 26c7bb06b8487cff1c7b3c44652b30f1

Id of the backtest from which to download the insights.
Example
{
  "backtestId": "26c7bb06b8487cff1c7b3c44652b30f1"
}

Responses

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

200 Success

BacktestInsightExportRow Model - Insight row of a backtest export.
id string
example: 4e9e6b461ef04756b6e6450b54953dea

Id of the insight.
groupId string
Id of the insight group.
sourceModel string
example: d1e4e8e4-a645-492c-bfb9-0006971e22b9

Id of the Alpha model that emitted the insight.
generatedTime integer
example: 1705093200

Unix time when the algorithm emitted the insight.
createdTime integer
example: 1705093200

Unix time when the insight was created.
closeTime integer
example: 1705438800

Unix time when the insight expires.
symbol string
example: SPY R735QTJ8XC9X

Id of the Symbol.
ticker string
example: SPY

Ticker of the Symbol.
type string Enum
Type of the insight. Options : ['price', 'volatility']
reference number
example: 461.57615586

Price of the Symbol when the algorithm emitted the insight.
referenceValueFinal number
Final reference value that scores the insight.
direction string Enum
Direction of the insight. Options : ['down', 'flat', 'up']
period integer
example: 86400

Period of the insight in seconds.
magnitude number
Predicted percent change of the insight type (price or volatility).
confidence number
Confidence of the insight.
weight number
Portfolio weight of the insight.
scoreIsFinal boolean
True if the scores are final.
scoreMagnitude string
example: 0

Magnitude score of the insight, as a decimal string.
scoreDirection string
example: 0

Direction score of the insight, as a decimal string.
estimatedValue string
example: 0

Estimated value of the insight in the account currency, as a decimal string.
tag string
Tag of the insight.
Example
[
  {
    "id": "4e9e6b461ef04756b6e6450b54953dea",
    "groupId": "string",
    "sourceModel": "d1e4e8e4-a645-492c-bfb9-0006971e22b9",
    "generatedTime": 1705093200,
    "createdTime": 1705093200,
    "closeTime": 1705438800,
    "symbol": "SPY R735QTJ8XC9X",
    "ticker": "SPY",
    "type": "price",
    "reference": 461.57615586,
    "referenceValueFinal": 0,
    "direction": "down",
    "period": 86400,
    "magnitude": 0,
    "confidence": 0,
    "weight": 0,
    "scoreIsFinal": true,
    "scoreMagnitude": "0",
    "scoreDirection": "0",
    "estimatedValue": "0",
    "tag": "string"
  }
]

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)

### Read Backtest Logs
# Prepare data payload to read the first 200 log lines
payload = {
    "projectId": project_id,  # ID of the project
    "backtestId": backtest_id,  # ID of the backtest to read
    "start": 0,  # Start line (inclusive)
    "end": 200,  # End line (exclusive), at most 200 lines per request
    "query": None  # Keyword to filter the lines, or None to read all of them
}
# Send a POST request to the /backtests/read/log endpoint to get the logs
response = post(f'{BASE_URL}/backtests/read/log', 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 logs
if result['success']:
    print("Backtest Logs:")
    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)

### Export Orders
# Download the orders of the backtest as a CSV file
payload = {
    "backtestId": backtest_id  # ID of the backtest
}
response = post(f'{BASE_URL}/backtests/export/orders', headers=get_headers(), json=payload)
with open(f'orders-{backtest_id}.csv', 'w', newline='') as file:
    file.write(response.text)

### Export Trades
# Download the closed trades of the backtest as a CSV file
payload = {
    "backtestId": backtest_id  # ID of the backtest
}
response = post(f'{BASE_URL}/backtests/export/trades', headers=get_headers(), json=payload)
with open(f'trades-{backtest_id}.csv', 'w', newline='') as file:
    file.write(response.text)

### Export Insights
# Download the insights of the backtest as a JSON file
payload = {
    "backtestId": backtest_id  # ID of the backtest
}
response = post(f'{BASE_URL}/backtests/export/insights', headers=get_headers(), json=payload)
with open(f'insights-{backtest_id}.json', 'w', newline='') as file:
    file.write(response.text)

### Export Logs
# Download the logs of the backtest as a text file
payload = {
    "projectId": project_id,  # ID of the project
    "backtestId": backtest_id  # ID of the backtest
}
response = post(f'{BASE_URL}/backtests/export/logs', headers=get_headers(), json=payload)
with open(f'logs-{backtest_id}.txt', 'w', newline='') as file:
    file.write(response.text)

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: