mirror of
https://github.com/wassname/catalyst.git
synced 2026-09-09 11:19:23 +08:00
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:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user