Compare commits

...

3 Commits
16632 ... 15681

Author SHA1 Message Date
Jhonathan Abreu
a6b758713e Add Python regression algorithm 2023-06-30 16:19:07 -04:00
Jhonathan Abreu
669327a83d Address peer review 2023-06-30 16:19:07 -04:00
Jhonathan Abreu
23d6869870 Add algorithm's mode and deployment target properties source from job packet 2023-06-30 16:19:07 -04:00
14 changed files with 411 additions and 11 deletions

View File

@@ -0,0 +1,111 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Algorithm asserting the correct values for the deployment target and algorithm mode.
/// </summary>
public class AlgorithmModeAndDeploymentTargetAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 07);
SetCash(100000);
Debug($"Algorithm Mode: {AlgorithmMode}. Is Live Mode: {LiveMode}. Deployment Target: {DeploymentTarget}.");
if (AlgorithmMode != AlgorithmMode.Backtesting)
{
throw new Exception($"Algorithm mode is not backtesting. Actual: {AlgorithmMode}");
}
if (LiveMode)
{
throw new Exception("Algorithm should not be live");
}
if (DeploymentTarget != DeploymentTarget.LocalPlatform)
{
throw new Exception($"Algorithm deployment target is not local. Actual{DeploymentTarget}");
}
// For a live deployment these checks should pass:
//if (AlgorithmMode != AlgorithmMode.Live) throw new Exception("Algorithm mode is not live");
//if (!LiveMode) throw new Exception("Algorithm should be live");
// For a cloud deployment these checks should pass:
//if (DeploymentTarget != DeploymentTarget.CloudPlatform) throw new Exception("Algorithm deployment target is not cloud");
Quit();
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 0;
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", ""},
{"Portfolio Turnover", "0%"},
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
};
}
}

View File

@@ -0,0 +1,44 @@
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from AlgorithmImports import *
### <summary>
### Algorithm asserting the correct values for the deployment target and algorithm mode.
### </summary>
class AlgorithmModeAndDeploymentTargetAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2013,10, 7)
self.SetEndDate(2013,10,11)
self.SetCash(100000)
#translate commented code from c# to python
self.Debug(f"Algorithm Mode: {self.AlgorithmMode}. Is Live Mode: {self.LiveMode}. Deployment Target: {self.DeploymentTarget}.")
if self.AlgorithmMode != AlgorithmMode.Backtesting:
raise Exception(f"Algorithm mode is not backtesting. Actual: {self.AlgorithmMode}")
if self.LiveMode:
raise Exception("Algorithm should not be live")
if self.DeploymentTarget != DeploymentTarget.LocalPlatform:
raise Exception(f"Algorithm deployment target is not local. Actual{self.DeploymentTarget}")
# For a live deployment these checks should pass:
# if self.AlgorithmMode != AlgorithmMode.Live: raise Exception("Algorithm mode is not live")
# if not self.LiveMode: raise Exception("Algorithm should be live")
# For a cloud deployment these checks should pass:
# if self.DeploymentTarget != DeploymentTarget.CloudPlatform: raise Exception("Algorithm deployment target is not cloud")
self.Quit()

View File

@@ -88,6 +88,8 @@ namespace QuantConnect.Algorithm
private DateTime _endDate; //Default end to yesterday
private bool _locked;
private bool _liveMode;
private AlgorithmMode _algorithmMode;
private DeploymentTarget _deploymentTarget;
private string _algorithmId = "";
private ConcurrentQueue<string> _debugMessages = new ConcurrentQueue<string>();
private ConcurrentQueue<string> _logMessages = new ConcurrentQueue<string>();
@@ -151,6 +153,12 @@ namespace QuantConnect.Algorithm
//Initialise End Date:
SetEndDate(DateTime.UtcNow.ConvertFromUtc(TimeZone));
// Set default algorithm mode as backtesting
_algorithmMode = AlgorithmMode.Backtesting;
// Set default deployment target as local
_deploymentTarget = DeploymentTarget.LocalPlatform;
_securityDefinitionSymbolResolver = SecurityDefinitionSymbolResolver.GetInstance();
Settings = new AlgorithmSettings();
@@ -533,6 +541,28 @@ namespace QuantConnect.Algorithm
}
}
/// <summary>
/// Algorithm running mode.
/// </summary>
public AlgorithmMode AlgorithmMode
{
get
{
return _algorithmMode;
}
}
/// <summary>
/// Deployment target, either local or cloud.
/// </summary>
public DeploymentTarget DeploymentTarget
{
get
{
return _deploymentTarget;
}
}
/// <summary>
/// Storage for debugging messages before the event handler has passed control back to the Lean Engine.
/// </summary>
@@ -1620,10 +1650,36 @@ namespace QuantConnect.Algorithm
if (live)
{
SetLiveModeStartDate();
_algorithmMode = AlgorithmMode.Live;
}
}
}
/// <summary>
/// Sets the algorithm running mode
/// </summary>
/// <param name="algorithmMode">Algorithm mode</param>
public void SetAlgorithmMode(AlgorithmMode algorithmMode)
{
if (!_locked)
{
_algorithmMode = algorithmMode;
SetLiveMode(_algorithmMode == AlgorithmMode.Live);
}
}
/// <summary>
/// Sets the algorithm deployment target
/// </summary>
/// <param name="deploymentTarget">Deployment target</param>
public void SetDeploymentTarget(DeploymentTarget deploymentTarget)
{
if (!_locked)
{
_deploymentTarget = deploymentTarget;
}
}
/// <summary>
/// Set the <see cref="ITradeBuilder"/> implementation to generate trades from executions and market price updates
/// </summary>

View File

@@ -228,6 +228,16 @@ namespace QuantConnect.AlgorithmFactory.Python.Wrappers
/// </summary>
public bool LiveMode => _baseAlgorithm.LiveMode;
/// <summary>
/// Algorithm running mode.
/// </summary>
public AlgorithmMode AlgorithmMode => _baseAlgorithm.AlgorithmMode;
/// <summary>
/// Deployment target, either local or cloud.
/// </summary>
public DeploymentTarget DeploymentTarget => _baseAlgorithm.DeploymentTarget;
/// <summary>
/// Log messages from the strategy:
/// </summary>
@@ -998,6 +1008,18 @@ namespace QuantConnect.AlgorithmFactory.Python.Wrappers
/// <param name="live">Bool live mode flag</param>
public void SetLiveMode(bool live) => _baseAlgorithm.SetLiveMode(live);
/// <summary>
/// Sets the algorithm running mode
/// </summary>
/// <param name="algorithmMode">Algorithm mode</param>
public void SetAlgorithmMode(AlgorithmMode algorithmMode) => _baseAlgorithm.SetAlgorithmMode(algorithmMode);
/// <summary>
/// Sets the algorithm deployment target
/// </summary>
/// <param name="deploymentTarget">Deployment target</param>
public void SetDeploymentTarget(DeploymentTarget deploymentTarget) => _baseAlgorithm.SetDeploymentTarget(deploymentTarget);
/// <summary>
/// Set the algorithm as initialized and locked. No more cash or security changes.
/// </summary>

View File

@@ -20,7 +20,6 @@ using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using static QuantConnect.StringExtensions;
namespace QuantConnect
{
@@ -1221,4 +1220,48 @@ namespace QuantConnect
new DateTime(2023, 12, 25)
};
}
/// <summary>
/// Represents the types deployment targets for algorithms
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum DeploymentTarget
{
/// <summary>
/// Cloud Platform (0)
/// </summary>
CloudPlatform,
/// <summary>
/// Local Platform (1)
/// </summary>
LocalPlatform
}
/// <summary>
/// Represents the deployment modes of an algorithm
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum AlgorithmMode
{
/// <summary>
/// Live (0)
/// </summary>
Live,
/// <summary>
/// Optimization (1)
/// </summary>
Optimization,
/// <summary>
/// Backtesting (2)
/// </summary>
Backtesting,
/// <summary>
/// Research (1)
/// </summary>
Research
}
}

View File

@@ -250,6 +250,22 @@ namespace QuantConnect.Interfaces
get;
}
/// <summary>
/// Algorithm running mode.
/// </summary>
AlgorithmMode AlgorithmMode
{
get;
}
/// <summary>
/// Deployment target, either local or cloud.
/// </summary>
DeploymentTarget DeploymentTarget
{
get;
}
/// <summary>
/// Gets the subscription settings to be used when adding securities via universe selection
/// </summary>
@@ -706,6 +722,18 @@ namespace QuantConnect.Interfaces
/// <param name="live">Bool live mode flag</param>
void SetLiveMode(bool live);
/// <summary>
/// Sets the algorithm running mode
/// </summary>
/// <param name="algorithmMode">Algorithm mode</param>
void SetAlgorithmMode(AlgorithmMode algorithmMode);
/// <summary>
/// Sets the algorithm deployment target
/// </summary>
/// <param name="deploymentTarget">Deployment target</param>
void SetDeploymentTarget(DeploymentTarget deploymentTarget);
/// <summary>
/// Sets <see cref="IsWarmingUp"/> to false to indicate this algorithm has finished its warm up
/// </summary>

View File

@@ -156,6 +156,18 @@ namespace QuantConnect.Packets
[JsonProperty(PropertyName = "sHistoryProvider")]
public string HistoryProvider = "";
/// <summary>
/// Algorithm running mode.
/// </summary>
[JsonIgnore]
public virtual AlgorithmMode AlgorithmMode { get; } = AlgorithmMode.Backtesting;
/// <summary>
/// Deployment target, either local or cloud.
/// </summary>
[JsonIgnore]
public DeploymentTarget DeploymentTarget;
/// <summary>
/// Gets a unique name for the algorithm defined by this packet
/// </summary>

View File

@@ -1,11 +1,11 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -15,10 +15,10 @@
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using QuantConnect.Securities;
using QuantConnect.Util;
namespace QuantConnect.Packets
{
@@ -78,6 +78,18 @@ namespace QuantConnect.Packets
/// </summary>
public CashAmount? CashAmount;
/// <summary>
/// Algorithm running mode.
/// </summary>
[JsonIgnore]
public override AlgorithmMode AlgorithmMode
{
get
{
return OptimizationId.IsNullOrEmpty() ? AlgorithmMode.Backtesting : AlgorithmMode.Optimization;
}
}
/// <summary>
/// Default constructor for JSON
/// </summary>

View File

@@ -1,4 +1,4 @@
/*
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
@@ -79,6 +79,18 @@ namespace QuantConnect.Packets
[JsonProperty(PropertyName = "aLiveDataTypes")]
public HashSet<string> LiveDataTypes;
/// <summary>
/// Algorithm running mode.
/// </summary>
[JsonIgnore]
public override AlgorithmMode AlgorithmMode
{
get
{
return AlgorithmMode.Live;
}
}
/// <summary>
/// Default constructor for JSON of the Live Task Packet
/// </summary>

View File

@@ -163,7 +163,8 @@ namespace QuantConnect.Lean.Engine.Setup
algorithm.SetAvailableDataTypes(BaseSetupHandler.GetConfiguredDataFeeds());
//Algorithm is backtesting, not live:
algorithm.SetLiveMode(false);
algorithm.SetAlgorithmMode(job.AlgorithmMode);
algorithm.SetDeploymentTarget(job.DeploymentTarget);
//Set the source impl for the event scheduling
algorithm.Schedule.SetEventSchedule(parameters.RealTimeHandler);

View File

@@ -243,7 +243,8 @@ namespace QuantConnect.Lean.Engine.Setup
algorithm.SetAvailableDataTypes(BaseSetupHandler.GetConfiguredDataFeeds());
//Algorithm is live, not backtesting:
algorithm.SetLiveMode(true);
algorithm.SetAlgorithmMode(liveJob.AlgorithmMode);
algorithm.SetDeploymentTarget(liveJob.DeploymentTarget);
//Initialize the algorithm's starting date
algorithm.SetDateTime(DateTime.UtcNow);

View File

@@ -148,7 +148,8 @@ namespace QuantConnect.Queues
Parameters = parameters,
Language = Language,
Controls = controls,
PythonVirtualEnvironment = Config.Get("python-venv")
PythonVirtualEnvironment = Config.Get("python-venv"),
DeploymentTarget = DeploymentTarget.LocalPlatform,
};
Type brokerageName = null;
@@ -214,7 +215,8 @@ namespace QuantConnect.Queues
Language = Language,
Parameters = parameters,
Controls = controls,
PythonVirtualEnvironment = Config.Get("python-venv")
PythonVirtualEnvironment = Config.Get("python-venv"),
DeploymentTarget = DeploymentTarget.LocalPlatform,
};
// Only set optimization id when backtest is for optimization
if (!optimizationId.IsNullOrEmpty())

View File

@@ -193,6 +193,9 @@ namespace QuantConnect.Research
SetOptionChainProvider(new CachingOptionChainProvider(new BacktestingOptionChainProvider(_dataCacheProvider, mapFileProvider)));
SetFutureChainProvider(new CachingFutureChainProvider(new BacktestingFutureChainProvider(_dataCacheProvider)));
SetAlgorithmMode(AlgorithmMode.Research);
SetDeploymentTarget(Config.GetValue("deployment-target", DeploymentTarget.LocalPlatform));
}
catch (Exception exception)
{

View File

@@ -0,0 +1,53 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NUnit.Framework;
using QuantConnect.Research;
using QuantConnect.Configuration;
using Newtonsoft.Json.Linq;
namespace QuantConnect.Tests.Research
{
[TestFixture]
public class QuantBookTests
{
[Test]
public void AlgorithmModeIsResearch()
{
var qb = new QuantBook();
Assert.AreEqual(AlgorithmMode.Research, qb.AlgorithmMode);
}
[TestCase(DeploymentTarget.CloudPlatform)]
[TestCase(DeploymentTarget.LocalPlatform)]
[TestCase(null)]
public void SetsDeploymentTarget(DeploymentTarget? deploymentTarget)
{
if (deploymentTarget.HasValue)
{
Config.Set("deployment-target", JToken.FromObject(deploymentTarget));
}
else
{
// The default value for deploymentTarget = DeploymentTarget.LocalPlatform
deploymentTarget = DeploymentTarget.LocalPlatform;
}
var qb = new QuantBook();
Assert.AreEqual(deploymentTarget, qb.DeploymentTarget);
}
}
}