-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Call the python reset from PythonIndicator.Reset #9698
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mkzung
wants to merge
2
commits into
QuantConnect:master
Choose a base branch
from
mkzung:bug-9697-python-indicator-reset
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| /* | ||
| * 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 NUnit.Framework; | ||
| using Python.Runtime; | ||
| using QuantConnect.Indicators; | ||
|
|
||
| namespace QuantConnect.Tests.Indicators | ||
| { | ||
| [TestFixture] | ||
| public class PythonIndicatorResetSnakeCaseTests : PythonIndicatorResetTests | ||
| { | ||
| protected override bool SnakeCase => true; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Reset cases that build their own python class, so they do not use the indicator | ||
| /// the surrounding fixtures create. Kept separate from <see cref="PythonIndicatorTests"/> | ||
| /// for that reason: inheriting them there would run each case in four more fixtures | ||
| /// without changing anything it exercises. | ||
| /// </summary> | ||
| [TestFixture] | ||
| public class PythonIndicatorResetTests | ||
| { | ||
| protected virtual bool SnakeCase => false; | ||
|
|
||
| private const int RecursionCap = 200; | ||
|
|
||
| private static PythonIndicator CreateIndicatorFrom(string source, string className) | ||
| { | ||
| using (Py.GIL()) | ||
| { | ||
| var module = PyModule.FromString(Guid.NewGuid().ToString(), source); | ||
| var instance = module.GetAttr(className).Invoke(); | ||
|
|
||
| return new PythonIndicator(instance); | ||
| } | ||
| } | ||
|
|
||
| [Test] | ||
| public void ResetIsNotReenteredByASubclassCallingSuper() | ||
| { | ||
| using (Py.GIL()) | ||
| { | ||
| var module = PyModule.FromString( | ||
| Guid.NewGuid().ToString(), | ||
| $@" | ||
| from AlgorithmImports import * | ||
| from collections import deque | ||
|
|
||
| class RecursiveReset(PythonIndicator): | ||
| depth = 0 | ||
| max_depth = 0 | ||
|
|
||
| def __init__(self): | ||
| self.{(SnakeCase ? "name" : "Name")} = 'recursive' | ||
| self.{(SnakeCase ? "value" : "Value")} = 0 | ||
| self.queue = deque(maxlen=3) | ||
|
|
||
| def {(SnakeCase ? "update" : "Update")}(self, input): | ||
| self.queue.appendleft(input.Value) | ||
| self.{(SnakeCase ? "value" : "Value")} = sum(self.queue) / len(self.queue) | ||
| return len(self.queue) == self.queue.maxlen | ||
|
|
||
| def {(SnakeCase ? "reset" : "Reset")}(self): | ||
| cls = type(self) | ||
| cls.depth += 1 | ||
| cls.max_depth = max(cls.max_depth, cls.depth) | ||
| if cls.depth < {RecursionCap}: | ||
| super().{(SnakeCase ? "reset" : "Reset")}() | ||
| cls.depth -= 1 | ||
| self.queue.clear() | ||
| " | ||
| ); | ||
|
|
||
| var pythonIndicator = module.GetAttr("RecursiveReset").Invoke(); | ||
|
|
||
| // An inheriting class converts to its own CSharp part, so SetIndicator points the | ||
| // wrapper at this same object. This is what WrapPythonIndicator does on registration. | ||
| pythonIndicator.TryConvert(out PythonIndicator indicator); | ||
| Assert.IsNotNull(indicator); | ||
| indicator.SetIndicator(pythonIndicator); | ||
|
|
||
| indicator.Update(new IndicatorDataPoint(new DateTime(2024, 1, 1), 100m)); | ||
| indicator.Reset(); | ||
|
|
||
| // Zero would mean the python reset was never reached, the cap would mean it recursed. | ||
| var depth = module.GetAttr("RecursiveReset").GetAttr("max_depth").As<int>(); | ||
| Assert.AreEqual(1, depth, $"python reset() ran {depth} deep"); | ||
| Assert.AreEqual(0, indicator.Samples); | ||
| Assert.AreEqual(0, pythonIndicator.GetAttr("queue").Length()); | ||
| } | ||
| } | ||
|
|
||
| [Test] | ||
| public void ResetSkipsANonMethodResetAttribute() | ||
| { | ||
| using (Py.GIL()) | ||
| { | ||
| var indicator = CreateIndicatorFrom($@" | ||
| class PlainResetAttribute(): | ||
| def __init__(self): | ||
| self.{(SnakeCase ? "name" : "Name")} = 'plain' | ||
| self.{(SnakeCase ? "value" : "Value")} = 0 | ||
| self.{(SnakeCase ? "is_ready" : "IsReady")} = False | ||
| self.{(SnakeCase ? "reset" : "Reset")} = False | ||
|
|
||
| def {(SnakeCase ? "update" : "Update")}(self, input): | ||
| self.{(SnakeCase ? "value" : "Value")} = input.Value | ||
| self.{(SnakeCase ? "is_ready" : "IsReady")} = True | ||
| return True | ||
| ", "PlainResetAttribute"); | ||
|
|
||
| indicator.Update(new IndicatorDataPoint(new DateTime(2024, 1, 1), 100m)); | ||
|
|
||
| Assert.DoesNotThrow(() => indicator.Reset()); | ||
| Assert.AreEqual(0, indicator.Samples); | ||
| } | ||
| } | ||
|
|
||
| [Test] | ||
| public void ResetClearsTheCSharpStateWhenPythonRaises() | ||
| { | ||
| using (Py.GIL()) | ||
| { | ||
| var indicator = CreateIndicatorFrom($@" | ||
| from AlgorithmImports import * | ||
| from collections import deque | ||
|
|
||
| class RaisingReset(PythonIndicator): | ||
| def __init__(self): | ||
| self.{(SnakeCase ? "name" : "Name")} = 'raising' | ||
| self.{(SnakeCase ? "value" : "Value")} = 0 | ||
| self.queue = deque(maxlen=3) | ||
|
|
||
| def {(SnakeCase ? "update" : "Update")}(self, input): | ||
| self.queue.appendleft(input.Value) | ||
| self.{(SnakeCase ? "value" : "Value")} = sum(self.queue) / len(self.queue) | ||
| return len(self.queue) == self.queue.maxlen | ||
|
|
||
| def {(SnakeCase ? "reset" : "Reset")}(self): | ||
| raise ValueError('boom') | ||
| ", "RaisingReset"); | ||
|
|
||
| indicator.Update(new IndicatorDataPoint(new DateTime(2024, 1, 1), 100m)); | ||
| Assert.AreEqual(1, indicator.Samples); | ||
|
|
||
| Assert.Throws<PythonException>(() => indicator.Reset()); | ||
|
|
||
| Assert.AreEqual(0, indicator.Samples); | ||
| Assert.IsFalse(indicator.IsReady); | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also assert
IsReadyis false (orSamples == 0) afterReset()— dropping_isReady = falsewouldn't fail this test.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sharper than it first looked, because the assertion would have been vacuous as well as missing. The indicator has period 14 and the test fed it three points, so it was never ready, and asserting
IsReadyis false after a reset would have passed against any implementation at all.It feeds 20 now and asserts ready first.
Dropping
_isReady = falseturns it red in all six fixtures that inheritPythonIndicatorTests.