Algorithm Framework

Insight Manager

Introduction

The InsightManager tracks all of the Insight objects in your algorithm. It's an InsightCollection, which stores all of your insights in an internal dictionary that has the security Symbol as the key and a list of Insight objects as the value. You can access the manager anywhere in your algorithm where you have reference to the algorithm class. If you want to use an InsightCollection in your algorithm that's seperate from the InsightManager, create a new InsightCollection.

Add Insights

To add insights to the InsightManager, return a list of Insight objects from the Update method of your Alpha model or call the EmitInsights method. If you manage an InsightCollection that's seperate from the InsightManager, there are some methods to add Insight objects to it.

To add an insight to an InsightCollection, call the Add method.

_insightCollection.Add(insight);
self.insight_collection.Add(insight)

To add a list of insights, call the AddRange method.

_insightCollection.AddRange(insights);
self.insight_collection.AddRange(insights)

Check Membership

To check if an insight exists in the InsightManager, call the Contains method.

if (algorithm.Insights.Contains(insight))
{
    
}
if self.algorithm.Insights.Contains(insight):
    pass

To check if the InsightManager has an insight for a Symbol, call the ContainsKey method.

if (algorithm.Insights.ContainsKey(symbol))
{
    
}
if self.algorithm.Insights.ContainsKey(symbol):
    pass

To check if the InsightManager has active insights for a Symbol at a specific Coordinated Universal Time (UTC), call the HasActiveInsights method.

if (algorithm.Insights.HasActiveInsights(symbol, utcTime))
{
    
}
if self.algorithm.Insights.HasActiveInsights(symbol, utc_time):
    pass

Get Insights

To get the insights for a Symbol, index the InsightManager with the Symbol.

if (algorithm.Insights.ContainsKey(symbol))
{
    var insights = algorithm.Insights[symbol];
}
if self.algorithm.Insights.ContainsKey(symbol):
    insights = self.algorithm.Insights[symbol]

To get the insights that pass a filter, call the GetInsights method.

var insights = algorithm.Insights.GetInsights(insight => insight.Direction == InsightDirection.Up);
insights = self.algorithm.Insights.GetInsights(lambda insight: insight.Direction == InsightDirection.Up)

To iterate through the InsightManager, call the GetEnumerator method.

var enumerator = algorithm.Insights.GetEnumerator();
enumerator = self.algorithm.Insights.GetEnumerator()

To get all of the insights that will be active at a certain UTC time, call the GetActiveInsights method.

var activeInsights = algorithm.Insights.GetActiveInsights(utcTime);
active_insights = self.algorithm.Insights.GetActiveInsights(utc_time)

Get the Next Expiry Time

To get the next insight expiry time in UTC, call the GetNextExpiryTime method.

var nextExpiry = algorithm.Insights.GetNextExpiryTime();
next_expiry = self.algorithm.Insights.GetNextExpiryTime()

Remove Insights

Only the Portfolio Construction model should remove insights from the InsightManager. It should remove insights when the insights expire and when the corresponding security leaves the universe.

To remove an insight from the InsightManager, call the Remove method.

var removeSuccessful = algorithm.Insights.Remove(insight);
remove_successful = self.algorithm.Insights.Remove(insight)

To remove all the insights for a set of Symbol objects, pass a list of Symbol objects the Clear method.

algorithm.Insights.Clear(symbols);
self.algorithm.Insights.Clear(symbols)

To remove all the Insight objects, call the Clear method.

algorithm.Insights.Clear();
self.algorithm.Insights.Clear()

To remove all the insights that will be expired at a certain UTC time, call the RemoveExpiredInsights method.

var expiredInsights = algorithm.Insights.RemoveExpiredInsights(utcTime);
expired_insights = self.algorithm.Insights.RemoveExpiredInsights(utc_time)

Cancel Insights

In some cases, you may want to cancel an Insight. For example, if a Risk Management model in your algorithm liquidates a security, it should also cancel all of the active insights for the security. If you don't cancel the insights, the Portfolio Construction model might create a new PortfolioTarget to re-enter the position.

Another example of a situtation where you would want to cancel an Insight is when an Alpha model in your algorithm determines the trading opportunity has pre-maturely ended. For instance, say you want your algorithm to enter a long position in a security when its Relative Strength Index (RSI) moves below 20 and then liquidate the position when the security's RSI moves above 30. If you emit an Insight that has a duration of 30 days when the RSI moves below 20 but the RSI moves above 30 in 10 days, you should cancel the Insight when the RSI moves above 30.

To cancel insights, call the Cancel/Expire method with a list of Insight objects.

algorithm.Insights.Cancel(insights)
algorithm.Insights.Cancel(insights);

To cancel all the insights for some securities, call the Cancel/Expire method with a list of Symbol objects.

algorithm.Insights.Cancel(symbols)
algorithm.Insights.Cancel(symbols);

When you cancel an active insight, it's CloseTimeUtc property is set to one second into the past.

Copy Insights

To copy a subset of the Insight objects in the InsightManager to an array, call the CopyTo method. The arrayIndex argument is the zero-based index in the array at which copying begins.

algorithm.Insights.CopyTo(array, arrayIndex);
self.algorithm.Insights.CopyTo(array, arrayIndex)

Preserve Insights Between Deployments

Follow these steps to use the Object Store to preserve the algorithm state across live deployments:

  1. Create an algorithm that defines a storage key and adds insights to the Insight Manager.
  2. public class ObjectStoreChartingAlgorithm : QCAlgorithm
    {
        private string _insightKey;
        public override void Initialize()
        {
            _insightKey = $"{ProjectId}/insights";
            SetUniverseSelection(new ManualUniverseSelectionModel(QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA)));
            SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(5), 0.025, null));    
        }
    }
    class ObjectStoreChartingAlgorithm(QCAlgorithm):
        def Initialize(self):
            self.insight_key = f"{self.ProjectId}/insights"
            self.SetUniverseSelection(ManualUniverseSelectionModel([ Symbol.Create("SPY", SecurityType.Equity, Market.USA) ]))
            self.SetAlpha(ConstantAlphaModel(InsightType.Price, InsightDirection.Up, timedelta(5), 0.025, None))
  3. At the top of the algorithm file, add the following imports:
  4. from Newtonsoft.Json import JsonConvert
    from System.Collections.Generic import List

    Insight objects are a C# objects, so you need the preceding C# libraries to serialize and deserialize them.

  5. In the OnEndOfAlgorithm event handler of the algorithm, get the Insight objects and save them in the Object Store as a JSON object.
  6. public override void OnEndOfAlgorithm()
    {
        var insights = Insights.GetInsights(x => x.IsActive(UtcTime));
        ObjectStore.SaveJson(_insightKey, insights);
    }
    def OnEndOfAlgorithm(self):
        insights = self.Insights.GetInsights(lambda x: x.IsActive(self.UtcTime))
        content = ','.join([JsonConvert.SerializeObject(x) for x in insights])
        self.ObjectStore.Save(self.insight_key, f'[{content}]')
  7. At the bottom of the Initialize method, read the Insight objects from the Object Store and add them to the Insight Manager.
  8. if (ObjectStore.ContainsKey(_insightKey))
    {
        var insights = ObjectStore.ReadJson<List<Insight>>(_insightKey);
        Insights.AddRange(insights);
    }
    if self.ObjectStore.ContainsKey(self.insight_key):
        insights = self.ObjectStore.ReadJson[List[Insight]](self.insight_key)
        self.Insights.AddRange(insights)

The following algorithm provides a full example of preserving the Insight state between deployments:

Properties

The InsightManager has the following properties:

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: