{"record":{"id":"bc8de576ae1b1b04","repo":"QuantConnect/Lean","slug":"total-profit-expected-sumofdividends-actual","errorCode":null,"errorMessage":"Total Profit: Expected {_sumOfDividends}. Actual {Portfolio.TotalProfit}","messagePattern":"Total Profit: Expected (.+?)\\. Actual (.+?)","errorType":"exception","errorClass":"RegressionTestException","httpStatus":null,"severity":"error","filePath":"Algorithm.CSharp/DividendRegressionAlgorithm.cs","lineNumber":79,"sourceCode":"        /// </summary>\n        /// <param name=\"dividends\">Data.</param>\n        public override void OnDividends(Dividends dividends) // update this to Dividends dictionary\n        {\n            var dividend = dividends[_symbol];\n            var holdings = Portfolio[_symbol];\n            Debug($\"{dividend.Time.ToStringInvariant(\"o\")} >> DIVIDEND >> {dividend.Symbol} - \" +\n                $\"{dividend.Distribution.ToStringInvariant(\"C\")} - {Portfolio.Cash} - \" +\n                $\"{holdings.Price.ToStringInvariant(\"C\")}\"\n            );\n            _sumOfDividends += dividend.Distribution * holdings.Quantity;\n        }\n        \n        public override void OnEndOfAlgorithm()\n        {\n            // The expected value refers to sum of dividend payments\n            if (Portfolio.TotalProfit != _sumOfDividends)\n            {\n                throw new RegressionTestException($\"Total Profit: Expected {_sumOfDividends}. Actual {Portfolio.TotalProfit}\");\n            }\n\n            var expectNetProfit = _sumOfDividends - Portfolio.TotalFees;\n            if (Portfolio.TotalNetProfit != expectNetProfit)\n            {\n                throw new RegressionTestException($\"Total Net Profit: Expected {expectNetProfit}. Actual {Portfolio.TotalNetProfit}\");\n            }\n\n            if (Portfolio[_symbol].TotalDividends != _sumOfDividends)\n            {\n                throw new RegressionTestException($\"{_symbol} Total Dividends: Expected {_sumOfDividends}. Actual {Portfolio[_symbol].TotalDividends}\");\n            }\n        }\n\n        /// <summary>\n        /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.\n        /// </summary>\n        public bool CanRunLocally { get; } = true;","sourceCodeStart":61,"sourceCodeEnd":97,"githubUrl":"https://github.com/QuantConnect/Lean/blob/d2c3659f877bfc2b5d9dc0fc89a9c7566f45e892/Algorithm.CSharp/DividendRegressionAlgorithm.cs#L61-L97","documentation":"OnEndOfAlgorithm asserts Portfolio.TotalProfit equals _sumOfDividends (the accumulated Distribution * holdings.Quantity across all OnDividends calls). Because the algorithm uses DataNormalizationMode.Raw and only holds SPY, all profit should come from dividend cash payments — no price P&L is expected from trading. A mismatch means dividend accounting diverged from realized profit.","triggerScenarios":"TotalProfit includes unexpected trading P&L (e.g., the position was bought/sold at different prices), a dividend distribution was applied but not reflected in cash, or a Lean change in how Raw-mode dividends hit Portfolio.TotalProfit.","commonSituations":"Switching away from DataNormalizationMode.Raw (which changes dividend handling), a Lean version change in dividend cash application, or partial fills / re-entry creating unexpected cost-basis P&L.","solutions":["Confirm AddEquity uses DataNormalizationMode.Raw — other modes factor dividends into price adjustments instead of cash.","Verify SetHoldings is called once and the position is held continuously (no extra trades generating P&L).","Log each dividend Distribution and holdings.Quantity to recompute _sumOfDividends and compare to Portfolio.TotalProfit.","Check for a Lean regression in dividend cash application to Portfolio.TotalProfit."],"exampleFix":null,"handlingStrategy":"validation","validationCode":"public override void OnEndOfAlgorithm()\n{\n    if (Portfolio.TotalProfit != _sumOfDividends)\n    {\n        Debug($\"TotalProfit={Portfolio.TotalProfit} sumOfDividends={_sumOfDividends}\");\n        // check for unexpected trades generating P&L\n        foreach (var t in Transactions.Orders)\n            Debug($\"Order: {t.Key} {t.Value}\");\n    }\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Use DataNormalizationMode.Raw for dividend-cash testing.","Enter the position once and hold; avoid extra trades that generate price P&L.","Log each dividend Distribution and holdings.Quantity to recompute the expected sum."],"tags":["quantconnect","dividends","portfolio","normalization-mode","regression-test"],"backgroundTag":null,"analyzedSha":"d2c3659f877bfc2b5d9dc0fc89a9c7566f45e892","analyzedAt":"2026-08-13T13:52:21.013Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}