Also notice the history() call is outside of the 'for' loop since history already has the history for every stock in data (so no need to re-run history() inside the loop each time).
Another point generally (although it might not apply so directly to the code above): At one time I recall running into a cryptic message doing for stock in context.stocks that took a skype session with Q to figure it out, it was merely because a stock had no trades during that bar, and I was bitten by it way down the line in another function, so ever since then I stick with for stock in data, or for some other purposes for stock in context.portfolio.positions, just never for stock in context.stocks, recommend shying away from that. You can see MT has some safeguards.
Notice the vertical alignment of equal signs in Market Tech code, makes for easier reading.
You can even run wild with white space like I do:
c.highs = history(period, '1d', 'high') .bfill().fillna(1)
c.lows = history(period, '1d', 'low') .bfill().fillna(1)
c.prices = history(period, '1d', 'price').bfill().fillna(1)
if show_beta: do_show_beta( c, sec)
if show_volatility: do_show_volatility(c, sec)
if show_drawdown: do_show_drawdown( c, sec, price)
(c = context) There's virtually no performance hit, Python runs a built version that removes all white space, and comments.
Part of the reason I posted that is that I'm not sure of what I'm doing with the fills in case anyone has a definitive tip.