{"spec_id":"frontier-efficient","library":"highcharts","language":"javascript","code":"// anyplot.ai\n// frontier-efficient: Efficient Frontier for Portfolio Optimization\n// Library: highcharts 12.6.0 | JavaScript 22.23.2\n// Quality: 87/100 | Created: 2026-09-02\n\nconst t = window.ANYPLOT_TOKENS;\n\n// --- Data: simulated 6-asset universe (mean/annualized return, volatility) --\nconst assets = [\n  { name: \"US Equities\", mu: 0.1, sigma: 0.16 },\n  { name: \"Intl Equities\", mu: 0.085, sigma: 0.19 },\n  { name: \"Corporate Bonds\", mu: 0.045, sigma: 0.07 },\n  { name: \"Government Bonds\", mu: 0.03, sigma: 0.05 },\n  { name: \"REITs\", mu: 0.075, sigma: 0.2 },\n  { name: \"Commodities\", mu: 0.05, sigma: 0.22 },\n];\n\n// Fixed correlation matrix (symmetric, unit diagonal)\nconst correlation = [\n  [1.0, 0.75, 0.15, 0.05, 0.55, 0.25],\n  [0.75, 1.0, 0.1, 0.0, 0.5, 0.3],\n  [0.15, 0.1, 1.0, 0.8, 0.2, 0.05],\n  [0.05, 0.0, 0.8, 1.0, 0.1, 0.0],\n  [0.55, 0.5, 0.2, 0.1, 1.0, 0.35],\n  [0.25, 0.3, 0.05, 0.0, 0.35, 1.0],\n];\n\nconst n = assets.length;\nconst covariance = Array.from({ length: n }, (_, i) =>\n  Array.from(\n    { length: n },\n    (_, j) => correlation[i][j] * assets[i].sigma * assets[j].sigma,\n  ),\n);\n\nconst riskFreeRate = 0.02;\n\n// Deterministic LCG PRNG (no seeded RNG available in the browser)\nlet seed = 42;\nfunction rand() {\n  seed = (seed * 1664525 + 1013904223) % 4294967296;\n  return seed / 4294967296;\n}\n\n// Long-only random weights via normalized exponential draws (Dirichlet-like)\nfunction randomWeights() {\n  const draws = Array.from({ length: n }, () => -Math.log(1 - rand()));\n  const total = draws.reduce((a, b) => a + b, 0);\n  return draws.map((d) => d / total);\n}\n\nfunction portfolioReturn(w) {\n  return w.reduce((sum, wi, i) => sum + wi * assets[i].mu, 0);\n}\n\nfunction portfolioRisk(w) {\n  let variance = 0;\n  for (let i = 0; i < n; i++) {\n    for (let j = 0; j < n; j++) {\n      variance += w[i] * w[j] * covariance[i][j];\n    }\n  }\n  return Math.sqrt(variance);\n}\n\nconst PORTFOLIO_COUNT = 400;\nconst portfolios = [];\nfor (let k = 0; k < PORTFOLIO_COUNT; k++) {\n  const w = randomWeights();\n  const risk = portfolioRisk(w);\n  const ret = portfolioReturn(w);\n  const sharpe = (ret - riskFreeRate) / risk;\n  portfolios.push({ risk, ret, sharpe });\n}\n\n// Pareto-efficient upper boundary: sort by risk, keep strictly-increasing return\nconst sortedByRisk = [...portfolios].sort((a, b) => a.risk - b.risk);\nconst frontier = [];\nlet bestReturnSoFar = -Infinity;\nfor (const p of sortedByRisk) {\n  if (p.ret > bestReturnSoFar) {\n    frontier.push(p);\n    bestReturnSoFar = p.ret;\n  }\n}\n\nconst minVariancePortfolio = frontier[0];\nconst maxSharpePortfolio = portfolios.reduce((best, p) =>\n  p.sharpe > best.sharpe ? p : best,\n);\n\n// Capital market line: risk-free rate tangent through the max-Sharpe portfolio\nconst cmlSlope =\n  (maxSharpePortfolio.ret - riskFreeRate) / maxSharpePortfolio.risk;\nconst cmlMaxRisk = frontier[frontier.length - 1].risk * 1.15;\n\n// Color-code the random-portfolio cloud by Sharpe ratio (imprint_seq gradient),\n// returned as an rgba() string so alpha can vary per point.\nfunction lerpHex(a, b, frac, alpha) {\n  const ah = parseInt(a.slice(1), 16);\n  const bh = parseInt(b.slice(1), 16);\n  const ar = (ah >> 16) & 0xff,\n    ag = (ah >> 8) & 0xff,\n    ab = ah & 0xff;\n  const br = (bh >> 16) & 0xff,\n    bg = (bh >> 8) & 0xff,\n    bb = bh & 0xff;\n  const rr = Math.round(ar + (br - ar) * frac);\n  const rg = Math.round(ag + (bg - ag) * frac);\n  const rb = Math.round(ab + (bb - ab) * frac);\n  return `rgba(${rr}, ${rg}, ${rb}, ${alpha})`;\n}\n\nconst sharpeValues = portfolios.map((p) => p.sharpe);\nconst sharpeMin = Math.min(...sharpeValues);\nconst sharpeMax = Math.max(...sharpeValues);\n\n// Risk band where the random-portfolio cloud clumps most densely — thin it\n// out with a smaller radius and lower opacity so the frontier still reads.\nconst DENSE_BAND_MIN = 8;\nconst DENSE_BAND_MAX = 14;\n\nconst cloudData = portfolios.map((p) => {\n  const frac = (p.sharpe - sharpeMin) / (sharpeMax - sharpeMin);\n  const xPct = Number((p.risk * 100).toFixed(2));\n  const inDenseBand = xPct >= DENSE_BAND_MIN && xPct <= DENSE_BAND_MAX;\n  return {\n    x: xPct,\n    y: Number((p.ret * 100).toFixed(2)),\n    sharpe: Number(p.sharpe.toFixed(2)),\n    color: lerpHex(t.seq[0], t.seq[1], frac, inDenseBand ? 0.5 : 0.75),\n    marker: inDenseBand ? { radius: 3 } : undefined,\n  };\n});\n\nconst frontierData = frontier.map((p) => [\n  Number((p.risk * 100).toFixed(2)),\n  Number((p.ret * 100).toFixed(2)),\n]);\n\nconst cmlData = [\n  [0, riskFreeRate * 100],\n  [\n    Number((cmlMaxRisk * 100).toFixed(2)),\n    Number(((riskFreeRate + cmlSlope * cmlMaxRisk) * 100).toFixed(2)),\n  ],\n];\n\n// --- Chart -------------------------------------------------------------\nHighcharts.chart(\"container\", {\n  chart: {\n    type: \"scatter\",\n    backgroundColor: \"transparent\",\n    animation: false,\n    style: { fontFamily: \"inherit\" },\n  },\n  credits: { enabled: false },\n  colors: t.palette,\n  title: {\n    text: \"frontier-efficient · javascript · highcharts · anyplot.ai\",\n    style: { color: t.ink, fontSize: \"22px\", fontWeight: \"600\" },\n  },\n  subtitle: {\n    text: `Simulated 6-asset universe · point color encodes Sharpe ratio (${sharpeMin.toFixed(2)} low → ${sharpeMax.toFixed(2)} high)`,\n    style: { color: t.inkSoft, fontSize: \"14px\" },\n  },\n  xAxis: {\n    title: {\n      text: \"Risk (Annualized Std. Dev., %)\",\n      style: { color: t.inkSoft, fontSize: \"16px\" },\n    },\n    min: 0,\n    lineColor: t.inkSoft,\n    tickColor: t.inkSoft,\n    gridLineColor: t.grid,\n    gridLineWidth: 1,\n    labels: {\n      style: { color: t.inkSoft, fontSize: \"14px\" },\n      format: \"{value}%\",\n    },\n  },\n  yAxis: {\n    title: {\n      text: \"Expected Return (Annualized, %)\",\n      style: { color: t.inkSoft, fontSize: \"16px\" },\n    },\n    min: 0,\n    lineColor: t.inkSoft,\n    tickColor: t.inkSoft,\n    gridLineColor: t.grid,\n    labels: {\n      style: { color: t.inkSoft, fontSize: \"14px\" },\n      format: \"{value}%\",\n    },\n  },\n  legend: {\n    enabled: true,\n    itemStyle: { color: t.inkSoft, fontSize: \"14px\" },\n    itemHoverStyle: { color: t.ink },\n  },\n  tooltip: {\n    backgroundColor: t.elevatedBg,\n    style: { color: t.ink },\n    pointFormatter: function () {\n      const sharpe =\n        this.sharpe !== undefined ? `<br/>Sharpe: ${this.sharpe}` : \"\";\n      return `Risk: ${this.x}%<br/>Return: ${this.y}%${sharpe}`;\n    },\n  },\n  plotOptions: {\n    series: { animation: false },\n    scatter: { marker: { radius: 4, lineWidth: 0 } },\n  },\n  series: [\n    {\n      name: \"Simulated portfolios\",\n      type: \"scatter\",\n      data: cloudData,\n      marker: { radius: 4 },\n      showInLegend: false,\n    },\n    {\n      name: \"Efficient frontier\",\n      type: \"spline\",\n      data: frontierData,\n      color: t.palette[0],\n      lineWidth: 3.5,\n      marker: { enabled: false },\n      zIndex: 3,\n    },\n    {\n      name: \"Capital market line\",\n      type: \"line\",\n      data: cmlData,\n      color: t.palette[3],\n      dashStyle: \"Dash\",\n      lineWidth: 2.5,\n      marker: { enabled: false },\n      zIndex: 2,\n    },\n    {\n      name: \"Minimum variance portfolio\",\n      type: \"scatter\",\n      data: [\n        {\n          x: Number((minVariancePortfolio.risk * 100).toFixed(2)),\n          y: Number((minVariancePortfolio.ret * 100).toFixed(2)),\n        },\n      ],\n      color: t.palette[1],\n      marker: { symbol: \"triangle\", radius: 9, lineColor: t.ink, lineWidth: 1 },\n      dataLabels: {\n        enabled: true,\n        format: \"Min Variance\",\n        y: 26,\n        style: {\n          color: t.ink,\n          fontSize: \"14px\",\n          textOutline: \"none\",\n          fontWeight: \"600\",\n        },\n      },\n      zIndex: 4,\n    },\n    {\n      name: \"Max Sharpe (tangency) portfolio\",\n      type: \"scatter\",\n      data: [\n        {\n          x: Number((maxSharpePortfolio.risk * 100).toFixed(2)),\n          y: Number((maxSharpePortfolio.ret * 100).toFixed(2)),\n        },\n      ],\n      color: t.palette[2],\n      marker: { symbol: \"diamond\", radius: 9, lineColor: t.ink, lineWidth: 1 },\n      dataLabels: {\n        enabled: true,\n        format: \"Max Sharpe\",\n        y: -20,\n        style: {\n          color: t.ink,\n          fontSize: \"14px\",\n          textOutline: \"none\",\n          fontWeight: \"600\",\n        },\n      },\n      zIndex: 4,\n    },\n  ],\n});\n"}