Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Algorithm/QCAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1527,7 +1527,7 @@ public void SetBenchmark(string ticker)
/// <summary>
/// Sets the benchmark used for computing statistics of the algorithm to the specified symbol
/// </summary>
/// <param name="symbol">symbol to use as the benchmark</param>
/// <param name="symbol">symbol to use as the benchmark, null to disable the benchmark</param>
[DocumentationAttribute(TradingAndOrders)]
[DocumentationAttribute(SecuritiesAndPortfolio)]
[DocumentationAttribute(Indicators)]
Expand All @@ -1538,6 +1538,13 @@ public void SetBenchmark(Symbol symbol)
throw new InvalidOperationException(Messages.QCAlgorithm.SetBenchmarkAlreadyInitialized());
}

if (symbol == null)
{
// Equivalent to no benchmark
Benchmark = new FuncBenchmark(_ => 0);
return;
}

// Create our security benchmark
Benchmark = SecurityBenchmark.CreateInstance(Securities, symbol);
}
Expand Down
32 changes: 32 additions & 0 deletions Tests/Algorithm/AlgorithmBenchmarkTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,38 @@ public void PythonSetBenchmarkThrowsDescriptiveErrorForUnsupportedBenchmarkType(
}
}

[TestCase(Language.CSharp)]
[TestCase(Language.Python)]
public void NullBenchmarkDisablesTheBenchmark(Language language)
{
var algorithm = new QCAlgorithm();
var dataManager = new DataManagerStub(algorithm, new MockDataFeed());
algorithm.SubscriptionManager.SetDataManager(dataManager);

if (language == Language.CSharp)
{
algorithm.SetBenchmark((Symbol)null);
}
else
{
using var _ = Py.GIL();
using var module = PyModule.FromString(nameof(NullBenchmarkDisablesTheBenchmark), @"
def set_benchmark(algorithm):
algorithm.set_benchmark(None)
");
using var pyAlgorithm = algorithm.ToPython();
using var setBenchmark = module.GetAttr("set_benchmark");
setBenchmark.Invoke(pyAlgorithm);
}

algorithm.PostInitialize();

// The default brokerage model benchmark is not used and no benchmark security is added
Assert.IsInstanceOf<FuncBenchmark>(algorithm.Benchmark);
Assert.AreEqual(0m, algorithm.Benchmark.Evaluate(new DateTime(2024, 1, 2)));
Assert.IsEmpty(algorithm.Securities);
}

[Test]
public void BenchmarkIsNotInitializeWithCustomSecurityInitializer()
{
Expand Down
Loading