In the following python example, I provide an alternative to the RollingWindow class when storing historical indicator values.

I am new to QuantConnect and coming from an older trading platform. I chose QuantConnect because it offers support for multiple languages and ability to trade different types of instruments including equity, futures, and options. In an attempt to acquaint myself with the platform, I wanted to write a simple python algorithm which accesses historical data for an indicator. 

To save historical data in QuantConnect, one needs to use the abstract RollingWindow class. To store indicator values, one must create a custom class which is instantiated and appended with each indicator update. Later, one can access historical values by simply indexing the RollingWindow object. A great C# example is available on the Community forum.

When I tried to create my algorithm, I learned the RollingWindow class does not support custom class types in python at this time.  Given python's vast library, I was able to find a workaround using python's collections.deque (pronounced "deck") class.

The deque class offers a method to prepend a python list with each new value. Prepending will store the most recent value in the first element of the list, while the oldest value is stored in the last element of the list. If I had a deque object labeled MacdHist, then I could retrieve the MACD values 5 bars ago using the notation, MacdHist[5].  

According to the python documentation, prepending the list using the deque method can be accomplished without significant performance impact, but I have not tested the actual performance myself. To ensure that the list does not grow unnecessarily large, I specify the maximum length of the list during instantiation of the deque object.

In my algorithm, I created a custom class, MacdState, which stores all the values associated with the MACD.   Each time the MACD is updated, the platform will call my macdUpdated function.  In this function, I  instantiate a new MacdState class and prepend the resulting object to the deque object, MacdHist. Each time the MacdState class is instantiated, it stores the lastest MACD value.

In the OnData function,  with each bar update, I check whether the MACD  has crossed above zero by accessing the current and previous MACD values stored in MacdHist. If crossed, I enter a long position.  If I am in a position and the most recent MACD value drops below zero, I liquidate the position.

I hope this example helps others who need to store historical values for their indicators when using python.

Author