quantopian/zipline — pull request #57 by ehebert (2013-01-12 19:44:56+00:00)
Title: Recycles objects for portfolio and positions. 

Recycles the objects created to pass the portfolio and positions to handle_data.

Since these values are passed to every call to handle_data, the object
creation for each hit of this loop becomes a high overall cost.
Instead of creating on object on each pass, this patch uses the same object for each pass,
but changes the values contained with in before passing along to handle_data.

With some benchmarking, seeing a large order of magnitude gain.
i.e. in a data set where `as_portfolio` took over 5 seconds, when recycling values `as_portfolio` now takes under 0.5 seconds.

Also, changes the containing type of the positions to be a regular Python dict, since accessing the values inside of the ndict had too much of a penalty.
This changes the existing behavior when a position is being accessed when that position does not exist.
Previously, a position for that sid would be created, but with zeroed out values (i.e. the default/starting values).
Code inside of handle_data will now have to check for existence of a position before accessing it.

i.e., previously:

```
position = context.portfolio.positions['STOCK']
```

Would return a value of `position` as the following:
```
ndict({'sid': 'STOCK',
'cost_basis': 0.0,
'last_sale_price': 0.0,
'amount': 0})
```

Now, a handle_data that accesses positions, should wrap the call as such:
```
if 'STOCK' in context.portfolio.positions:
position = context.portfolio.positions['STOCK']
```

or

```
try:
position = context.portfolio.positions['STOCK']
except KeyError:
log.info("No position held for 'STOCK'")
```