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):

from AlgorithmImports import *
class CustomDataEMFAlgorithm(QCAlgorithm):

    def initialize(self):

        self.set_start_date(2008, 1, 8)
        self.set_end_date(2014, 7, 25)
        self.set_cash(100000)
        self.activeSecurities = set()

        universe = self.add_universe(MyCustomUniverseDataClass, "myCustomUniverse", self.selector_function)
        self.universe_settings.resolution = Resolution.DAILY

		#...

        self.discount_purchase = {}

        #...

        
    def OnData(self, data):
        
        
        if self.portfolioTargets == []:
            return
        
        for target in self.portfolioTargets:
            symbol = target.Symbol
            price = self.Securities[symbol].Price  # Get the current price
            discount_value = self.discount_data[symbol] # Get the discount value from filter
            if value < self.lower_limit and not self.Portfolio[symbol].Invested:
                self.discount_purchase[symbol] = self.discount_data[symbol]
                self.SetHoldings(self.portfolioTargets) # Buy
                self.Debug(f"Buying {symbol} at {self.Time}, Price: {price}, Purchase discount: {self.discount_purchase[symbol]}")
            elif aro_value > self.upper_limit and self.Portfolio[symbol].Invested:
                self.Liquidate(symbol) # Sell
                self.Debug(f"Selling {symbol} at {self.Time}, Price: {price}, Purchase discount: {self.discount_purchase[symbol]}")

                  
# Example custom universe data; it is virtually identical to other custom data types.
class MyCustomUniverseDataClass(PythonData):
	#...