Generate code in 3 minutes
Enter your idea and AI generates runnable code.
To update your old QuantConnect trading script to the new PEP8 API format, you need to transition from C#-style PascalCase to Pythonic snake_case. This involves renaming methods, properties, and event handlers, as well as capitalizing constants.
Below is a guide and a comparison to help you migrate your code.
self.AddEquity $\rightarrow$ self.add_equityself.Portfolio $\rightarrow$ self.portfoliodef Initialize(self): $\rightarrow$ def initialize(self):def OnData(self, data): $\rightarrow$ def on_data(self, data):Resolution.Minute $\rightarrow$ Resolution.MINUTESecurityChanges.None $\rightarrow$ SecurityChanges.NONEManualUniverseSelectionModel remains the same.Here is a side-by-side comparison of a standard algorithm structure.
class OldAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetCash(100000)
self.AddEquity("SPY", Resolution.Minute)
self.spy = self.Securities["SPY"].Symbol
def OnData(self, data):
if not self.Portfolio.Invested:
self.SetHoldings("SPY", 1.0)
self.Debug("Purchased SPY")
class NewAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2020, 1, 1)
self.set_cash(100000)
self.add_equity("SPY", Resolution.MINUTE)
# Note: self.securities is now lowercase
self.spy = self.securities["SPY"].symbol
def on_data(self, data):
# Note: self.portfolio is now lowercase
if not self.portfolio.invested:
self.set_holdings("SPY", 1.0)
self.debug("Purchased SPY")
Variable Name Conflicts
In the old API, it was common to create a custom variable named self.securities to store a list of tickers. In the new API, self.securities is a reserved system property (formerly self.Securities).
self.my_tickers or self.active_securities, to avoid overwriting the system object.Enum Capitalization
Ensure you capitalize the properties of Enums.
Resolution.DailyResolution.DAILYIf you provide your specific script, I can rewrite it for you in the new format immediately. Please paste your code below.
Q: Can I still use the old API format?
A: Yes, but you must select an older version of the LEAN engine (e.g., "master v16356") in your project settings. New projects default to the PEP8 version.
Q: How do I handle private variables in the new format?
A: The new convention encourages using an underscore prefix for private variables (e.g., self._ema instead of self.ema) to distinguish them from public API methods.
Q: Do I need to change class names like QCAlgorithm?
A: No, class names generally remain in CamelCase (e.g., QCAlgorithm, AlphaModel, PortfolioConstructionModel). Only instances, methods, and properties change to snake_case.
Q: What happens if I mix formats?
A: Mixing formats (e.g., calling self.AddEquity in a project set to the new LEAN version) will result in AttributeError because the Python wrapper no longer exposes the PascalCase aliases by default in the new version.