Hi, 

I have been facing a problem trying to access a dictionary to store information when a security is purchased. 

The error is: 

Error Message

Runtime Error: Trying to retrieve an element from a collection using a key that does not exist in that collection throws a KeyError exception. To prevent the exception, ensure that the  key exist in the collection and/or that collection is not empty.  at OnData    self.Debug(f"Selling {symbol} at {self.Time}, Price: {price}, ARO_DPTL_{self.period}YR: {aro_value}, Purchase discount: {self.cef_discount_purchase[symbol]}")                                                                                                                             ~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^ in main.py: line 80

 

However, nowhere in my code am I deleting or removing the key related to the Dictionary. But to note, I am using a custom universe that is being filtered and sorted.

Surprisingly though, I am able to log and print the key at the time of purchase, but the key no longer exists at the time of sale:

 

ahmed-jaber_1719268447.jpg

 

Snippets of the code attached for reference (modified for confidentiality):

  1. from AlgorithmImports import *
  2. class CustomDataEMFAlgorithm(QCAlgorithm):
  3. def initialize(self):
  4. self.set_start_date(2008, 1, 8)
  5. self.set_end_date(2014, 7, 25)
  6. self.set_cash(100000)
  7. self.activeSecurities = set()
  8. universe = self.add_universe(MyCustomUniverseDataClass, "myCustomUniverse", self.selector_function)
  9. self.universe_settings.resolution = Resolution.DAILY
  10. #...
  11. self.discount_purchase = {}
  12. #...
  13. def OnData(self, data):
  14. if self.portfolioTargets == []:
  15. return
  16. for target in self.portfolioTargets:
  17. symbol = target.Symbol
  18. price = self.Securities[symbol].Price # Get the current price
  19. discount_value = self.discount_data[symbol] # Get the discount value from filter
  20. if value < self.lower_limit and not self.Portfolio[symbol].Invested:
  21. self.discount_purchase[symbol] = self.discount_data[symbol]
  22. self.SetHoldings(self.portfolioTargets) # Buy
  23. self.Debug(f"Buying {symbol} at {self.Time}, Price: {price}, Purchase discount: {self.discount_purchase[symbol]}")
  24. elif aro_value > self.upper_limit and self.Portfolio[symbol].Invested:
  25. self.Liquidate(symbol) # Sell
  26. self.Debug(f"Selling {symbol} at {self.Time}, Price: {price}, Purchase discount: {self.discount_purchase[symbol]}")
  27. # Example custom universe data; it is virtually identical to other custom data types.
  28. class MyCustomUniverseDataClass(PythonData):
  29. #...
+ Expand

Author

Ahmed Jaber

June 2024