An entry for the security sec
is in the data
dictionary only if sec
was traded in the latest time bar. This may happen with stocks not yet admitted to trading, delisted, suspended, renamed, or many low-volume small- and mid-caps. One way around this is to use a pattern seen in some examples:
for sec in context.securities:
if sec in data:
# look at sec, buy it low or sell it high
Then, if sec
was not traded in the latest bar, sec in data
is False
, and you will not attempt to look at the non-existent data[sec]
.
If the only concern is trying to trade before or after the security was admitted, you can instead do this:
for sec in context.securities:
if sec.security_start_date <= get_date time() <= sec.security_end_date:
order(sec, 1)
log.info("{}: Buying {} ({})".format(get_datetime("US/Eastern"), sec.security_name, sec.symbol))
Try this with Walgreen Co. (WAG) and Walgreen Boots Alliance (WBA) from December 2014 through January 2015, see http://www.marketwatch.com/story/walgreen-ticker-changes-to-wba-after-merger-with-boots-alliance-2014-12-31.