QuantConnect/Lean · error · RegressionTestException

Portfolio should be invested

Error message

Portfolio should be invested

What it means

Asserts Portfolio.Invested is true at algorithm end: the assignment should have left a non-zero stock position. If Invested is false, the stock position is flat/zero, meaning the assignment did not result in a held stock position.

Source

Thrown at Algorithm.CSharp/DuplicateOptionAssignmentRegressionAlgorithm.cs:193

            if (!_optionDelisted)
            {
                throw new RegressionTestException("Option was not delisted");
            }

            if (!_orderCanceled)
            {
                throw new RegressionTestException("Order was not canceled");
            }

            var openOrders = Transactions.GetOpenOrders();
            if (openOrders.Count != 0)
            {
                throw new RegressionTestException("There should be no open orders");
            }

            if (!Portfolio.Invested)
            {
                throw new RegressionTestException("Portfolio should be invested");
            }

            // We should have the stock since the option was assigned
            if (Portfolio.Positions.Groups.Single().Single().Symbol != _stock)
            {
                throw new RegressionTestException("Portfolio should have the stock");
            }
        }

        /// <summary>
        /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
        /// </summary>
        public bool CanRunLocally { get; } = true;

        /// <summary>
        /// This is used by the regression test system to indicate which languages this algorithm is written in.
        /// </summary>
        public List<Language> Languages { get; } = new() { Language.CSharp };

View on GitHub (pinned to d2c3659f87)

Solutions

  1. Check Portfolio[stock].Quantity at end; if zero, trace why assignment did not deliver shares.
  2. Confirm errors 104/105 did not abort first (they gate this invariant).
  3. Verify no auto-liquidation or margin call closed the assigned position.
Defensive patterns

Strategy: validation

Validate before calling

var qty = Portfolio[_stock].Quantity;
if (qty == 0) Log($"Stock position is flat; assignment did not deliver shares (qty={qty})");

Prevention

When it happens

Trigger: The stock position was never opened (assignment failed, see 104/105) or was closed/liquidated by a later step. Quantity rounded to zero due to lot sizing.

Common situations: Assignment quantity zero; position-group modeling cleared the position on delisting; an unintended liquidation ran before end.

Related errors


AI-assisted analysis of QuantConnect/Lean@d2c3659f87 (2026-08-13). Data as JSON: /api/errors/52fd66e1a17fa89f. Report an issue: GitHub.