Generate code in 3 minutes
Enter your idea and AI generates runnable code.
To fix naming errors like securities after the QuantConnect API update, you need to update your code to follow PEP8 standards. QuantConnect has migrated the Python API from C#-style PascalCase to Pythonic snake_case.
Here is the breakdown of the specific changes required to fix your code.
securities fix)Class properties that were previously capitalized must now be lowercase.
Old: self.Securities
New: self.securities
Old: self.Portfolio
New: self.portfolio
Built-in methods provided by QCAlgorithm now use underscores between words.
Old: self.AddEquity("SPY")
New: self.add_equity("SPY")
Old: self.SetCash(100000)
New: self.set_cash(100000)
The definitions of event methods must be updated to snake_case, or the LEAN engine will not call them.
Old: def OnData(self, data):
New: def on_data(self, data):
Old: def Initialize(self):
New: def initialize(self):
Enum members are now generally uppercase.
Old: Resolution.Minute
New: Resolution.MINUTE
Old: SecurityChanges.None
New: SecurityChanges.NONE
Here is a side-by-side comparison of how to refactor a standard algorithm structure.
class OldApiAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2023, 1, 1)
self.SetCash(100000)
self.AddEquity("SPY", Resolution.Minute)
def OnData(self, data):
if not self.Portfolio.Invested:
self.SetHoldings("SPY", 1.0)
# Accessing Securities
price = self.Securities["SPY"].Price
class NewApiAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2023, 1, 1)
self.set_cash(100000)
self.add_equity("SPY", Resolution.MINUTE)
def on_data(self, data):
# Properties are now lowercase
if not self.portfolio.invested:
self.set_holdings("SPY", 1.0)
# Accessing securities (lowercase 's')
price = self.securities["SPY"].price
If you cannot migrate your code immediately, you can revert to the previous engine version in the QuantConnect IDE:
However, it is highly recommended to migrate to the new format as new features will only be added to the PEP8 version.
Q: Why am I getting an AttributeError on self.Securities?
A: The property has been renamed to self.securities (lowercase) to comply with Python PEP8 standards.
Q: Do I need to change my custom variable names?
A: No, you only need to change calls to the QuantConnect API methods and properties. However, be careful not to name your own variables self.securities or self.portfolio, as this will override the built-in API objects.
Q: How do I update Resolution.Daily?
A: Enum constants are now uppercase. You should use Resolution.DAILY.
Q: Is OnData still supported?
A: No, you must rename the method definition to on_data (lowercase with underscore) for the LEAN engine to detect and execute it.