{"spec_id":"heatmap-loss-triangle","library":"muix","language":"javascript","code":"// anyplot.ai\n// heatmap-loss-triangle: Actuarial Loss Development Triangle\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/100 | Updated: 2026-10-24\n//# anyplot-orientation: square\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst SIZE = window.ANYPLOT_SIZE;\nconst TITLE = \"heatmap-loss-triangle · javascript · muix · anyplot.ai\";\nconst CELL_TEXT_ON_LIGHT_FILL = \"#1A1A17\";\nconst CELL_TEXT_ON_DARK_FILL = \"#FAF8F1\";\nconst HATCH_ID = \"loss-triangle-hatch\";\nconst GRAD_ID = \"loss-triangle-seq-grad\";\nconst COLORBAR_TICKS = [0, 0.25, 0.5, 0.75, 1];\n\n// Columns: set these to your data's column names\nconst ACCIDENT_YEAR = \"Accident Year\"; // role: accident_year\nconst DEV_PERIOD = \"Development Period (years since occurrence)\"; // role: development_period\nconst CUMULATIVE_CLAIMS = \"Cumulative paid claims ($000s)\"; // role: cumulative_amount\nconst IS_PROJECTED = \"Projected\"; // role: is_projected\nconst DEV_FACTOR = \"Age-to-age factor\"; // role: development_factor\n\n// Data: replace this block with your own records\nconst SEED_YEARS = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024];\nconst SEED_FACTORS = [1.45, 1.2, 1.12, 1.07, 1.045, 1.028, 1.017, 1.01, 1.005, 1.0];\n\ntype LossTriangleRow = {\n  [ACCIDENT_YEAR]: number;\n  [DEV_PERIOD]: number;\n  [CUMULATIVE_CLAIMS]: number;\n  [IS_PROJECTED]: number;\n  [DEV_FACTOR]: number;\n};\n\nlet lcgState = 42;\nconst nextRand = () => {\n  lcgState = (lcgState * 1103515245 + 12345) & 0x7fffffff;\n  return lcgState / 0x7fffffff;\n};\nconst nPeriods = SEED_FACTORS.length;\nconst nYears = SEED_YEARS.length;\n\n// Observed triangle: each year's link ratios scatter around the seed factors\nconst grid: number[][] = SEED_YEARS.map((_, i) => {\n  const row = [Math.round(820 + i * 35 + (nextRand() - 0.5) * 60)];\n  for (let j = 1; j < nPeriods - i; j++) {\n    const growth = SEED_FACTORS[j - 1] - 1;\n    const noisy = 1 + growth * (1 + (nextRand() - 0.5) * 0.5);\n    row.push(Math.round(row[j - 1] * noisy));\n  }\n  return row;\n});\n\n// Chain-ladder: volume-weighted age-to-age factors from the observed cells\nconst selectedFactors = SEED_FACTORS.map((seed, j) => {\n  let num = 0;\n  let den = 0;\n  for (const row of grid) {\n    if (row.length > j + 1) {\n      num += row[j + 1];\n      den += row[j];\n    }\n  }\n  return den > 0 ? num / den : seed;\n});\n\nconst data: LossTriangleRow[] = [];\nfor (let i = 0; i < nYears; i++) {\n  const observedCount = grid[i].length;\n  let cumulative = grid[i][0];\n  for (let j = 0; j < nPeriods; j++) {\n    if (j > 0) {\n      cumulative = j < observedCount ? grid[i][j] : cumulative * selectedFactors[j - 1];\n    }\n    data.push({\n      [ACCIDENT_YEAR]: SEED_YEARS[i],\n      [DEV_PERIOD]: j + 1,\n      [CUMULATIVE_CLAIMS]: Math.round(cumulative),\n      [IS_PROJECTED]: j < observedCount ? 0 : 1,\n      [DEV_FACTOR]: selectedFactors[j],\n    });\n  }\n}\n\n// Plot: reads only data and the constants above\nconst accidentYearNums = Array.from(\n  new Set(data.map((r) => r[ACCIDENT_YEAR])),\n).sort((a, b) => a - b);\nconst devPeriodNums = Array.from(\n  new Set(data.map((r) => r[DEV_PERIOD])),\n).sort((a, b) => a - b);\n\nconst accidentYearLabels = accidentYearNums.map(String);\nconst devPeriodLabels = devPeriodNums.map(String);\n\nconst factorByPeriod = new Map<number, number>();\nfor (const row of data) {\n  const p = row[DEV_PERIOD];\n  if (!factorByPeriod.has(p)) {\n    factorByPeriod.set(p, row[DEV_FACTOR]);\n  }\n}\n\nconst maxObsPeriodIdxByYear = new Map<number, number>();\nfor (const year of accidentYearNums) {\n  const obsPeriods = data\n    .filter((r) => r[ACCIDENT_YEAR] === year && r[IS_PROJECTED] === 0)\n    .map((r) => r[DEV_PERIOD]);\n  const maxP = Math.max(...obsPeriods);\n  maxObsPeriodIdxByYear.set(year, devPeriodNums.indexOf(maxP));\n}\n\nconst allAmounts = data.map((r) => r[CUMULATIVE_CLAIMS]);\nconst minVal = Math.min(...allAmounts);\nconst maxVal = Math.max(...allAmounts);\nconst valSpan = maxVal - minVal;\n\nconst seqLowNum = parseInt(t.seq[0].slice(1), 16);\nconst seqHighNum = parseInt(t.seq[1].slice(1), 16);\nconst lowR = (seqLowNum >> 16) & 255;\nconst lowG = (seqLowNum >> 8) & 255;\nconst lowB = seqLowNum & 255;\nconst highR = (seqHighNum >> 16) & 255;\nconst highG = (seqHighNum >> 8) & 255;\nconst highB = seqHighNum & 255;\n\nconst cells = data.map((row) => {\n  const val = row[CUMULATIVE_CLAIMS];\n  const ratio = (val - minVal) / valSpan;\n  const r = Math.round(lowR + (highR - lowR) * ratio);\n  const g = Math.round(lowG + (highG - lowG) * ratio);\n  const b = Math.round(lowB + (highB - lowB) * ratio);\n  const lum = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;\n  return {\n    id: `${row[ACCIDENT_YEAR]}-${row[DEV_PERIOD]}`,\n    yearKey: String(row[ACCIDENT_YEAR]),\n    periodKey: String(row[DEV_PERIOD]),\n    value: val,\n    isProjected: row[IS_PROJECTED] === 1,\n    fill: `rgb(${r}, ${g}, ${b})`,\n    textFill: lum > 0.54 ? CELL_TEXT_ON_LIGHT_FILL : CELL_TEXT_ON_DARK_FILL,\n  };\n});\n\nconst latestYear = accidentYearNums[accidentYearNums.length - 1];\nlet totalIbnr = 0;\nfor (const year of accidentYearNums) {\n  const yearRows = data.filter((r) => r[ACCIDENT_YEAR] === year);\n  const observedRows = yearRows.filter((r) => r[IS_PROJECTED] === 0);\n  const latestObserved = observedRows[observedRows.length - 1][CUMULATIVE_CLAIMS];\n  const ultimate = yearRows[yearRows.length - 1][CUMULATIVE_CLAIMS];\n  totalIbnr += ultimate - latestObserved;\n}\n\nconst unitMatch = CUMULATIVE_CLAIMS.match(/\\(([^)]+)\\)/);\nconst claimsUnit = unitMatch ? unitMatch[1] : \"\";\nconst claimsName = CUMULATIVE_CLAIMS.replace(/\\s*\\([^)]*\\)/, \"\");\nconst subtitle = `${ACCIDENT_YEAR}s ${accidentYearNums[0]}–${latestYear} · ${CUMULATIVE_CLAIMS} · Total projected IBNR reserve: ${totalIbnr.toLocaleString(\"en-US\")} (${claimsUnit})`;\n\nfunction LossTriangleLayer() {\n  const area = useDrawingArea();\n  const xScale = useXScale(\"dev-period\") as unknown as ((v: string) => number) & { bandwidth: () => number };\n  const yScale = useYScale(\"accident-year\") as unknown as ((v: string) => number) & { bandwidth: () => number };\n\n  const bw = xScale.bandwidth();\n  const bh = yScale.bandwidth();\n  const stepX = xScale(devPeriodLabels[1]) - xScale(devPeriodLabels[0]);\n  const stepY = yScale(accidentYearLabels[1]) - yScale(accidentYearLabels[0]);\n\n  const staircasePts: string[] = [];\n  let prevXRight = xScale(devPeriodLabels[devPeriodLabels.length - 1]) + bw;\n  for (let i = 0; i < accidentYearNums.length; i++) {\n    const year = accidentYearNums[i];\n    const maxObsIdx = maxObsPeriodIdxByYear.get(year)!;\n    if (maxObsIdx < devPeriodLabels.length - 1) {\n      const xRight = xScale(devPeriodLabels[maxObsIdx]) + bw + (stepX - bw) / 2;\n      const yTop = yScale(accidentYearLabels[i]) - (stepY - bh) / 2;\n      const yBot = yScale(accidentYearLabels[i]) + bh + (stepY - bh) / 2;\n      if (staircasePts.length === 0) {\n        staircasePts.push(`M ${prevXRight} ${yTop}`);\n      }\n      staircasePts.push(`L ${xRight} ${yTop}`);\n      staircasePts.push(`L ${xRight} ${yBot}`);\n      prevXRight = xRight;\n    } else {\n      prevXRight = xScale(devPeriodLabels[maxObsIdx]) + bw;\n    }\n  }\n  const staircasePath = staircasePts.join(\" \");\n\n  const factorRowY = area.top + area.height + 92;\n  const barX = area.left + area.width + 28;\n  const barW = 18;\n  const barTop = area.top + area.height * 0.12;\n  const barH = area.height * 0.78;\n\n  return (\n    <g>\n      <defs>\n        <pattern\n          id={HATCH_ID}\n          width={8}\n          height={8}\n          patternUnits=\"userSpaceOnUse\"\n          patternTransform=\"rotate(45)\"\n        >\n          <line\n            x1={0}\n            y1={0}\n            x2={0}\n            y2={8}\n            stroke={t.ink}\n            strokeWidth={2}\n            strokeOpacity={0.24}\n          />\n        </pattern>\n        <linearGradient id={GRAD_ID} x1=\"0\" y1=\"1\" x2=\"0\" y2=\"0\">\n          <stop offset=\"0%\" stopColor={t.seq[0]} />\n          <stop offset=\"100%\" stopColor={t.seq[1]} />\n        </linearGradient>\n      </defs>\n\n      <text\n        x={SIZE.width / 2}\n        y={42}\n        textAnchor=\"middle\"\n        fontSize={22}\n        fontWeight=\"600\"\n        fill={t.ink}\n      >\n        {TITLE}\n      </text>\n      <text\n        x={SIZE.width / 2}\n        y={70}\n        textAnchor=\"middle\"\n        fontSize={15}\n        fill={t.inkSoft}\n      >\n        {subtitle}\n      </text>\n\n      {/* Legend swatches: Actual vs Projected */}\n      <g transform={`translate(${SIZE.width / 2 - 225}, 96)`}>\n        <rect\n          x={0}\n          y={0}\n          width={20}\n          height={20}\n          rx={3}\n          fill={t.seq[0]}\n          stroke={t.pageBg}\n          strokeWidth={1.5}\n        />\n        <text\n          x={28}\n          y={15}\n          fontSize={14}\n          fontWeight=\"600\"\n          fill={t.ink}\n        >\n          Actual (observed claims)\n        </text>\n\n        <rect\n          x={235}\n          y={0}\n          width={20}\n          height={20}\n          rx={3}\n          fill={t.seq[0]}\n          stroke={t.inkSoft}\n          strokeWidth={1.5}\n          strokeDasharray=\"4 2\"\n        />\n        <rect\n          x={235}\n          y={0}\n          width={20}\n          height={20}\n          rx={3}\n          fill={`url(#${HATCH_ID})`}\n        />\n        <text\n          x={263}\n          y={15}\n          fontSize={14}\n          fontWeight=\"600\"\n          fill={t.ink}\n        >\n          Projected (chain-ladder IBNR)\n        </text>\n      </g>\n\n      {/* Triangle cells */}\n      {cells.map((cell) => {\n        const x = xScale(cell.periodKey);\n        const y = yScale(cell.yearKey);\n        return (\n          <g key={cell.id}>\n            <rect\n              x={x}\n              y={y}\n              width={bw}\n              height={bh}\n              fill={cell.fill}\n              rx={4}\n              stroke={cell.isProjected ? t.inkSoft : t.pageBg}\n              strokeWidth={cell.isProjected ? 1.5 : 2}\n              strokeDasharray={cell.isProjected ? \"4 3\" : undefined}\n            />\n            {cell.isProjected && (\n              <rect\n                x={x}\n                y={y}\n                width={bw}\n                height={bh}\n                fill={`url(#${HATCH_ID})`}\n                rx={4}\n              />\n            )}\n            <text\n              x={x + bw / 2}\n              y={y + bh / 2}\n              textAnchor=\"middle\"\n              dominantBaseline=\"central\"\n              fontSize={14}\n              fontWeight=\"600\"\n              fill={cell.textFill}\n            >\n              {cell.value.toLocaleString(\"en-US\")}\n            </text>\n          </g>\n        );\n      })}\n\n      {/* Latest evaluation diagonal boundary */}\n      <path\n        d={staircasePath}\n        fill=\"none\"\n        stroke={t.ink}\n        strokeWidth={2.5}\n      />\n\n      {/* Age-to-age development factors row below the x-axis */}\n      <text\n        x={area.left}\n        y={factorRowY}\n        textAnchor=\"end\"\n        dominantBaseline=\"central\"\n        fontSize={14}\n        fontWeight=\"600\"\n        fill={t.inkSoft}\n      >\n        {DEV_FACTOR}\n      </text>\n      {devPeriodNums.slice(0, -1).map((period, k) => {\n        const nextPeriod = devPeriodNums[k + 1];\n        const factor = factorByPeriod.get(period)!;\n        const xLeft = xScale(String(period)) + bw;\n        const xRight = xScale(String(nextPeriod));\n        const boundaryX = (xLeft + xRight) / 2;\n        return (\n          <text\n            key={`factor-${period}`}\n            x={boundaryX}\n            y={factorRowY}\n            textAnchor=\"middle\"\n            dominantBaseline=\"central\"\n            fontSize={14}\n            fontWeight=\"600\"\n            fill={t.inkSoft}\n          >\n            {`×${factor.toFixed(2)}`}\n          </text>\n        );\n      })}\n\n      {/* Sequential Colorbar */}\n      <text\n        x={barX}\n        y={barTop - 30}\n        textAnchor=\"start\"\n        fontSize={14}\n        fontWeight=\"600\"\n        fill={t.ink}\n      >\n        {claimsName}\n      </text>\n      <text\n        x={barX}\n        y={barTop - 12}\n        textAnchor=\"start\"\n        fontSize={14}\n        fill={t.inkSoft}\n      >\n        {`(${claimsUnit})`}\n      </text>\n      <rect\n        x={barX}\n        y={barTop}\n        width={barW}\n        height={barH}\n        fill={`url(#${GRAD_ID})`}\n        stroke={t.grid}\n        strokeWidth={1}\n        rx={3}\n      />\n      {COLORBAR_TICKS.map((frac) => {\n        const val = Math.round(minVal + frac * valSpan);\n        const ty = barTop + barH * (1 - frac);\n        return (\n          <g key={frac}>\n            <line\n              x1={barX + barW}\n              y1={ty}\n              x2={barX + barW + 6}\n              y2={ty}\n              stroke={t.inkSoft}\n              strokeWidth={1}\n            />\n            <text\n              x={barX + barW + 10}\n              y={ty + 5}\n              fontSize={14}\n              fill={t.inkSoft}\n            >\n              {val.toLocaleString(\"en-US\")}\n            </text>\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  return (\n    <ChartsContainer\n      width={SIZE.width}\n      height={SIZE.height}\n      series={[]}\n      margin={{ top: 138, right: 210, bottom: 64, left: 74 }}\n      skipAnimation\n      xAxis={[\n        {\n          id: \"dev-period\",\n          scaleType: \"band\",\n          data: devPeriodLabels,\n          categoryGapRatio: 0.06,\n          height: 58,\n          label: DEV_PERIOD,\n          disableLine: true,\n          disableTicks: true,\n          tickLabelStyle: { fontSize: 14, fill: t.inkSoft, fontWeight: 600 },\n          labelStyle: { fontSize: 15, fill: t.ink },\n        },\n      ]}\n      yAxis={[\n        {\n          id: \"accident-year\",\n          scaleType: \"band\",\n          data: accidentYearLabels,\n          categoryGapRatio: 0.06,\n          width: 82,\n          label: ACCIDENT_YEAR,\n          disableLine: true,\n          disableTicks: true,\n          tickLabelStyle: { fontSize: 14, fill: t.inkSoft, fontWeight: 600 },\n          labelStyle: { fontSize: 15, fill: t.ink },\n        },\n      ]}\n    >\n      <LossTriangleLayer />\n      <ChartsXAxis axisId=\"dev-period\" />\n      <ChartsYAxis axisId=\"accident-year\" />\n    </ChartsContainer>\n  );\n}\n"}