Skip to content

Commit

Permalink
Handle zero price and target quantity case - Collective2 (#8525)
Browse files Browse the repository at this point in the history
* Skip zero price and target quantity case

* Addressed PR comments

* Addressed new PR comments
  • Loading branch information
JosueNina authored Jan 13, 2025
1 parent f689826 commit d633fed
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ public class Collective2SignalExport : BaseSignalExport
/// </summary>
private IAlgorithm _algorithm;

/// <summary>
/// Flag to track if the warning has already been printed.
/// </summary>
private bool _isZeroPriceWarningPrinted;

/// <summary>
/// The name of this signal export
/// </summary>
Expand Down Expand Up @@ -212,6 +217,15 @@ protected int ConvertPercentageToQuantity(IAlgorithm algorithm, PortfolioTarget
var numberShares = PortfolioTarget.Percent(algorithm, target.Symbol, target.Quantity);
if (numberShares == null)
{
if (algorithm.Securities.TryGetValue(target.Symbol, out var security) && security.Price == 0 && target.Quantity == 0)
{
if (!_isZeroPriceWarningPrinted)
{
_isZeroPriceWarningPrinted = true;
algorithm.Debug($"Warning: Collective2 failed to calculate target quantity for {target}. The price for {target.Symbol} is 0, and the target quantity is 0. Will return 0 for all similar cases.");
}
return 0;
}
throw new InvalidOperationException($"Collective2 failed to calculate target quantity for {target}");
}

Expand Down
19 changes: 19 additions & 0 deletions Tests/Algorithm/Framework/Portfolio/SignalExportTargetTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,25 @@ public void SignalExportManagerGetsCorrectPortfolioTargetArray(SecurityType secu
Assert.AreEqual(quantity, targetQuantity, 1);
}

[Test]
public void SignalExportManagerDoesNotThrowOnZeroPrice()
{
var algorithm = new AlgorithmStub(true);
algorithm.SetDateTime(new DateTime(2024, 02, 16, 11, 53, 30));

var security = algorithm.AddSecurity(Symbols.SPY);
// Set the market price to 0 to simulate the edge case being tested
security.SetMarketPrice(new Tick { Value = 0 });

using var manager = new Collective2SignalExportHandler("", 0);
// Ensure ConvertPercentageToQuantity does not throw when price is 0
Assert.DoesNotThrow(() =>
{
var result = manager.ConvertPercentageToQuantity(algorithm, new PortfolioTarget(Symbols.SPY, 0));
Assert.AreEqual(0, result);
});
}

[Test]
public void SignalExportManagerHandlesIndexOptions()
{
Expand Down

0 comments on commit d633fed

Please sign in to comment.