Optimization Management

Read Optimization

Introduction

Read an optimization.

Request

Id of the optimization to read. The /optimizations/read API accepts requests in the following format:

ReadOptimizationRequest Model - Request to read an optimization from a project.
optimizationId string
required

Id of the optimization to read.
Example
{
  "optimizationId": "string"
}

Responses

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

200 Success

ReadOptimizationResponse Model - Response received when reading an optimization.
optimization Optimization object
Response received when reading an optimization job.
success boolean
Indicate if the API request was successful.
errors string Array
List of errors with the API call.
Example
{
  "optimization": {
    "optimizationId": "string",
    "snapshotId": 0,
    "projectId": 0,
    "name": "string",
    "status": ,
    "nodeType": "O2-8",
    "parallelNodes": 0,
    "criterion": {
      "target": "TotalPerformance.PortfolioStatistics.SharpeRatio",
      "extremum": "min",
      "targetValue": 0
    },
    "runtimeStatistics": {
      "Completed": "string",
      "Failed": "string",
      "Running": "string",
      "In Queue": "string",
      "Average Length": "2021-11-26T15:18:27.693Z",
      "Total Runtime": "2021-11-26T15:18:27.693Z",
      "Total": "string",
      "Consumed": "string"
    },
    "constraints": [
      {
        "target": "TotalPerformance.PortfolioStatistics.SharpeRatio",
        "operator": "LessOrEqual",
        "targetValue": 0
      }
    ],
    "parameters": [
      {
        "name": "string",
        "min": 0,
        "max": 0,
        "step": 0,
        "minStep": 0
      }
    ],
    "backtests": {
      "name": "string",
      "id": "string",
      "progress": 0,
      "exitCode": 0,
      "statistics": [
        "number"
      ],
      "parameterSet": ,
      "equity": [
        "array"
      ],
      "startDate": "2021-11-26T15:18:27.693Z",
      "endDate": "2021-11-26T15:18:27.693Z",
      "outOfSampleDays": 0,
      "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z"
    },
    "strategy": "QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy",
    "requested": "2021-11-26T15:18:27.693Z",
    "optimizationTarget": "TotalPerformance.PortfolioStatistics.SharpeRatio",
    "targetValue": 0,
    "gridLayout": [
      {
        "chartName": "string",
        "width": 0,
        "height": 0,
        "row": 0,
        "column": 0,
        "sort": 0
      }
    ],
    "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z",
    "outOfSampleDays": 0
  },
  "success": true,
  "errors": [
    "string"
  ]
}
Optimization Model - Response received when reading an optimization job.
optimizationId string
Id of the optimization.
snapshotId integer
Snapshot Id of this optimization.
projectId integer
required

Id of the project the optimization belongs to.
name string
Name of the optimization.
status OptimizationStatus object
Status of the optimization.
nodeType string Enum
Optimization node types available in QuantConnect Cloud. Options : ['O2-8', 'O4-12', 'O8-16']
parallelNodes integer
Number of parallel nodes for the optimization.
criterion OptimizationTarget object
/.
runtimeStatistics OptimizationRuntimeStatistics object
/.
constraints OptimizationConstraint Array
Optimization constraints.
parameters OptimizationParameter Array
Optimization parameters.
backtests OptimizationBacktest object
Dictionary of optimization backtests.
strategy string Enum
/. Options : ['QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy']
requested string($date-time)
Optimization requested date and time.
optimizationTarget string Enum
/. Options : ['TotalPerformance.PortfolioStatistics.SharpeRatio', 'TotalPerformance.PortfolioStatistics.CompoundingAnnualReturn', 'TotalPerformance.PortfolioStatistics.ProbabilisticSharpeRatio', 'TotalPerformance.PortfolioStatistics.Drawdown']
targetValue number
Desired value for the optimization target statistic.
gridLayout GridChart Array
List with grid charts representing the grid layout.
outOfSampleMaxEndDate string($date-time)
End date of out of sample data.
outOfSampleDays integer
Number of days of out of sample days.
Example
{
  "optimizationId": "string",
  "snapshotId": 0,
  "projectId": 0,
  "name": "string",
  "status": ,
  "nodeType": "O2-8",
  "parallelNodes": 0,
  "criterion": {
    "target": "TotalPerformance.PortfolioStatistics.SharpeRatio",
    "extremum": "min",
    "targetValue": 0
  },
  "runtimeStatistics": {
    "Completed": "string",
    "Failed": "string",
    "Running": "string",
    "In Queue": "string",
    "Average Length": "2021-11-26T15:18:27.693Z",
    "Total Runtime": "2021-11-26T15:18:27.693Z",
    "Total": "string",
    "Consumed": "string"
  },
  "constraints": [
    {
      "target": "TotalPerformance.PortfolioStatistics.SharpeRatio",
      "operator": "LessOrEqual",
      "targetValue": 0
    }
  ],
  "parameters": [
    {
      "name": "string",
      "min": 0,
      "max": 0,
      "step": 0,
      "minStep": 0
    }
  ],
  "backtests": {
    "name": "string",
    "id": "string",
    "progress": 0,
    "exitCode": 0,
    "statistics": [
      "number"
    ],
    "parameterSet": ,
    "equity": [
      "array"
    ],
    "startDate": "2021-11-26T15:18:27.693Z",
    "endDate": "2021-11-26T15:18:27.693Z",
    "outOfSampleDays": 0,
    "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z"
  },
  "strategy": "QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy",
  "requested": "2021-11-26T15:18:27.693Z",
  "optimizationTarget": "TotalPerformance.PortfolioStatistics.SharpeRatio",
  "targetValue": 0,
  "gridLayout": [
    {
      "chartName": "string",
      "width": 0,
      "height": 0,
      "row": 0,
      "column": 0,
      "sort": 0
    }
  ],
  "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z",
  "outOfSampleDays": 0
}
OptimizationStatus Model - Status of the optimization job.
OptimizationNodeType Model - Optimization node types available in QuantConnect Cloud.
OptimizationNodeType string Enum
Optimization node types available in QuantConnect Cloud. Options : ['O2-8', 'O4-12', 'O8-16']
Example
{
  "OptimizationNodeType": "O2-8"
}
OptimizationTarget Model
target string Enum
/. Options : ['TotalPerformance.PortfolioStatistics.SharpeRatio', 'TotalPerformance.PortfolioStatistics.CompoundingAnnualReturn', 'TotalPerformance.PortfolioStatistics.ProbabilisticSharpeRatio', 'TotalPerformance.PortfolioStatistics.Drawdown']
extremum string Enum
/. Options : ['min', 'max']
targetValue number
Desired value for the optimization target statistic.
Example
{
  "target": "TotalPerformance.PortfolioStatistics.SharpeRatio",
  "extremum": "min",
  "targetValue": 0
}
OptimizationTargetStatistic Model
OptimizationTargetStatistic string Enum
/. Options : ['TotalPerformance.PortfolioStatistics.SharpeRatio', 'TotalPerformance.PortfolioStatistics.CompoundingAnnualReturn', 'TotalPerformance.PortfolioStatistics.ProbabilisticSharpeRatio', 'TotalPerformance.PortfolioStatistics.Drawdown']
Example
{
  "OptimizationTargetStatistic": "TotalPerformance.PortfolioStatistics.SharpeRatio"
}
OptimizationTargetTo Model
OptimizationTargetTo string Enum
/. Options : ['min', 'max']
Example
{
  "OptimizationTargetTo": "min"
}
OptimizationRuntimeStatistics Model
Completed string
Number of completed backtests in the optimization job.
Failed string
Number of failed backtests in the optimization job.
Running string
Number of running backtests in the optimization job.
In Queue string
Number of backtests waiting in-queue in the optimization job.
Average Length string($time)
The average time of each backtest in the optimization job (HH:MM:SS).
Total Runtime string($time)
The total runtime of the optimization (HH:MM:SS).
Total string
Number of backtests in the optimization job.
Consumed string
Amount of QuantConnect Credit consumed by the optimization job.
Example
{
  "Completed": "string",
  "Failed": "string",
  "Running": "string",
  "In Queue": "string",
  "Average Length": "2021-11-26T15:18:27.693Z",
  "Total Runtime": "2021-11-26T15:18:27.693Z",
  "Total": "string",
  "Consumed": "string"
}
OptimizationConstraint Model - Backtests in the optimization job that don't respect this constraint are excluded from the optimization result.
target string Enum
/. Options : ['TotalPerformance.PortfolioStatistics.SharpeRatio', 'TotalPerformance.PortfolioStatistics.CompoundingAnnualReturn', 'TotalPerformance.PortfolioStatistics.ProbabilisticSharpeRatio', 'TotalPerformance.PortfolioStatistics.Drawdown']
operator string Enum
required

The target comparison operation. Options : ['LessOrEqual', 'Less', 'GreaterOrEqual', 'Greater', 'NotEqual', 'Equals']
targetValue number
required

The threshold value for the target constraint.
Example
{
  "target": "TotalPerformance.PortfolioStatistics.SharpeRatio",
  "operator": "LessOrEqual",
  "targetValue": 0
}
OptimizationParameter Model
name string
required

Name of optimization parameter.
min number
required

Minimum value of optimization parameter, applicable for boundary conditions.
max number
required

Maximum value of optimization parameter, applicable for boundary conditions.
step number
required

Movement, should be positive.
minStep number
Minimal possible movement for current parameter, should be positive. Used by Strategies.EulerSearchOptimizationStrategy to determine when this parameter can no longer be optimized.
Example
{
  "name": "string",
  "min": 0,
  "max": 0,
  "step": 0,
  "minStep": 0
}
OptimizationBacktest Model
name string
The backtest name.
id string
Id of the backtest.
progress number
Progress of the backtest as a percentage from 0-1 based on the days lapsed from start-finish.
exitCode integer
The exit code of this backtest.
statistics number Array
The backtest statistics results. [alpha, annual standard deviation, annual variance, average loss (%), average win (%), beta, compounding annual return (%), drawdown (%), estimated strategy capacity, expectancy, information ratio, loss rate (%), net profit (%), probabilistic sharpe ratio, profit-loss ratio, sharpe ratio, total fees, total orders, tracking error, treynor ratio, win rate (%)].
parameterSet ParameterSet object
Parameters used in the backtest.
equity array Array
The backtest equity chart series.
startDate string($date-time)
The backtest start date.
endDate string($date-time)
The backtest end date.
outOfSampleDays integer
The backtest out-of-sample day count.
outOfSampleMaxEndDate string($date-time)
End date of out-of-sample data.
Example
{
  "name": "string",
  "id": "string",
  "progress": 0,
  "exitCode": 0,
  "statistics": [
    "number"
  ],
  "parameterSet": ,
  "equity": [
    "array"
  ],
  "startDate": "2021-11-26T15:18:27.693Z",
  "endDate": "2021-11-26T15:18:27.693Z",
  "outOfSampleDays": 0,
  "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z"
}
OptimizationStrategy Model
OptimizationStrategy string Enum
/. Options : ['QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy']
Example
{
  "OptimizationStrategy": "QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy"
}
GridChart Model - The chart display properties.
chartName string
The chart name.
width integer
Width of the chart.
height integer
Height of the chart.
row integer
Number of rows of the chart.
column integer
Number of columns of the chart.
sort integer
Sort of the chart.
Example
{
  "chartName": "string",
  "width": 0,
  "height": 0,
  "row": 0,
  "column": 0,
  "sort": 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, aborting 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())

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


# The project ID of the project to manage an optimization job
project_id = 12345678

### Estimate Optimization Cost
# Send a POST request to the /optimizations/estimate endpoint to estimate cost
response = post(f'{BASE_URL}/optimizations/estimate', headers=get_headers(), json={
    "projectId": project_id,  # ID of the project
    "name": f"Optimization_{compileId[:5]}",  # Name of the optimization (using compile ID prefix)
    "target": "TotalPerformance.PortfolioStatistics.SharpeRatio",  # Optimization target metric
    "targetTo": "max",  # Direction to optimize (maximize)
    "targetValue": None,  # Specific target value (None for max/min)
    "strategy": "QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy",  # Optimization strategy
    "compileId": compile_id,  # Compilation ID for the optimization
    "parameters[0][key]": "ema_fast",  # First parameter key
    "parameters[0][min]": 100,  # Minimum value for first parameter
    "parameters[0][max]": 200,  # Maximum value for first parameter
    "parameters[0][step]": 50,  # Step size for first parameter
    "parameters[1][key]": "ema_slow",  # Second parameter key
    "parameters[1][min]": 200,  # Minimum value for second parameter
    "parameters[1][max]": 300,  # Maximum value for second parameter
    "parameters[1][step]": 50,  # Step size for second parameter
    "constraints": [{  # Constraints for the optimization
        "target": "TotalPerformance.PortfolioStatistics.SharpeRatio",
        "operator": "greater",
        "target-value": 1
    }]
})
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the estimated cost
if result['success']:
    print("Optimization Cost Estimated Successfully:")
    print(result)

### Create Optimization
# Send a POST request to the /optimizations/create endpoint to create an optimization
response = post(f'{BASE_URL}/optimizations/create', headers=get_headers(), json={
    "projectId": project_id,  # ID of the project
    "name": f"Optimization_{compileId[:5]}",  # Name of the optimization
    "target": "TotalPerformance.PortfolioStatistics.SharpeRatio",  # Optimization target
    "targetTo": "max",  # Direction to optimize
    "targetValue": None,  # Specific target value
    "strategy": "QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy",  # Strategy
    "compileId": compile_id,  # Compilation ID
    "parameters[0][key]": "ema_fast",  # First parameter key
    "parameters[0][min]": 100,  # Minimum value
    "parameters[0][max]": 200,  # Maximum value
    "parameters[0][step]": 50,  # Step size
    "parameters[1][key]": "ema_slow",  # Second parameter key
    "parameters[1][min]": 200,  # Minimum value
    "parameters[1][max]": 300,  # Maximum value
    "parameters[1][step]": 50,  # Step size
    "constraints": [{  # Constraints
        "target": "TotalPerformance.PortfolioStatistics.SharpeRatio",
        "operator": "greater",
        "target-value": 1
    }],
    "estimatedCost": 10,  # Estimated cost of optimization
    "nodeType": "O2-8",  # Node type for optimization
    "parallelNodes": 4  # Number of parallel nodes
})
# Parse the JSON response into python managable dict
result = response.json()
# Extract the optimization ID from the response
optimization_id = result['optimizations'][0]['optimizationId']
# Check if the request was successful and print the result
if result['success']:
    print("Optimization Created Successfully:")
    print(result)

### Update Optimization
# Send a POST request to the /optimizations/update endpoint to update the optimization
response = post(f'{BASE_URL}/optimizations/update', headers=get_headers(), json={
    "optimizationId": optimization_id,  # ID of the optimization to update
    "name": f"Optimization_{optimizationId[:5]}"  # New name for the optimization
})
# 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("Optimization Updated Successfully:")
    print(result)

### Read Optimization
# Prepare data payload to read optimization details
payload = {
    "optimizationId": optimization_id  # ID of the optimization to read
}
# Send a POST request to the /optimizations/read endpoint to get details
response = post(f'{BASE_URL}/optimizations/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 details
if result['success']:
    print("Optimization Details:")
    print(result)

### Abort Optimization
# Prepare data payload to abort the optimization
payload = {
    "optimizationId": optimization_id  # ID of the optimization to abort
}
# Send a POST request to the /optimizations/abort endpoint to abort
response = post(f'{BASE_URL}/optimizations/abort', 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("Optimization Aborted Successfully:")
    print(result)

### Delete Optimization
# Prepare data payload to delete the optimization
payload = {
    "optimizationId": optimization_id  # ID of the optimization to delete
}
# Send a POST request to the /optimizations/delete endpoint to delete
response = post(f'{BASE_URL}/optimizations/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("Optimization Deleted Successfully:")
    print(result)

### List Optimizations
# Prepare data payload to list optimizations
payload = {
    "projectId": project_id  # ID of the project
}
# Send a POST request to the /optimizations/list endpoint to list optimizations
response = post(f'{BASE_URL}/optimizations/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 Optimizations:")
    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: