diff --git a/AssetManager.Services/PortfolioNavService.cs b/AssetManager.Services/PortfolioNavService.cs index 94b0682..ad010b6 100644 --- a/AssetManager.Services/PortfolioNavService.cs +++ b/AssetManager.Services/PortfolioNavService.cs @@ -394,6 +394,14 @@ public class PortfolioNavService : IPortfolioNavService if (holdings.ContainsKey(tx.StockCode)) { var existing = holdings[tx.StockCode]; + + // 安全检查:防止除零 + if (existing.shares <= 0) + { + holdings.Remove(tx.StockCode); + continue; + } + decimal soldRatio = tx.Amount / existing.shares; decimal remainingShares = existing.shares - tx.Amount; decimal remainingCost = existing.cost * (1 - (decimal)soldRatio); @@ -407,8 +415,11 @@ public class PortfolioNavService : IPortfolioNavService holdings[tx.StockCode] = (remainingShares, remainingCost, existing.currency, existing.assetType); } - // 按比例减少累计投入成本(关键修复:不再用卖出金额) - decimal costToReduce = cumulativeCost * (decimal)soldRatio; + // 按比例减少累计投入成本(修复:使用该标的的成本,而非全局累计成本) + // 先将该标的的成本转换为目标币种 + decimal existingCostInTarget = await _exchangeRateService.ConvertAmountAsync( + existing.cost, existing.currency ?? targetCurrency, targetCurrency); + decimal costToReduce = existingCostInTarget * (decimal)soldRatio; cumulativeCost -= costToReduce; } }