Mariner Backtesting - KeyError

  • KeyErrors in Python are raised if you attempt to access an invalid key in a dictionary.
Sample Traceback
 Traceback (most recent call last):
  File "run_simulation.py", line 550, in <module>
    main(sys.argv[1:])
  File "run_simulation.py", line 525, in main
    results = simulator()
  File "/opt/anaconda/lib/python2.7/site-packages/tradesim/engine.py", line 542, in __call__
    return self.simulate()
  File "/opt/anaconda/lib/python2.7/site-packages/tradesim/engine.py", line 661, in simulate
    context_collection.process_event(event, delivery_timestamp)
  File "/opt/anaconda/lib/python2.7/site-packages/tradesim/context.py", line 712, in process_event
    event.context._call_on_timer(event)
  File "/opt/anaconda/lib/python2.7/site-packages/tradesim/context.py", line 465, in _call_on_timer
    self.strategy.on_timer(event, self.market, self.order, self.service, self.account)
  File "job/CQ8f16682d028a4d638d2d312ea7be9afb.py", line 100, in on_timer
    quantity = self.weights[self.symbol] / md.L1.last + account[self.symbol].position.shares
  File "/opt/anaconda/lib/python2.7/site-packages/pandas/core/series.py", line 583, in __getitem__
    result = self.index.get_value(self, key)
  File "/opt/anaconda/lib/python2.7/site-packages/pandas/indexes/base.py", line 1994, in get_value
    raise e1
KeyError: 'HPQ'
Sample Broken Code
 my_dictionary = {'AAPL': 500, 'GOOG': 1000} 
print my_dictionary['AAPL']
print my_dictionary['IBM']
Sample Fixed Code
 if 'AAPL' in my_dictionary:

    print my_dictionary['AAPL']

if 'IBM' in my_dictionary:
    print my_dictionary['IBM']
Notes
  • This makes sure that the key is present in your dictionary
  • Another standard python error. If you access an item in a dictionary that is not present.