{"spec_id":"frontier-efficient","library":"muix","language":"javascript","code":"// anyplot.ai\n// frontier-efficient: Efficient Frontier for Portfolio Optimization\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 86/100 | Updated: 2026-10-24\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"frontier-efficient · javascript · muix · anyplot.ai\";\nconst FRONTIER_LABEL = \"Efficient Frontier\";\nconst CML_LABEL = \"Capital Market Line\";\nconst GMV_LABEL = \"Min-Variance Portfolio\";\nconst TAN_LABEL = \"Max-Sharpe (Tangency) Portfolio\";\nconst RF_LABEL = \"Risk-free rate\";\nconst SHARPE_LOW_LABEL = \"Low Sharpe ratio\";\nconst SHARPE_HIGH_LABEL = \"High Sharpe ratio\";\nconst CML_DASH = \"10,6\";\n\nconst RF_RATE = 0.02;\nconst FRONTIER_R_MAX_MULT = 1.18;\nconst FRONTIER_STEPS = 80;\nconst X_MAX_PAD_MULT = 1.08;\nconst Y_MIN_PAD_SHARE = 0.14;\nconst Y_MAX_PAD_MULT = 1.05;\n\n// Columns: set these to your data's column names\nconst PORTFOLIO_ID = \"Portfolio\";\nconst RISK = \"Portfolio Risk — Annualized Standard Deviation (%)\"; // role: risk\nconst RETURN = \"Expected Portfolio Return — Annualized (%)\"; // role: return\n\n// Data: replace this block with your own records\nconst N_PORTFOLIOS = 300;\nconst ASSET_RETURNS = [0.095, 0.075, 0.11, 0.035, 0.085, 0.045];\nconst ASSET_VOLS = [0.16, 0.18, 0.24, 0.055, 0.19, 0.15];\nconst ASSET_CORR_ROWS = [\n  \"1.00,0.82,0.72,-0.08,0.58,0.02\",\n  \"0.82,1.00,0.78,-0.04,0.52,0.08\",\n  \"0.72,0.78,1.00,-0.12,0.48,0.12\",\n  \"-0.08,-0.04,-0.12,1.00,0.10,0.18\",\n  \"0.58,0.52,0.48,0.10,1.00,0.06\",\n  \"0.02,0.08,0.12,0.18,0.06,1.00\",\n];\n\nconst nAssets = ASSET_RETURNS.length;\nconst covMatrix = ASSET_CORR_ROWS.map((rowStr, i) =>\n  rowStr.split(\",\").map((cStr, j) => Number(cStr) * ASSET_VOLS[i] * ASSET_VOLS[j]),\n);\n\nlet lcgSeed = 7;\nconst data: Record<string, string | number>[] = [];\n\nfor (let k = 0; k < N_PORTFOLIOS; k++) {\n  const expSamples: number[] = [];\n  let weightSum = 0;\n  for (let i = 0; i < nAssets; i++) {\n    lcgSeed = (Math.imul(1664525, lcgSeed) + 1013904223) >>> 0;\n    const u = lcgSeed / 4294967296;\n    const e = -Math.log(1 - u);\n    expSamples.push(e);\n    weightSum += e;\n  }\n  const weights = expSamples.map((e) => e / weightSum);\n  let portRet = 0;\n  let portVar = 0;\n  for (let i = 0; i < nAssets; i++) {\n    portRet += weights[i] * ASSET_RETURNS[i];\n    for (let j = 0; j < nAssets; j++) {\n      portVar += weights[i] * covMatrix[i][j] * weights[j];\n    }\n  }\n  const portRisk = Math.sqrt(Math.max(0, portVar));\n  data.push({\n    [PORTFOLIO_ID]: `p${k}`,\n    [RISK]: portRisk,\n    [RETURN]: portRet,\n  });\n}\n\n// Plot: reads only data and the constants above\nconst augMatrix = covMatrix.map((row, i) => [\n  ...row,\n  ...Array.from({ length: nAssets }, (_, j) => (i === j ? 1 : 0)),\n]);\n\nfor (let col = 0; col < nAssets; col++) {\n  let pivotRow = col;\n  let maxVal = Math.abs(augMatrix[col][col]);\n  for (let r = col + 1; r < nAssets; r++) {\n    if (Math.abs(augMatrix[r][col]) > maxVal) {\n      maxVal = Math.abs(augMatrix[r][col]);\n      pivotRow = r;\n    }\n  }\n  const tmpRow = augMatrix[col];\n  augMatrix[col] = augMatrix[pivotRow];\n  augMatrix[pivotRow] = tmpRow;\n\n  const pivot = augMatrix[col][col];\n  for (let j = 0; j < 2 * nAssets; j++) {\n    augMatrix[col][j] /= pivot;\n  }\n  for (let r = 0; r < nAssets; r++) {\n    if (r === col) continue;\n    const factor = augMatrix[r][col];\n    for (let j = 0; j < 2 * nAssets; j++) {\n      augMatrix[r][j] -= factor * augMatrix[col][j];\n    }\n  }\n}\n\nconst covInv = augMatrix.map((row) => row.slice(nAssets));\nconst invOnes = covInv.map((row) => row.reduce((s, v) => s + v, 0));\nconst invMu = covInv.map((row) => row.reduce((s, v, j) => s + v * ASSET_RETURNS[j], 0));\n\nconst scalarA = invOnes.reduce((s, v) => s + v, 0);\nconst scalarB = invMu.reduce((s, v) => s + v, 0);\nconst scalarC = ASSET_RETURNS.reduce((s, mu_i, i) => s + mu_i * invMu[i], 0);\nconst scalarD = scalarA * scalarC - scalarB * scalarB;\n\nconst rGmv = scalarB / scalarA;\nconst riskGmv = Math.sqrt(1 / scalarA);\n\nconst excessReturns = ASSET_RETURNS.map((m) => m - RF_RATE);\nconst zTan = covInv.map((row) => row.reduce((s, v, j) => s + v * excessReturns[j], 0));\nconst sumZTan = zTan.reduce((a, b) => a + b, 0);\nconst wTan = zTan.map((z) => z / sumZTan);\nconst rTan = wTan.reduce((s, w, i) => s + w * ASSET_RETURNS[i], 0);\nlet varTan = 0;\nfor (let i = 0; i < nAssets; i++) {\n  for (let j = 0; j < nAssets; j++) {\n    varTan += wTan[i] * covMatrix[i][j] * wTan[j];\n  }\n}\nconst riskTan = Math.sqrt(Math.max(0, varTan));\nconst sharpeTan = (rTan - RF_RATE) / riskTan;\n\nconst rFrontierMax = Math.max(...ASSET_RETURNS) * FRONTIER_R_MAX_MULT;\nconst frontierReturns = Array.from(\n  { length: FRONTIER_STEPS },\n  (_, i) => rGmv + ((rFrontierMax - rGmv) * i) / (FRONTIER_STEPS - 1),\n);\nconst frontierRisks = frontierReturns.map((r) =>\n  Math.sqrt(Math.max(0, (scalarA * r * r - 2 * scalarB * r + scalarC) / scalarD)),\n);\n\nconst portfolios = data.map((row) => {\n  const x = Number(row[RISK]);\n  const y = Number(row[RETURN]);\n  const z = (y - RF_RATE) / x;\n  return {\n    id: String(row[PORTFOLIO_ID]),\n    x,\n    y,\n    z,\n  };\n});\n\nconst sharpeVals = portfolios.map((p) => p.z);\nconst sharpeMin = Math.min(...sharpeVals);\nconst sharpeMax = Math.max(...sharpeVals, sharpeTan);\n\nconst xMax = Math.max(riskTan, riskGmv, ...frontierRisks, ...portfolios.map((p) => p.x)) * X_MAX_PAD_MULT;\nconst rawYMin = Math.min(RF_RATE, rGmv, ...portfolios.map((p) => p.y));\nconst rawYMax = Math.max(rFrontierMax, ...portfolios.map((p) => p.y));\nconst yMin = rawYMin - (rawYMax - rawYMin) * Y_MIN_PAD_SHARE;\nconst yMax = rawYMax * Y_MAX_PAD_MULT;\n\nconst cmlXEnd = Math.min(xMax, (yMax - RF_RATE) / sharpeTan);\nconst cmlYEnd = RF_RATE + sharpeTan * cmlXEnd;\nconst cmlLabelX = 0.58 * cmlXEnd;\nconst cmlLabelY = RF_RATE + sharpeTan * cmlLabelX;\n\nfunction FrontierOverlay() {\n  const xScale = useXScale(\"risk\") as (v: number) => number;\n  const yScale = useYScale(\"return\") as (v: number) => number;\n\n  const x1 = xScale(0);\n  const y1 = yScale(RF_RATE);\n  const x2 = xScale(cmlXEnd);\n  const y2 = yScale(cmlYEnd);\n  const xLabel = xScale(cmlLabelX);\n  const yLabel = yScale(cmlLabelY);\n\n  const gmvX = xScale(riskGmv);\n  const gmvY = yScale(rGmv);\n  const tanX = xScale(riskTan);\n  const tanY = yScale(rTan);\n\n  return (\n    <g>\n      {/* Capital Market Line */}\n      <line\n        x1={x1}\n        y1={y1}\n        x2={x2}\n        y2={y2}\n        stroke={t.palette[1]}\n        strokeWidth={2.5}\n        strokeDasharray={CML_DASH}\n      />\n      <text\n        x={xLabel}\n        y={yLabel - 28}\n        textAnchor=\"middle\"\n        fontSize={14}\n        fontWeight={600}\n        fill={t.palette[1]}\n        stroke={t.pageBg}\n        strokeWidth={3.5}\n        paintOrder=\"stroke\"\n      >\n        {CML_LABEL}\n      </text>\n\n      {/* Highlight rings around GMV and Tangency markers */}\n      <circle cx={gmvX} cy={gmvY} r={10} fill={t.ink} stroke={t.pageBg} strokeWidth={2.5} />\n      <text\n        x={gmvX - 14}\n        y={gmvY + 5}\n        textAnchor=\"end\"\n        fontSize={14}\n        fontWeight={600}\n        fill={t.ink}\n        stroke={t.pageBg}\n        strokeWidth={3.5}\n        paintOrder=\"stroke\"\n      >\n        {`GMV (${(riskGmv * 100).toFixed(1)}%, ${(rGmv * 100).toFixed(1)}%)`}\n      </text>\n\n      <circle cx={tanX} cy={tanY} r={10} fill={t.palette[0]} stroke={t.pageBg} strokeWidth={2.5} />\n      <text\n        x={tanX - 14}\n        y={tanY - 12}\n        textAnchor=\"end\"\n        fontSize={14}\n        fontWeight={600}\n        fill={t.ink}\n        stroke={t.pageBg}\n        strokeWidth={3.5}\n        paintOrder=\"stroke\"\n      >\n        {`Max Sharpe = ${sharpeTan.toFixed(2)} (${(riskTan * 100).toFixed(1)}%, ${(rTan * 100).toFixed(1)}%)`}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const headerH = 82;\n  const legendH = 38;\n  const colorbarH = 44;\n  const chartH = height - headerH - legendH - colorbarH;\n  const subtitle = `Mean-variance optimization across ${nAssets} assets · ${data.length} simulated portfolios · rf = ${(RF_RATE * 100).toFixed(1)}%`;\n\n  return (\n    <Box\n      sx={{\n        width,\n        height,\n        background: t.pageBg,\n        display: \"flex\",\n        flexDirection: \"column\",\n        overflow: \"hidden\",\n      }}\n    >\n      <Box sx={{ height: headerH, display: \"flex\", flexDirection: \"column\", justifyContent: \"center\", alignItems: \"center\" }}>\n        <Typography sx={{ fontSize: \"22px\", fontWeight: 600, color: t.ink }}>\n          {TITLE}\n        </Typography>\n        <Typography sx={{ fontSize: \"15px\", color: t.inkSoft, mt: \"2px\" }}>\n          {subtitle}\n        </Typography>\n      </Box>\n\n      {/* Series legend rendered outside the SVG drawing area */}\n      <Box\n        sx={{\n          height: legendH,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: \"28px\",\n        }}\n      >\n        <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}>\n          <svg width={28} height={14}>\n            <line x1={0} y1={7} x2={28} y2={7} stroke={t.ink} strokeWidth={4} />\n          </svg>\n          <Typography sx={{ fontSize: \"14px\", color: t.ink }}>{FRONTIER_LABEL}</Typography>\n        </Box>\n        <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}>\n          <svg width={28} height={14}>\n            <line\n              x1={0}\n              y1={7}\n              x2={28}\n              y2={7}\n              stroke={t.palette[1]}\n              strokeWidth={2.5}\n              strokeDasharray={CML_DASH}\n            />\n          </svg>\n          <Typography sx={{ fontSize: \"14px\", color: t.ink }}>{CML_LABEL}</Typography>\n        </Box>\n        <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}>\n          <svg width={18} height={18}>\n            <circle cx={9} cy={9} r={7} fill={t.ink} stroke={t.pageBg} strokeWidth={1.5} />\n          </svg>\n          <Typography sx={{ fontSize: \"14px\", color: t.ink }}>{GMV_LABEL}</Typography>\n        </Box>\n        <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}>\n          <svg width={18} height={18}>\n            <circle cx={9} cy={9} r={7} fill={t.palette[0]} stroke={t.pageBg} strokeWidth={1.5} />\n          </svg>\n          <Typography sx={{ fontSize: \"14px\", color: t.ink }}>{TAN_LABEL}</Typography>\n        </Box>\n      </Box>\n\n      <ChartsContainer\n        width={width}\n        height={chartH}\n        skipAnimation\n        margin={{ top: 12, right: 48, bottom: 16, left: 20 }}\n        sx={{ '& .MuiLineChart-line[data-series=\"frontier\"]': { strokeWidth: 4 } }}\n        series={[\n          {\n            type: \"line\",\n            id: \"frontier\",\n            data: frontierReturns,\n            xAxisId: \"risk\",\n            yAxisId: \"return\",\n            color: t.ink,\n            showMark: false,\n            curve: \"monotoneX\",\n            label: FRONTIER_LABEL,\n          },\n          {\n            type: \"scatter\",\n            id: \"cloud\",\n            data: portfolios,\n            xAxisId: \"risk\",\n            yAxisId: \"return\",\n            zAxisId: \"sharpe\",\n            markerSize: 5.5,\n          },\n        ]}\n        xAxis={[\n          {\n            id: \"risk\",\n            scaleType: \"linear\",\n            data: frontierRisks,\n            min: 0,\n            max: xMax,\n            height: 54,\n            label: RISK,\n            valueFormatter: (v: number) => `${(v * 100).toFixed(0)}%`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 15, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"return\",\n            min: yMin,\n            max: yMax,\n            width: 84,\n            label: RETURN,\n            valueFormatter: (v: number) => `${(v * 100).toFixed(0)}%`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 15, fill: t.ink },\n          },\n        ]}\n        zAxis={[\n          {\n            id: \"sharpe\",\n            min: sharpeMin,\n            max: sharpeMax,\n            colorMap: {\n              type: \"continuous\",\n              min: sharpeMin,\n              max: sharpeMax,\n              color: [t.seq[0], t.seq[1]],\n            },\n          },\n        ]}\n      >\n        <ChartsGrid horizontal vertical />\n        <ScatterPlot skipAnimation />\n        <LinePlot skipAnimation />\n        <ChartsReferenceLine\n          y={RF_RATE}\n          axisId=\"return\"\n          label={`${RF_LABEL} (${(RF_RATE * 100).toFixed(0)}%)`}\n          labelAlign=\"end\"\n          labelStyle={{ fill: t.inkSoft, fontSize: 14 }}\n          lineStyle={{ stroke: t.inkSoft, strokeDasharray: \"4,4\", strokeWidth: 1.2, opacity: 0.65 }}\n        />\n        <FrontierOverlay />\n        <ChartsXAxis axisId=\"risk\" />\n        <ChartsYAxis axisId=\"return\" />\n      </ChartsContainer>\n\n      <Box\n        sx={{\n          height: colorbarH,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: \"12px\",\n          pb: \"6px\",\n        }}\n      >\n        <Typography sx={{ fontSize: \"14px\", color: t.inkSoft }}>\n          {`${SHARPE_LOW_LABEL} (${sharpeMin.toFixed(2)})`}\n        </Typography>\n        <Box\n          sx={{\n            width: 240,\n            height: 14,\n            borderRadius: \"3px\",\n            background: `linear-gradient(to right, ${t.seq[0]}, ${t.seq[1]})`,\n          }}\n        />\n        <Typography sx={{ fontSize: \"14px\", color: t.inkSoft }}>\n          {`${SHARPE_HIGH_LABEL} (${sharpeMax.toFixed(2)})`}\n        </Typography>\n      </Box>\n    </Box>\n  );\n}\n"}