chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 13:02:50 +08:00
commit 0fc60fdcb1
5008 changed files with 910633 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
/*
* 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 QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Orders;
using QuantConnect.Python;
namespace QuantConnect.Algorithm.Framework.Execution
{
/// <summary>
/// Provides a base class for execution models
/// </summary>
public class ExecutionModel : BasePythonWrapper<ExecutionModel>, IExecutionModel
{
/// <summary>
/// If true, orders should be submitted asynchronously.
/// </summary>
protected bool Asynchronous { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ExecutionModel"/> class.
/// </summary>
/// <param name="asynchronous">If true, orders should be submitted asynchronously</param>
public ExecutionModel(bool asynchronous = true)
{
Asynchronous = asynchronous;
}
/// <summary>
/// Submit orders for the specified portfolio targets.
/// This model is free to delay or spread out these orders as it sees fit
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="targets">The portfolio targets just emitted by the portfolio construction model.
/// These are always just the new/updated targets and not a complete set of targets</param>
public virtual void Execute(QCAlgorithm algorithm, IPortfolioTarget[] targets)
{
throw new System.NotImplementedException("Types deriving from 'ExecutionModel' must implement the 'void Execute(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)
{
}
/// <summary>
/// New order event handler
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="orderEvent">Order event to process</param>
public virtual void OnOrderEvent(QCAlgorithm algorithm, OrderEvent orderEvent)
{
}
}
}
@@ -0,0 +1,90 @@
/*
* 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.Algorithm.Framework.Portfolio;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Orders;
using QuantConnect.Python;
using System;
namespace QuantConnect.Algorithm.Framework.Execution
{
/// <summary>
/// Provides an implementation of <see cref="IExecutionModel"/> that wraps a <see cref="PyObject"/> object
/// </summary>
public class ExecutionModelPythonWrapper : ExecutionModel
{
private readonly bool _onOrderEventsDefined;
/// <summary>
/// Constructor for initialising the <see cref="IExecutionModel"/> class with wrapped <see cref="PyObject"/> object
/// </summary>
/// <param name="model">Model defining how to execute trades to reach a portfolio target</param>
public ExecutionModelPythonWrapper(PyObject model)
{
SetPythonInstance(model, false);
foreach (var attributeName in new[] { "Execute", "OnSecuritiesChanged" })
{
if (!HasAttr(attributeName))
{
throw new NotImplementedException($"IExecutionModel.{attributeName} must be implemented. Please implement this missing method on {model.GetPythonType()}");
}
}
_onOrderEventsDefined = HasAttr("OnOrderEvent");
var methodName = nameof(SetPythonInstance);
if (HasAttr(methodName))
{
InvokeMethod(methodName, model);
}
}
/// <summary>
/// Submit orders for the specified portfolio targets.
/// This model is free to delay or spread out these orders as it sees fit
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="targets">The portfolio targets to be ordered</param>
public override void Execute(QCAlgorithm algorithm, IPortfolioTarget[] targets)
{
InvokeMethod(nameof(Execute), algorithm, targets).Dispose();
}
/// <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)
{
InvokeMethod(nameof(OnSecuritiesChanged), algorithm, changes).Dispose();
}
/// <summary>
/// New order event handler
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="orderEvent">Order event to process</param>
public override void OnOrderEvent(QCAlgorithm algorithm, OrderEvent orderEvent)
{
if (_onOrderEventsDefined)
{
InvokeMethod(nameof(OnOrderEvent), algorithm, orderEvent).Dispose();
}
}
}
}
+42
View File
@@ -0,0 +1,42 @@
/*
* 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 QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Orders;
namespace QuantConnect.Algorithm.Framework.Execution
{
/// <summary>
/// Algorithm framework model that executes portfolio targets
/// </summary>
public interface IExecutionModel : INotifiedSecurityChanges
{
/// <summary>
/// Submit orders for the specified portfolio targets.
/// This model is free to delay or spread out these orders as it sees fit
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="targets">The portfolio targets just emitted by the portfolio construction model.
/// These are always just the new/updated targets and not a complete set of targets</param>
void Execute(QCAlgorithm algorithm, IPortfolioTarget[] targets);
/// <summary>
/// New order event handler
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="orderEvent">Order event to process</param>
void OnOrderEvent(QCAlgorithm algorithm, OrderEvent orderEvent);
}
}
@@ -0,0 +1,86 @@
/*
* 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 QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Algorithm.Framework.Portfolio;
namespace QuantConnect.Algorithm.Framework.Execution
{
/// <summary>
/// Provides an implementation of <see cref="IExecutionModel"/> that immediately submits
/// market orders to achieve the desired portfolio targets
/// </summary>
public class ImmediateExecutionModel : ExecutionModel
{
private readonly PortfolioTargetCollection _targetsCollection = new PortfolioTargetCollection();
/// <summary>
/// Initializes a new instance of the <see cref="ImmediateExecutionModel"/> class.
/// </summary>
/// <param name="asynchronous">If true, orders will be submitted asynchronously</param>
public ImmediateExecutionModel(bool asynchronous = true)
: base(asynchronous)
{
}
/// <summary>
/// Immediately submits orders for the specified portfolio targets.
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="targets">The portfolio targets to be ordered</param>
public override void Execute(QCAlgorithm algorithm, IPortfolioTarget[] targets)
{
_targetsCollection.AddRange(targets);
// for performance we if empty, OrderByMarginImpact and ClearFulfilled are expensive to call
if (!_targetsCollection.IsEmpty)
{
foreach (var target in _targetsCollection.OrderByMarginImpact(algorithm))
{
var security = algorithm.Securities[target.Symbol];
// calculate remaining quantity to be ordered
var quantity = OrderSizing.GetUnorderedQuantity(algorithm, target, security, true);
if (quantity != 0)
{
if (security.BuyingPowerModel.AboveMinimumOrderMarginPortfolioPercentage(security, quantity,
algorithm.Portfolio, algorithm.Settings.MinimumOrderMarginPortfolioPercentage))
{
algorithm.MarketOrder(security, quantity, Asynchronous, target.Tag);
}
else if (!PortfolioTarget.MinimumOrderMarginPercentageWarningSent.HasValue)
{
// will trigger the warning if it has not already been sent
PortfolioTarget.MinimumOrderMarginPercentageWarningSent = false;
}
}
}
_targetsCollection.ClearFulfilled(algorithm);
}
}
/// <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)
{
}
}
}
@@ -0,0 +1,52 @@
# 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 ImmediateExecutionModel(ExecutionModel):
'''Provides an implementation of IExecutionModel that immediately submits market orders to achieve the desired portfolio targets'''
def __init__(self, asynchronous=True):
'''Initializes a new instance of the ImmediateExecutionModel class.
Args:
asynchronous: If True, orders will be submitted asynchronously.'''
super().__init__(asynchronous)
self.targets_collection = PortfolioTargetCollection()
def execute(self, algorithm, targets):
'''Immediately submits orders for the specified portfolio targets.
Args:
algorithm: The algorithm instance
targets: The portfolio targets to be ordered'''
# for performance we check count value, OrderByMarginImpact and ClearFulfilled are expensive to call
self.targets_collection.add_range(targets)
if not self.targets_collection.is_empty:
for target in self.targets_collection.order_by_margin_impact(algorithm):
security = algorithm.securities[target.symbol]
# calculate remaining quantity to be ordered
quantity = OrderSizing.get_unordered_quantity(algorithm, target, security, True)
if quantity != 0:
above_minimum_portfolio = BuyingPowerModelExtensions.above_minimum_order_margin_portfolio_percentage(
security.buying_power_model,
security,
quantity,
algorithm.portfolio,
algorithm.settings.minimum_order_margin_portfolio_percentage)
if above_minimum_portfolio:
algorithm.market_order(security, quantity, self.asynchronous, target.tag)
elif not PortfolioTarget.minimum_order_margin_percentage_warning_sent:
# will trigger the warning if it has not already been sent
PortfolioTarget.minimum_order_margin_percentage_warning_sent = False
self.targets_collection.clear_fulfilled(algorithm)
+35
View File
@@ -0,0 +1,35 @@
/*
* 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 QuantConnect.Algorithm.Framework.Portfolio;
namespace QuantConnect.Algorithm.Framework.Execution
{
/// <summary>
/// Provides an implementation of <see cref="IExecutionModel"/> that does nothing
/// </summary>
public class NullExecutionModel : ExecutionModel
{
/// <summary>
/// Execute the ExecutionModel
/// </summary>
/// <param name="algorithm">The Algorithm to execute this model on</param>
/// <param name="targets">The portfolio targets</param>
public override void Execute(QCAlgorithm algorithm, IPortfolioTarget[] targets)
{
// NOP
}
}
}
+19
View File
@@ -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 NullExecutionModel(ExecutionModel):
'''Provides an implementation of IExecutionModel that does nothing'''
def execute(self, algorithm, targets):
pass