Build, refactor, and explain QuantConnect LEAN algorithms in Python using QCAlgorithm, including data subscriptions, event handlers, scheduling, history, indicators, and order placement. Use when translating strategy logic into QuantConnect's Python API, debugging backtests/live behavior, or implementing core algorithm patterns.
Enable fast, correct construction of QuantConnect LEAN algorithms in Python. Focus on core QCAlgorithm lifecycle, data access, scheduling, indicators, history, and orders (not exhaustive API coverage).
initialize and on_data; store Symbol objects from add_* calls.lean login and lean init in an organization workspace, then into the workspace directory that contains .cdlean.jsonlean project-create --language python "<projectName>" to scaffold a new Python project inside that LEAN workspace.code_version.lean cloud push --project "<projectName>" to push only that project. If the local project's cloud-id is missing or null, the push step creates the cloud project first.lean cloud backtest "<projectName>" --name "<runName>" --open after the push succeeds when you want a human-readable run label in QuantConnect. lean cloud backtest takes the cloud project name or id, not an arbitrary local folder path.lean cloud pull --project "<projectName>" before local work when cloud changes may exist, and use lean cloud push --project "<projectName>" --force when you want the cloud copy updated.python .codex/skills/quant-connect/scripts/bootstrap_research_log.pyscripts/generate_research_id.py so hypothesis_id and experiment_id values are sequential and deterministic.research_log/results/ so they live alongside the hypothesis and experiment logs.python .codex/skills/quant-connect/scripts/extract_backtest_metrics.py <results-json>quantconnect_results, and normalized numeric fields in parsed_metrics.hypothesis_id.templates/hypothesis.md and templates/experiment.md.code_version in the experiment entry.python .codex/skills/quant-connect/scripts/bootstrap_research_log.pypython .codex/skills/quant-connect/scripts/generate_research_id.py hypothesispython .codex/skills/quant-connect/scripts/generate_research_id.py experimentresearch_log/hypotheses/h001.mdresearch_log/experiments/e001.mdresearch_log/hypotheses/.templates/hypothesis.md as the canonical structure for files keyed by hypothesis_id.research_log/experiments/.templates/experiment.md as the canonical structure for files keyed by experiment_id.QCAlgorithm. Use initialize for setup and on_data(self, slice) as the primary data event handler.add_equity (or other add_*) in initialize and store the returned Symbol for later Slice access.self.sma(symbol, period, resolution) for auto-updating indicators; use self.set_warm_up or self.warm_up_indicator so indicators are ready before trading.self.history(...) in initialize or runtime to fetch recent data for features and checks.from AlgorithmImports import *
class MyAlgo(QCAlgorithm):
def initialize(self):
self.set_start_date(2023, 1, 1)
self.set_cash(100000)
self.symbol = self.add_equity("SPY", Resolution.MINUTE).symbol
self.sma = self.sma(self.symbol, 20, Resolution.DAILY)
self.set_warm_up(20, Resolution.DAILY)
def on_data(self, slice: Slice):
if self.is_warming_up:
return
if not slice.contains_key(self.symbol):
return
if self.sma.is_ready and not self.portfolio.invested:
self.market_order(self.symbol, 10)
self.schedule.on(date_rules..., time_rules..., callback) for timed logic.slice.contains_key(symbol) before accessing per-symbol data.slice.bars[symbol] and quote bars via slice.quote_bars[symbol] when present.self.market_order(symbol, quantity) for immediate execution and self.limit_order(symbol, quantity, limit_price) for price-constrained orders.references/quantconnect-python-core.md for quick patterns, doc links, and API nuances.references/CLI.md for a concise LEAN CLI workflow covering project creation, research, sync, backtests, and result review.scripts/bootstrap_research_log.py to initialize the research log directories.scripts/generate_research_id.py for deterministic hypothesis and experiment ids.scripts/extract_backtest_metrics.py to pull the key QuantConnect metrics from a saved results JSON file.examples/basic_buy_and_hold.py: minimal single-asset QCAlgorithm skeleton.examples/sma_crossover.py: indicator-driven long/flat equity strategy.examples/weekly_momentum_rotation.py: scheduled rebalance using recent return ranking.examples/event_aware_expiry_selection.py: choosing valid option expiries around event days and exchange-open checks.examples/scheduled_entry_retry.py: scheduled entry attempts with retry-until-close logic.examples/iron_condor_finder.py: selecting and iteratively tweaking iron condor spreads from an option chain.examples/combo_spread_entry.py: placing a multi-leg combo order and storing trade state for later monitoring.examples/combo_limit_order_manager.py: managing a repriced combo limit order for multi-leg entries.