Quant League is evolving into Strategies, our new home for sharing, discovering, and exploring trading strategies, with improved organization and a better overall experience. Q4-2025 will be the final Quant League.
LEAN is the open-source algorithmic trading engine powering QuantConnect.
Founded in 2012 LEAN has been built by a global community of 180+ engineers and powers more than 300+ hedge funds today.
Join Our Discord Channel
Join QuantConnect's Discord server for real-time support, where a vibrant community of traders and developers awaits to help you with any of your QuantConnect needs.
This research is under review. To publish this research attract three community upvotes.
This research is under review. To publish this research attract three community upvotes.
This discussion is a draft. Click here to publish this discusison.
Algorithmic Trading Video Series #8 | Dyanimc Universes
Hi,
Just published the 8th video of my algorithmic trading course using Python and the QC platform. Below you can find the backtest and code from that video. Simply click the “Clone Algorithm” button to copy the code to your own projects.
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Log Up
1.2k Pro
,
Hi Louis Thanks for the video! I have one question: when we execute self.SetHoldings(self.portfolioTargets), what happens to the securities which are already in portfolio and in portfolioTargets too? I suppose if the ratio is same then nothing will happen, but if it's changed then it will be bought/sold according to the ratio specified? Am I interpreting it right? Thanks.
Louis Szeto
45.8k Pro
,
Hi Log Up
There would be no effect on other existing positions. The SetHoldings method is actually placing MarketOrder in quantity representing a proportion of the portfolio value for an asset.
If you want to rebalance the portfolio, you could consider
1. Liquidate all positions and use SetHoldings with a list of PortfolioTarget
2. using the Framework and InsightWeightingPortfolioConstructionModel. Active insight weights sum up larger than 1 will rebalance when new insight arrives. This could avoid excessive orders when singular order is desired instead of a whole portfolio change.
Best Louis
Log Up
1.2k Pro
,
HI Louis Szeto , thanks for the reply. Let's say I have SetHoldings with TSLA as 0.1(10%) previously, and in next iteration of OnData I set it to 0.2(20%) of my portfolio, then what will happen in this case?
Louis Szeto
45.8k Pro
,
Hi Log Up
For the same asset, it would hold the new set ratio (i.e. 20%). The other assets would not change their existing positions although (they will not automatically rebalance/adjust).
Best Louis
Sam von Badan
26 Pro
,
Hi Louis,
thank you for the videos.
I am just a beginner and have watched your videos.
Please I have some questions regarding AddUniverse with CoarseSelectionFunction and FineSelectionFunction
In your videos, you have selected
Coarse: Securities with FundamentalData that have DollarVolume > a certain amount.
But I also want the Filter to include: Industry, segment, etc.
Please how can I add those to my CoarseSelectionFunction?
Thank you for the very helpful videos, indeed this has really allowed me to gain knowledge I previously found to be very difficult, despite trying other tutorials too! Your approach to teaching is outstanding.
I have a question regarding customdata universe, and the use on onSecuritiesChanged function. I am getting this error while backtesting and I am not entirely sure why this is happening:
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 on_securities_changed
self.activeSecurities.remove(x.Symbol)
in main.py: line 27
And this is my line of code:
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.portfolioTargets = []
# Define the selector function
def selector_function(self, data):
sorted_data = sorted([ x for x in data if x["ARO_5YR"] < 33 ],
key=lambda x: x.end_time) #,
# reverse=True)
self.Log('Stocks with discount percentile < 33: ' + str(len(sorted_data)))
return [x.symbol for x in sorted_data]
def on_securities_changed(self, changes):
# close positions in removed securities
for x in changes.RemovedSecurities:
self.Liquidate(x.Symbol)
self.activeSecurities.remove(x.Symbol)
# can't open positions here since data might not be added correctly yet
for x in changes.AddedSecurities:
self.activeSecurities.add(x.Symbol)
# adjust targets if universe has changed
self.portfolioTargets = [PortfolioTarget(symbol, 1/len(self.activeSecurities))
for symbol in self.activeSecurities]
def OnData(self, data):
if self.portfolioTargets == []:
return
# for symbol in self.activeSecurities:
# if symbol not in data:
# return
self.SetHoldings(self.portfolioTargets)
self.portfolioTargets = []
# Example custom universe data; it is virtually identical to other custom data types.
class MyCustomUniverseDataClass(PythonData):
def get_source(self, config, date, is_live_mode):
source = "https://raw.githubusercontent.com/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.csv"
return SubscriptionDataSource(source, SubscriptionTransportMedium.RemoteFile);
def Reader(self, config, line, date, isLive):
if not (line.strip() and line[0].isalnum()):
return None
items = line.split(",")
# Generate required data, then return an instance of your class.
data = MyCustomUniverseDataClass()
try:
data.end_time = datetime.strptime(items[1], '%Y-%m-%d')+timedelta(hours=20)
# define Time as exactly 1 day earlier Time
data.time = data.end_time - timedelta(1)
data.symbol = Symbol.create(items[0], SecurityType.EQUITY, Market.USA)
data.value = float(items[5])
data["Open"] = float(items[2])
data["High"] = float(items[3])
data["Low"] = float(items[4])
data["Close"] = float(items[5])
data["Volume"] = int(items[6])
data["ARO_5YR"] = float(items[7])
except ValueError:
return None
return data
My csv data looks like this, with hundreds of tickers…:
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp. You can
continue your Boot Camp training progress from the terminal. We
hope to see you in the community soon!
Allocate to this Strategy
Institutional clients can contact the author and allocate capital to this strategy.
Log Up
Hi Louis Thanks for the video! I have one question: when we execute self.SetHoldings(self.portfolioTargets), what happens to the securities which are already in portfolio and in portfolioTargets too? I suppose if the ratio is same then nothing will happen, but if it's changed then it will be bought/sold according to the ratio specified? Am I interpreting it right? Thanks.
Louis Szeto
Hi Log Up
There would be no effect on other existing positions. The SetHoldings method is actually placing MarketOrder in quantity representing a proportion of the portfolio value for an asset.
If you want to rebalance the portfolio, you could consider
1. Liquidate all positions and use SetHoldings with a list of PortfolioTarget
2. using the Framework and InsightWeightingPortfolioConstructionModel. Active insight weights sum up larger than 1 will rebalance when new insight arrives. This could avoid excessive orders when singular order is desired instead of a whole portfolio change.
Best
Louis
Log Up
HI Louis Szeto , thanks for the reply. Let's say I have SetHoldings with TSLA as 0.1(10%) previously, and in next iteration of OnData I set it to 0.2(20%) of my portfolio, then what will happen in this case?
Louis Szeto
Hi Log Up
For the same asset, it would hold the new set ratio (i.e. 20%). The other assets would not change their existing positions although (they will not automatically rebalance/adjust).
Best
Louis
Sam von Badan
Hi Louis,
thank you for the videos.
I am just a beginner and have watched your videos.
Please I have some questions regarding AddUniverse with CoarseSelectionFunction and FineSelectionFunction
In your videos, you have selected
Coarse: Securities with FundamentalData that have DollarVolume > a certain amount.
But I also want the Filter to include: Industry, segment, etc.
Please how can I add those to my CoarseSelectionFunction?
I am inspired by video #8 and the More Advanced Fundamental Investing bot video in your education series.
Thank you.
Samuel
Ahmed Jaber
Hi Louis,
Thank you for the very helpful videos, indeed this has really allowed me to gain knowledge I previously found to be very difficult, despite trying other tutorials too! Your approach to teaching is outstanding.
I have a question regarding customdata universe, and the use on onSecuritiesChanged function. I am getting this error while backtesting and I am not entirely sure why this is happening:
And this is my line of code:
My csv data looks like this, with hundreds of tickers…:
Any help is highly appreciated!
Best
Louis
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!