| name | code-quality |
| description | Use when writing, reviewing, or refactoring QuantConnect/LEAN algorithm code for style correctness. Triggers: new algorithm code, code review, cleanup, "fix code style", "review code quality", "clean up the algorithm", redundant imports, subscription variable usage, comment format, blank-line rules, multi-line boolean layout, or catch-all error handling. Skip when only debugging runtime behavior or performance, unless the fix also changes style.
|
QuantConnect Algorithm Code Quality
Apply these rules to main.py and custom data classes. The goal is compiling code that does not hide real failures.
Imports
Use AlgorithmImports for LEAN APIs and common algorithm types. Do not add redundant imports for datetime, timedelta, date, pandas, numpy, or math. Put required standard library imports before AlgorithmImports, separated by one blank line.
Subscription Variables
Store the Security returned by add_data, add_equity, or add_crypto. Pass that Security directly anywhere a Symbol is expected; do not store or use .symbol.
self._custom_symbol = self.add_data(MyData, "TICKER").symbol
data[self._custom_btc.symbol]
self._custom_btc = self.add_data(MyData, "TICKER")
if self._custom_btc not in data:
return
bar = data[self._custom_btc]
Use x in data and x not in data, not data.contains_key(x).
Comments
Follow PEP 8: block comments start with # , use complete sentences, start sentences with capitals, and end sentences with periods. Inline comments are rare, separated from code by at least two spaces, and start with # .
x = price*quantity
x = price * quantity
Multi-Line Boolean Expressions
Put and/or at the end of each continued line.
if (
close > ema_fast
and open_ > ema_fast
and rsi > 50):
return
if (close > ema_fast and
open_ > ema_fast and
rsi > 50):
return
Blank Lines
Use two blank lines before top-level classes, one blank line before methods inside classes, and no blank lines inside method bodies.
Error Handling
Do not wrap algorithm logic in try / except blocks. Exceptions reveal invalid state, missing data, and incorrect assumptions; catch-all handlers make bugs invisible.
try:
self.set_holdings(self._spy, target_weight)
except Exception:
pass
if target_weight:
self.set_holdings(self._spy, target_weight)
Checklist
- Standard library imports precede AlgorithmImports.
- Stored subscription variables are Security objects, not .symbol values.
- Comments follow language-specific rules.
- Multi-line boolean expressions follow language-specific continuation style.
- Blank lines match language rules.
- Algorithm code has no
try / except; it uses explicit guards for expected conditions.