MAINT: Clean up set_algo_instance usage in TradingAlgorithm.

TradingAlgorithm always uses set_algo_instance in pairs of
set_algo_instance(self) and set_algo_instance(None).  Refactoring this to use a
context manager.
This commit is contained in:
Scott Sanderson
2014-04-17 16:19:37 -04:00
parent 316611abd5
commit 47bfc2b536
2 changed files with 30 additions and 13 deletions
+23
View File
@@ -28,6 +28,29 @@ def set_algo_instance(algo):
context.algorithm = algo
class ZiplineAPI(object):
"""
Context manager for making an algorithm instance available to zipline API
functions within a scoped block.
"""
def __init__(self, algo_instance):
self.algo_instance = algo_instance
def __enter__(self):
"""
Set the given algo instance, storing any previously-existing instance.
"""
self.old_algo_instance = get_algo_instance()
set_algo_instance(self.algo_instance)
def __exit__(self, _type, _value, _tb):
"""
Restore the algo instance stored in __enter__.
"""
set_algo_instance(self.old_algo_instance)
def api_method(f):
# Decorator that adds the decorated class method as a callable
# function (wrapped) to zipline.api