chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
/*
|
||||
* 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 System.Linq;
|
||||
using Python.Runtime;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Util;
|
||||
|
||||
namespace QuantConnect.Algorithm.Framework.Risk
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides an implementation of <see cref="IRiskManagementModel"/> that combines multiple risk
|
||||
/// models into a single risk management model and properly sets each insights 'SourceModel' property.
|
||||
/// </summary>
|
||||
public class CompositeRiskManagementModel : RiskManagementModel
|
||||
{
|
||||
private readonly List<IRiskManagementModel> _riskManagementModels = new List<IRiskManagementModel>();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CompositeRiskManagementModel"/> class
|
||||
/// </summary>
|
||||
/// <param name="riskManagementModels">The individual risk management models defining this composite model</param>
|
||||
public CompositeRiskManagementModel(params IRiskManagementModel[] riskManagementModels)
|
||||
{
|
||||
if (riskManagementModels.IsNullOrEmpty())
|
||||
{
|
||||
throw new ArgumentException("Must specify at least 1 risk management model for the CompositeRiskManagementModel");
|
||||
}
|
||||
|
||||
_riskManagementModels.AddRange(riskManagementModels);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CompositeRiskManagementModel"/> class
|
||||
/// </summary>
|
||||
/// <param name="riskManagementModels">The individual risk management models defining this composite model</param>
|
||||
public CompositeRiskManagementModel(IEnumerable<IRiskManagementModel> riskManagementModels)
|
||||
{
|
||||
foreach (var riskManagementModel in riskManagementModels)
|
||||
{
|
||||
AddRiskManagement(riskManagementModel);
|
||||
}
|
||||
|
||||
if (_riskManagementModels.IsNullOrEmpty())
|
||||
{
|
||||
throw new ArgumentException("Must specify at least 1 risk management model for the CompositeRiskManagementModel");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CompositeRiskManagementModel"/> class
|
||||
/// </summary>
|
||||
/// <param name="riskManagementModels">The individual risk management models defining this composite model</param>
|
||||
public CompositeRiskManagementModel(params PyObject[] riskManagementModels)
|
||||
{
|
||||
if (riskManagementModels.IsNullOrEmpty())
|
||||
{
|
||||
throw new ArgumentException("Must specify at least 1 risk management model for the CompositeRiskManagementModel");
|
||||
}
|
||||
|
||||
foreach (var pyRiskManagementModel in riskManagementModels)
|
||||
{
|
||||
AddRiskManagement(pyRiskManagementModel);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Manages the algorithm's risk at each time step.
|
||||
/// This method patches this call through the each of the wrapped models.
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance</param>
|
||||
/// <param name="targets">The current portfolio targets to be assessed for risk</param>
|
||||
/// <returns>The new portfolio targets</returns>
|
||||
public override IEnumerable<IPortfolioTarget> ManageRisk(QCAlgorithm algorithm, IPortfolioTarget[] targets)
|
||||
{
|
||||
foreach (var model in _riskManagementModels)
|
||||
{
|
||||
// take into account the possibility of ManageRisk returning nothing
|
||||
var riskAdjusted = model.ManageRisk(algorithm, targets);
|
||||
|
||||
// produce a distinct set of new targets giving preference to newer targets
|
||||
targets = riskAdjusted.Concat(targets).DistinctBy(t => t.Symbol).ToArray();
|
||||
}
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event fired each time the we add/remove securities from the data feed.
|
||||
/// This method patches this call through the each of the wrapped models.
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
|
||||
/// <param name="changes">The security additions and removals from the algorithm</param>
|
||||
public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
|
||||
{
|
||||
foreach (var model in _riskManagementModels)
|
||||
{
|
||||
model.OnSecuritiesChanged(algorithm, changes);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new <see cref="IRiskManagementModel"/> instance
|
||||
/// </summary>
|
||||
/// <param name="riskManagementModel">The risk management model to add</param>
|
||||
public void AddRiskManagement(IRiskManagementModel riskManagementModel)
|
||||
{
|
||||
_riskManagementModels.Add(riskManagementModel);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new <see cref="IRiskManagementModel"/> instance
|
||||
/// </summary>
|
||||
/// <param name="pyRiskManagementModel">The risk management model to add</param>
|
||||
public void AddRiskManagement(PyObject pyRiskManagementModel)
|
||||
{
|
||||
var riskManagementModel = PythonUtil.CreateInstanceOrWrapper<IRiskManagementModel>(
|
||||
pyRiskManagementModel,
|
||||
py => new RiskManagementModelPythonWrapper(py)
|
||||
);
|
||||
_riskManagementModels.Add(riskManagementModel);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
# 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 *
|
||||
|
||||
class CompositeRiskManagementModel(RiskManagementModel):
|
||||
'''Provides an implementation of IRiskManagementModel that combines multiple risk models
|
||||
into a single risk management model and properly sets each insights 'SourceModel' property.'''
|
||||
|
||||
def __init__(self, *risk_management_models):
|
||||
'''Initializes a new instance of the CompositeRiskManagementModel class
|
||||
Args:
|
||||
risk_management_models: The individual risk management models defining this composite model.'''
|
||||
for model in risk_management_models:
|
||||
for attribute_names in [('ManageRisk', 'manage_risk'), ('OnSecuritiesChanged', 'on_securities_changed')]:
|
||||
if not hasattr(model, attribute_names[0]) and not hasattr(model, attribute_names[1]):
|
||||
raise Exception(f'IRiskManagementModel.{attribute_names[1]} must be implemented. Please implement this missing method on {model.__class__.__name__}')
|
||||
|
||||
self.risk_management_models = risk_management_models
|
||||
|
||||
def manage_risk(self, algorithm, targets):
|
||||
'''Manages the algorithm's risk at each time step
|
||||
Args:
|
||||
algorithm: The algorithm instance
|
||||
targets: The current portfolio targets to be assessed for risk'''
|
||||
for model in self.risk_management_models:
|
||||
# take into account the possibility of ManageRisk returning nothing
|
||||
risk_adjusted = model.manage_risk(algorithm, targets)
|
||||
|
||||
# produce a distinct set of new targets giving preference to newer targets
|
||||
symbols = [x.symbol for x in risk_adjusted]
|
||||
for target in targets:
|
||||
if target.symbol not in symbols:
|
||||
risk_adjusted.append(target)
|
||||
|
||||
targets = risk_adjusted
|
||||
|
||||
return targets
|
||||
|
||||
def on_securities_changed(self, algorithm, changes):
|
||||
'''Event fired each time the we add/remove securities from the data feed.
|
||||
This method patches this call through the each of the wrapped models.
|
||||
Args:
|
||||
algorithm: The algorithm instance that experienced the change in securities
|
||||
changes: The security additions and removals from the algorithm'''
|
||||
for model in self.risk_management_models:
|
||||
model.on_securities_changed(algorithm, changes)
|
||||
|
||||
def add_risk_management(self, risk_management_model):
|
||||
'''Adds a new 'IRiskManagementModel' instance
|
||||
Args:
|
||||
risk_management_model: The risk management model to add'''
|
||||
self.risk_management_models.add(risk_management_model)
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* 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.Collections.Generic;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
|
||||
namespace QuantConnect.Algorithm.Framework.Risk
|
||||
{
|
||||
/// <summary>
|
||||
/// Algorithm framework model that manages an algorithm's risk/downside
|
||||
/// </summary>
|
||||
public interface IRiskManagementModel : INotifiedSecurityChanges
|
||||
{
|
||||
/// <summary>
|
||||
/// Manages the algorithm's risk at each time step
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance</param>
|
||||
/// <param name="targets">The current portfolio targets to be assessed for risk</param>
|
||||
IEnumerable<IPortfolioTarget> ManageRisk(QCAlgorithm algorithm, IPortfolioTarget[] targets);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
|
||||
namespace QuantConnect.Algorithm.Framework.Risk
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides an implementation of <see cref="IRiskManagementModel"/> that does nothing
|
||||
/// </summary>
|
||||
public class NullRiskManagementModel : RiskManagementModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Manages the algorithm's risk at each time step
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance</param>
|
||||
/// <param name="targets">The current portfolio targets to be assessed for risk</param>
|
||||
public override IEnumerable<IPortfolioTarget> ManageRisk(QCAlgorithm algorithm, IPortfolioTarget[] targets)
|
||||
{
|
||||
return Enumerable.Empty<IPortfolioTarget>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
# 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 *
|
||||
|
||||
class NullRiskManagementModel(RiskManagementModel):
|
||||
'''Provides an implementation of IRiskManagementModel that does nothing'''
|
||||
def manage_risk(self, algorithm, targets):
|
||||
return []
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* 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.Collections.Generic;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
|
||||
namespace QuantConnect.Algorithm.Framework.Risk
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides a base class for risk management models
|
||||
/// </summary>
|
||||
public class RiskManagementModel : IRiskManagementModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Manages the algorithm's risk at each time step
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance</param>
|
||||
/// <param name="targets">The current portfolio targets to be assessed for risk</param>
|
||||
public virtual IEnumerable<IPortfolioTarget> ManageRisk(QCAlgorithm algorithm, IPortfolioTarget[] targets)
|
||||
{
|
||||
throw new System.NotImplementedException("Types deriving from 'RiskManagementModel' must implement the 'IEnumerable<IPortfolioTarget> ManageRisk(QCAlgorithm, IPortfolioTarget[]) method.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event fired each time the we add/remove securities from the data feed
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
|
||||
/// <param name="changes">The security additions and removals from the algorithm</param>
|
||||
public virtual void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* 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 Python.Runtime;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Python;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
|
||||
namespace QuantConnect.Algorithm.Framework.Risk
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides an implementation of <see cref="IRiskManagementModel"/> that wraps a <see cref="PyObject"/> object
|
||||
/// </summary>
|
||||
public class RiskManagementModelPythonWrapper : RiskManagementModel
|
||||
{
|
||||
private readonly BasePythonWrapper<IRiskManagementModel> _model;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for initialising the <see cref="IRiskManagementModel"/> class with wrapped <see cref="PyObject"/> object
|
||||
/// </summary>
|
||||
/// <param name="model">Model defining how risk is managed</param>
|
||||
public RiskManagementModelPythonWrapper(PyObject model)
|
||||
{
|
||||
_model = new BasePythonWrapper<IRiskManagementModel>(model);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Manages the algorithm's risk at each time step
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance</param>
|
||||
/// <param name="targets">The current portfolio targets to be assessed for risk</param>
|
||||
public override IEnumerable<IPortfolioTarget> ManageRisk(QCAlgorithm algorithm, IPortfolioTarget[] targets)
|
||||
{
|
||||
return _model.InvokeMethodAndEnumerate<IPortfolioTarget>(nameof(ManageRisk), algorithm, targets);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event fired each time the we add/remove securities from the data feed
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
|
||||
/// <param name="changes">The security additions and removals from the algorithm</param>
|
||||
public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
|
||||
{
|
||||
_model.InvokeMethod(nameof(OnSecuritiesChanged), algorithm, changes).Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user