PERF/BUG: Make the portfolio property call updated_portfolio.

Make the portfolio property on TradingAlgorithm call `updated_portfolio`
internally.  This prevents needless recomputation of the portfolio between
calls to `handle_data`, and also prevents issues where the portfolio object
could be unexpectedly modified in place in the body of a `handle_data` call.

Noteworthy finding in the course of investigating this bug:

If you modify a Python dictionary while iterating over it, the language will
only throw an exception if the size of the dictionary changes between loop
iterations; this means that you can do:
```
x = {1:1, 2:2, 3:3}
for k in x:
    old_val = x[k]
    del x[k]
    x[f(k)] = old_val
    print k
```
and you'll only get an error if f(k) is already a key in the dictionary.
This can lead to bizarre/nondeterministic behavior in the key iterator.
This commit is contained in:
Scott Sanderson
2014-05-27 11:20:13 -04:00
parent 146ec9329b
commit ecd9bff0d6
2 changed files with 15 additions and 15 deletions
+1 -5
View File
@@ -601,13 +601,9 @@ class TradingAlgorithm(object):
@property
def portfolio(self):
# internally this will cause a refresh of the
# period performance calculations.
return self.perf_tracker.get_portfolio()
return self.updated_portfolio()
def updated_portfolio(self):
# internally this will cause a refresh of the
# period performance calculations.
if self.portfolio_needs_update:
self._portfolio = self.perf_tracker.get_portfolio()
self.portfolio_needs_update = False