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 Updateupdate method of your Alpha model or call the EmitInsights
emit_insights
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
add
method.
// You can manually add an Insight to an InsightCollection object to organize, fetch, or cancel insights an alpha has generated. _insightCollection.Add(insight);
# You can manually add an Insight to an InsightCollection object to organize, fetch, or cancel insights an alpha has generated. self.insight_collection.add(insight)
To add a list of insights, call the AddRange
add_range
method.
// You can manually add a list of Insights to an InsightCollection object to organize, fetch, or cancel insights an alpha has generated. _insightCollection.AddRange(insights);
# You can manually add a list of Insights to an InsightCollection object to organize, fetch, or cancel insights an alpha has generated. self.insight_collection.add_range(insights)
Check Membership
To check if an insight exists in the InsightManager
, call the Contains
contains
method.
// Check the algorithms central insight collection (InsightManager) to avoid emitting duplicates, reducing the processing work. if (algorithm.Insights.Contains(insight)) { }
# Check the algorithms central insight collection (InsightManager) to avoid emitting duplicates, reducing the processing work. if algorithm.insights.contains(insight): pass
To check if the InsightManager
has an insight for a Symbol
, call the ContainsKey
contains_key
method.
// Check the algorithms central insight collection (InsightManager) if there's already been an insight for this symbol across the other alphas. if (algorithm.Insights.ContainsKey(symbol)) { }
# Check the algorithms central insight collection (InsightManager) if there's already been an insight for this symbol across the other alphas. if algorithm.insights.contains_key(symbol): pass
To check if the InsightManager
has active insights for a Symbol
at a specific Coordinated Universal Time (UTC), call the HasActiveInsights
has_active_insights
method.
// Check if there are active insights for a specific symbol at the given time to determine if alpha should emit more insights. if (algorithm.Insights.HasActiveInsights(symbol, utcTime)) { }
# Check if there are active insights for a specific symbol at the given time to determine if alpha should emit more insights if algorithm.insights.has_active_insights(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 algorithm.insights.contains_key(symbol): insights = algorithm.insights[symbol]
To get the insights that pass a filter, call the GetInsights
get_insights
method.
var insights = algorithm.Insights.GetInsights(insight => insight.Direction == InsightDirection.Up);
insights = algorithm.insights.get_insights(lambda insight: insight.direction == Insightdirection.up)
To iterate through the InsightManager
, call the GetEnumerator
get_enumerator
method.
var enumerator = algorithm.insights.get_enumerator();
enumerator = algorithm.insights.get_enumerator()
To get all of the insights that will be active at a certain UTC time, call the GetActiveInsights
get_active_insights
method.
var activeInsights = algorithm.Insights.GetActiveInsights(utcTime);
active_insights = algorithm.insights.get_active_insights(utc_time)
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
remove
method.
var removeSuccessful = algorithm.Insights.Remove(insight);
remove_successful = algorithm.insights.remove(insight)
To remove all the insights for a set of Symbol
objects, pass a list of Symbol
objects the Clear
clear
method.
algorithm.insights.clear(symbols);
algorithm.insights.clear(symbols)
To remove all the insights that will be expired at a certain UTC time, call the RemoveExpiredInsights
remove_expired_insights
method.
var expiredInsights = algorithm.Insights.RemoveExpiredInsights(utcTime);
expired_insights = algorithm.insights.remove_expired_insights(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
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
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
close_time_utc
property is set to one second into the past.
Preserve Insights Between Deployments
Follow these steps to use the Object Store to preserve the algorithm state across live deployments:
- Create an algorithm that defines a storage key and adds insights to the Insight Manager.
- At the top of the algorithm file, add the following imports:
- In the OnEndOfAlgorithmon_end_of_algorithm event handler of the algorithm, get the Insight objects and save them in the Object Store as a JSON object.
- At the bottom of the
Initialize
initialize
method, read the Insight objects from the Object Store and add them to the Insight Manager.
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.project_id}/insights" self.set_universe_selection(ManualUniverseSelectionModel([ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ])) self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(5), 0.025, None))
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.
public override void OnEndOfAlgorithm() { var insights = Insights.GetInsights(x => x.IsActive(UtcTime)); ObjectStore.SaveJson(_insightKey, insights); }
def on_end_of_algorithm(self): insights = self.insights.get_insights(lambda x: x.is_active(self.utc_time)) content = ','.join([JsonConvert.SerializeObject(x) for x in insights]) self.object_store.save(self.insight_key, f'[{content}]')
if (ObjectStore.ContainsKey(_insightKey)) { var insights = ObjectStore.ReadJson<List<Insight>>(_insightKey); Insights.AddRange(insights); }
if self.object_store.contains_key(self.insight_key): insights = self.object_store.read_json[List[Insight]](self.insight_key) self.insights.add_range(insights)
The following algorithm provides a full example of preserving the Insight state between deployments: