aggregate_api 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- aggregate_api/__init__.py +41 -0
- aggregate_api/__main__.py +154 -0
- aggregate_api/app.py +206 -0
- aggregate_api/audit.py +395 -0
- aggregate_api/bounds.py +331 -0
- aggregate_api/cache.py +319 -0
- aggregate_api/capability.py +823 -0
- aggregate_api/completion.py +219 -0
- aggregate_api/config.py +363 -0
- aggregate_api/cors.py +61 -0
- aggregate_api/examples.py +620 -0
- aggregate_api/layer_pricing.py +840 -0
- aggregate_api/library.py +94 -0
- aggregate_api/library_notes.py +96 -0
- aggregate_api/models.py +1407 -0
- aggregate_api/net.py +281 -0
- aggregate_api/pnl.py +101 -0
- aggregate_api/pricing.py +778 -0
- aggregate_api/resources.py +257 -0
- aggregate_api/routes/__init__.py +8 -0
- aggregate_api/routes/decl.py +327 -0
- aggregate_api/routes/examples.py +82 -0
- aggregate_api/routes/meta.py +282 -0
- aggregate_api/routes/objects.py +4119 -0
- aggregate_api/routes/status.py +466 -0
- aggregate_api/serializers.py +565 -0
- aggregate_api/sessions.py +353 -0
- aggregate_api/static/aggregate-api-logo-512.png +0 -0
- aggregate_api/static/aggregate-api-logo.png +0 -0
- aggregate_api/static/aggregate-api-trim.png +0 -0
- aggregate_api/static/android-chrome-192x192.png +0 -0
- aggregate_api/static/android-chrome-512x512.png +0 -0
- aggregate_api/static/apple-touch-icon.png +0 -0
- aggregate_api/static/assets/bootstrap-icons-BeopsB42.woff +0 -0
- aggregate_api/static/assets/bootstrap-icons-mSm7cUeB.woff2 +0 -0
- aggregate_api/static/assets/bootstrap-ohb1VZ53.js +5 -0
- aggregate_api/static/assets/codemirror-h62DHGGa.js +14 -0
- aggregate_api/static/assets/csv-grid.worker-DKzHGXac.js +4 -0
- aggregate_api/static/assets/echarts-B7o9sc00.js +40 -0
- aggregate_api/static/assets/echarts-gl-DG1Uf6wE.js +4282 -0
- aggregate_api/static/assets/lite-CUlcD8p4.css +1 -0
- aggregate_api/static/assets/lite-Dd2TnT4M.js +1 -0
- aggregate_api/static/assets/main-Bxhxa55v.css +9 -0
- aggregate_api/static/assets/main-CmoEiPit.js +9 -0
- aggregate_api/static/assets/tables-BHCF7qIF.js +8 -0
- aggregate_api/static/assets/tables-CxvajLr7.css +1 -0
- aggregate_api/static/favicon-16x16.png +0 -0
- aggregate_api/static/favicon-32x32.png +0 -0
- aggregate_api/static/favicon.ico +0 -0
- aggregate_api/static/index.html +912 -0
- aggregate_api/static/lite.html +83 -0
- aggregate_api/static/logo.png +0 -0
- aggregate_api/static/site.webmanifest +14 -0
- aggregate_api/static/sw.js +78 -0
- aggregate_api/status.py +536 -0
- aggregate_api/status_page.html +546 -0
- aggregate_api/tables.py +316 -0
- aggregate_api-1.0.0.dist-info/METADATA +187 -0
- aggregate_api-1.0.0.dist-info/RECORD +63 -0
- aggregate_api-1.0.0.dist-info/WHEEL +5 -0
- aggregate_api-1.0.0.dist-info/entry_points.txt +2 -0
- aggregate_api-1.0.0.dist-info/licenses/LICENSE +28 -0
- aggregate_api-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{g as P,f as s,a as b,h as Jn,$ as u,o as si,r as ri,l as li,t as ci,w as ln,A as Lt,j as Z,n as cn,s as ke,c as ct,v as ui,d as di,m as Tt,i as Bt,e as pi,b as fi,q as mi,p as hi,k as gi}from"./tables-BHCF7qIF.js";import{a as un,O as bi,D as ea,T as vi}from"./bootstrap-ohb1VZ53.js";import{S as yi,a as ze,o as en,b as wi,E as Mn,p as xi,k as Ci,l as $i,d as Li,i as ki,j as Ni,C as ta,q as Ei,c as Si,g as Pi,m as Ai,e as _i,s as Ti,n as Bi,h as Fi,A as Mi,f as Ri}from"./codemirror-h62DHGGa.js";import"./echarts-B7o9sc00.js";function Ft(e,t){let n=null;return(...a)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{n=null,e(...a)},t)}}const Di=[["p","p","a VaR probability in (0, 1]"],["a","assets","an asset level, snapped to the grid"]],Ot=[["coc","CoC","0.15","cost of capital, the pentagon’s ROE"],["lr","LR","0.9","loss ratio"],["premium","Premium",null,"the premium itself"]];let yt=(()=>{try{return localStorage.getItem("aggapi.priceBasis")||"gross"}catch{return"gross"}})(),Te=null;const qi=[["gross","Gross"],["net occ","Net occ"],["net","Net"]];function ut(e,t){const{verb:n,onSubmit:a,basisLabel:i=null,targets:o=Ot.map(f=>f[0]),preview:r=!1,allowBlank:l=!1,help:p=null,extras:d=null,expense:g=!1,basisOnly:m=null,basisWhy:L=null,context:v,onChange:$=null}=t;P(e);const C=s("div",{className:"tab-tools price-form"}),A=f=>s("span",{className:"qr-op"},f),D=f=>s("span",{className:"qr-op price-punct"},f);C.appendChild(A(i?i[0].toUpperCase()+i.slice(1):`${n} at`));const ye=s("span",{className:"price-basis"});i&&(C.appendChild(ye),C.appendChild(D(",")));const N=s("input",{type:"number",step:"0.001",min:"0",max:"1",value:"0.99",autocomplete:"off"}),O=s("div",{className:"btn-group btn-group-sm",role:"group"});O.setAttribute("aria-label","capital anchor"),l&&(N.placeholder="none");const He=s("label",{className:"price-field"},N);C.appendChild(He),C.appendChild(O),C.appendChild(D(",")),g||C.appendChild(A("and"));const V=s("input",{type:"number",step:"0.01",value:"0.15",autocomplete:"off"}),ae=s("div",{className:"btn-group btn-group-sm",role:"group"});ae.setAttribute("aria-label","pricing target");const Ge=s("label",{className:"price-field"},V);C.appendChild(Ge),C.appendChild(ae);let T=null;g&&(C.appendChild(D(",")),C.appendChild(A("and")),T=s("input",{type:"number",step:"0.01",min:"0",max:"0.99",value:Te!=null?String(Te):"0",autocomplete:"off"}),C.appendChild(s("label",{className:"price-field"},T)),C.appendChild(s("span",{className:"price-unit"},"expense ratio"))),C.appendChild(D("."));const le=s("button",{className:"btn btn-primary btn-sm"},n);C.appendChild(le),p&&C.appendChild(s("button",{type:"button",className:"qr-help",title:p,"aria-label":`how ${n} reads these boxes`},"?")),e.appendChild(C),d&&e.appendChild(d);const W=r?s("p",{className:"price-preview"}):null;W&&e.appendChild(W);let J="p",x=o.includes("coc")?"coc":o[0],B=!1;function we(f,y,F,S){P(f);for(const[Y,_e,oe,w]of y){const U=s("button",{type:"button",title:oe,className:"btn btn-outline-secondary"+(Y===F&&!w?" active":"")},_e);w||B?(U.disabled=!0,w&&U.setAttribute("aria-label",`${_e}, ${oe}`)):U.addEventListener("click",()=>S(Y)),f.appendChild(U)}}function ie(){we(O,Di,J,f=>{if(f===J)return;J=f;const y=J==="p";N.step=y?"0.001":"1",y?N.max="1":N.removeAttribute("max"),N.value=y?"0.99":"",ie(),y||N.focus(),Ae()})}function Se(){const f=Ot.filter(y=>o.includes(y[0])).map(([y,F,,S])=>[y,F,S]);if(f.length<2){P(ae),ae.appendChild(s("span",{className:"price-unit"},f[0]?.[1]||""));return}we(ae,f,x,y=>{if(y===x)return;x=y;const F=Ot.find(S=>S[0]===y)?.[2];F!=null&&(V.value=F),V.step=y==="premium"?"1":"0.01",Se(),Ae()})}function Pe(){const{bases:f=[],kind:y}=v()||{};return m?m(f,y):f}function Ke(){const f=Pe();return f.length?m?f[0]:(f.includes(yt)||(yt=f[0]),yt):null}function ce(){if(!i)return;P(ye);const{bases:f=[],kind:y}=v()||{},F=Pe(),S=s("div",{className:"btn-group btn-group-sm",role:"group"});S.setAttribute("aria-label",i);const Y=Ke(),_e=w=>L&&f.includes(w)?L:y==="port"?w==="net"?"this book has no cession":"a book has no cession of its own: its units cede on their own stages and it takes what they produce":y==="pnl"?"a P&L states a premium on every row of its ledger":f.length?"this program has no distinct basis of that kind":"needs a cession; add one on the Reinsurance tab",oe=qi.map(([w,U])=>{const Fn=!F.includes(w);return[w,U,Fn?_e(w):`calibrated on the ${U.toLowerCase()} view`,Fn]});we(S,oe,Y,w=>{if(!m){yt=w;try{localStorage.setItem("aggapi.priceBasis",w)}catch{}ce(),Ae()}}),ye.appendChild(S)}let ue=0,Ye=null;async function _n(){if(!W)return;const f=()=>{W.textContent="",W.classList.remove("is-pending")},{id:y,canPreview:F}=v()||{};if(!y||!F)return f();const S=It();if(!S||l&&(S[J]==null||S[x]==null))return f();const Y=++ue,_e=setTimeout(()=>{Y===ue&&W.classList.add("is-pending")},120),oe=w=>{clearTimeout(_e),Y===ue&&(W.textContent=w,W.classList.remove("is-pending"))};try{const w=await b.pricingPreview(y,S);Ye=w;const U=`assets ${H(w.assets)}, loss ratio ${he(w.lr)}, PQ ${w.pq?.toFixed(3)??""}, and CoC ${he(w.coc)}`;w.net_of_expense_premium!=null?oe(`Preview: gross premium ${H(w.gross_premium)}, net premium ${H(w.net_premium)}, net of expense premium ${H(w.net_of_expense_premium)}, `+U):w.gross_premium!=null?oe(`Preview: gross premium ${H(w.gross_premium)}, net premium ${H(w.premium)}, `+U):oe(`Preview: premium ${H(w.premium)}, `+U)}catch(w){Ye=null,oe(Jn(w))}}const Tn=Ft(_n,350),Ae=()=>{_n(),$?.()};for(const f of[N,V])f.addEventListener("input",()=>{Tn(),$?.()});T&&T.addEventListener("input",()=>{const f=parseFloat(T.value);Te=Number.isFinite(f)&&f>0?f:null,Tn(),$?.()}),le.addEventListener("click",()=>{const f=It();f&&a(f)});function It(){const f={},y=parseFloat(N.value),F=parseFloat(V.value);if(Number.isFinite(y))f[J]=y;else if(!l)return null;if(Number.isFinite(F))f[x]=F;else if(!l)return null;const S=i?Ke():null;if(S&&(f.basis=S),T&&!T.disabled){const Y=parseFloat(T.value);Number.isFinite(Y)&&Y>0&&(f.expense_ratio=Y)}return f}function ti(f){if(!f){Ae();return}J=f.anchor==="a"?"a":"p";const y=J==="p";N.step=y?"0.001":"1",y?N.max="1":N.removeAttribute("max");const F=y?f.octet?.p:f.octet?.assets;if(Number.isFinite(F)&&(N.value=String(F)),o.includes(f.target)){x=f.target;const S=f.octet?.[f.target==="coc"?"coc":f.target];Number.isFinite(S)&&(V.value=String(S))}else o.includes("premium")&&Number.isFinite(f.octet?.premium)&&(x="premium",V.value=String(f.octet.premium));V.step=x==="premium"?"1":"0.01",T&&!T.disabled&&Number.isFinite(f.expense)&&(T.value=String(f.expense),Te=f.expense>0?f.expense:null),ie(),Se(),Ae()}function ni(f){W&&(ue+=1,W.textContent=f,W.classList.remove("is-pending"))}function ai(f,y){le.disabled=f||B,le.textContent=f?y:n}function Bn(){if(!T)return;const f=(v()||{}).kind==="pnl";T.disabled=B||f,T.title=f?"the ledger states its own expenses":"gross expense as a fraction of premium; empty or zero sends nothing",document.activeElement!==T&&(T.value=Te!=null?String(Te):"0")}function ii(){Bn(),ce(),Ae()}function oi(f){B=!!f,C.classList.toggle("is-dormant",B),N.disabled=B,V.disabled=B,le.disabled=B,Bn(),ie(),Se(),ce()}return ie(),Se(),ce(),{read:It,write:ti,setBusy:ai,sync:ii,note:ni,setDormant:oi,held:()=>Ye,button:le}}function H(e){return Number.isFinite(e)?e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):""}function he(e){return Number.isFinite(e)?`${(e*100).toFixed(1)}%`:""}const Ii="Hand-curated DecL keyword pool, used by decl-mode.js for editor syntax highlighting and by completion.js as a client-side fallback when the api is unreachable. Mirrors _TERMINAL_LABELS in src/aggregate/parser_errors.py.",Oi=["agg","port","sev","distortion","note"],ji=["claims","loss","in","premium","at","dfreq","mixed","samples","poisson","binomial","bernoulli","geometric","negbin","neyman","logarithmic","fixed","pascal"],Vi=["dsev","lognorm","gamma","pareto","expon","weibull","beta","uniform","norm","logistic","burr","burr12","genpareto","invgamma","invgauss","tweedie","phasefit"],Wi=["mean","cv","skewness","kurtosis","wt","wts","shape","scale","loc","rate","p0","p1"],Hi=["occurrence","aggregate","net","of","ceded","to","xs","po","share","tower","and","inf"],Gi=["pnl","xpnl","inherit","derive","retro","peel","less","expense","expenses"],Ki=["tvar","ph","wang","proportional","linear","constant","convex","biTVaR","blend"],Yi=["splice","between","and","infinity","build","update","fast","slow"],Ui={_comment:Ii,structural:Oi,frequency:ji,severity:Vi,parameters:Wi,reinsurance:Hi,pnl:Gi,distortions:Ki,modifiers:Yi},dn=new Set,pn=new Set;for(const[e,t]of Object.entries(Ui)){if(e.startsWith("_"))continue;const n=e==="distortions"?pn:dn;for(const a of t)n.add(a)}const na=/[A-Za-z]/,Qi=/[A-Za-z0-9._:~\-]/,Be=/[0-9]/;function Xi(e){for(e.eat(na);!e.eol()&&Qi.test(e.peek());)e.next();return e.current()}const zi=yi.define({name:"decl",startState(){return{inBraceString:!1}},token(e,t){if(t.inBraceString){for(;!e.eol();)if(e.next()==="}")return t.inBraceString=!1,"string";return"string"}if(e.eatSpace())return null;if(e.peek()==="#")return e.skipToEnd(),"comment";if(e.peek()==="{"){for(e.next(),t.inBraceString=!0;!e.eol();)if(e.next()==="}")return t.inBraceString=!1,"string";return"string"}if(e.peek()==='"'||e.peek()==="'"){const n=e.next();for(;!e.eol();){const a=e.next();if(a==="\\"){e.next();continue}if(a===n)break}return"string"}if(Be.test(e.peek())||e.peek()==="-"&&Be.test(e.string[e.pos+1]||"")){for(e.eat("-");!e.eol()&&Be.test(e.peek());)e.next();if(e.peek()==="."&&Be.test(e.string[e.pos+1]||""))for(e.next();!e.eol()&&Be.test(e.peek());)e.next();if(e.peek()==="e"||e.peek()==="E")for(e.next(),(e.peek()==="+"||e.peek()==="-")&&e.next();!e.eol()&&Be.test(e.peek());)e.next();return"number"}if("()[]".includes(e.peek()))return e.next(),"bracket";if(na.test(e.peek())){const n=Xi(e);return dn.has(n.toLowerCase())?"keyword":pn.has(n.toLowerCase())?"atom":null}return e.next(),null},languageData:{commentTokens:{line:"#"},wordChars:"._:~-"}}),Zi=[...[...dn].map(e=>({label:e,type:"keyword"})),...[...pn].map(e=>({label:e,type:"atom"}))];async function Ji(e){const t=e.matchBefore(/[\w.:~-]*/);if(!t||t.from===t.to&&!e.explicit)return null;const n=e.state.doc.toString(),a=e.pos;let i=null;if(e.explicit)try{const r=await b.complete(n,a);r&&Array.isArray(r.completions)&&(i=r.completions.map(l=>({label:l.text||l.label,detail:l.detail||void 0,type:l.kind||"keyword",boost:5})))}catch{i=null}const o=eo([...i||[],...Zi]);return{from:t.from,options:o,validFor:/^[\w.:~-]*$/}}function eo(e){const t=new Set,n=[];for(const a of e)t.has(a.label)||(t.add(a.label),n.push(a));return n}const to=new ta,Rn=new ta,aa="aggapi.emacsKeys",Dn=Mi.define();function ia(){const e=typeof navigator>"u"?null:navigator;return e&&(/Apple Computer/.test(e.vendor||"")&&(/Mobile\/\w+/.test(e.userAgent||"")||(e.maxTouchPoints||0)>2)||/Mac/.test(e.platform||""))?"Cmd":"Ctrl"}function oa(){try{return localStorage.getItem(aa)!=="off"}catch{return!0}}let qe="";function no(e){const{state:t}=e,{from:n,to:a,empty:i}=t.selection.main;if(!i)return qe=t.doc.sliceString(n,a),e.dispatch({changes:{from:n,to:a},scrollIntoView:!0}),!0;const o=t.doc.lineAt(n);let r=o.to;if(n===o.to){if(o.to===t.doc.length)return!0;r=o.to+1,qe=`
|
|
2
|
+
`}else qe=t.doc.sliceString(n,o.to);return e.dispatch({changes:{from:n,to:r},scrollIntoView:!0}),!0}function ao(e){if(!qe)return!1;const{from:t,to:n}=e.state.selection.main;return e.dispatch({changes:{from:t,to:n,insert:qe},selection:{anchor:t+qe.length},scrollIntoView:!0}),!0}function qn(e){return e?en.of([{key:"Ctrl-k",run:no,preventDefault:!0},{key:"Ctrl-y",run:ao,preventDefault:!0},...Fi]):[]}const io=ze.theme({"&":{fontSize:"14px"},".cm-content":{fontFamily:'"Cascadia Mono", Menlo, Consolas, monospace',padding:"12px 54px 12px 10px",minHeight:"10.2em"},".cm-scroller":{overflow:"auto",maxHeight:"40vh"},".cm-gutters":{backgroundColor:"#fff",color:"#9aa3b0",borderRight:"1px solid #eef0f3"},".cm-activeLine":{backgroundColor:"#f7faff"},".cm-activeLineGutter":{backgroundColor:"#eef3fb"}});function oo(e,t={}){const n=en.of([{key:"Mod-Enter",run:()=>(t.onBuild?.(),!0)},{key:"Mod-ArrowUp",run:()=>(t.onHistoryPrev?.(),!0)},{key:"Mod-ArrowDown",run:()=>(t.onHistoryNext?.(),!0)},{key:"Ctrl-ArrowUp",run:()=>(t.onHistoryPrev?.(),!0)},{key:"Ctrl-ArrowDown",run:()=>(t.onHistoryNext?.(),!0)},{key:"Mod-Shift-ArrowUp",run:()=>(t.onExamplePrev?.(),!0)},{key:"Mod-Shift-ArrowDown",run:()=>(t.onExampleNext?.(),!0)},{key:"Ctrl-Shift-ArrowUp",run:()=>(t.onExamplePrev?.(),!0)},{key:"Ctrl-Shift-ArrowDown",run:()=>(t.onExampleNext?.(),!0)},{key:"Tab",run:wi}]),a=Mn.create({doc:"",extensions:[xi(),Ci(),$i(),Mn.allowMultipleSelections.of(!0),Li(),ki(),Ni(),to.of(zi),Ei(Ri,{fallback:!0}),ze.lineWrapping,Si({override:[Ji],activateOnTyping:!1,closeOnBlur:!0}),n,Rn.of(qn(oa())),en.of([...Pi,...Ai,..._i,...Ti,Bi]),ze.contentAttributes.of({autocomplete:"off",autocorrect:"off",autocapitalize:"off",spellcheck:"false"}),ze.updateListener.of(o=>{if(!o.docChanged)return;const r=o.transactions.some(l=>l.annotation(Dn));t.onEdit?.(!!r)}),io]}),i=new ze({state:a,parent:e});return{view:i,getText:()=>i.state.doc.toString(),setText:o=>{i.dispatch({changes:{from:0,to:i.state.doc.length,insert:o||""},annotations:Dn.of(!0)})},focus:()=>i.focus(),setEmacs:o=>{i.dispatch({effects:Rn.reconfigure(qn(o))});try{localStorage.setItem(aa,o?"on":"off")}catch{}}}}const tn="aggregate-web:history",In=500,so=256*1024,at=-2;function ro(){try{const e=localStorage.getItem(tn);if(!e)return{entries:[],cursor:-1,draft:null};const t=JSON.parse(e);return Array.isArray(t.entries)?(typeof t.draft!="string"&&(t.draft=null),t):{entries:[],cursor:-1,draft:null}}catch{return{entries:[],cursor:-1,draft:null}}}function lo(e){e.length>In&&(e.length=In);let t=0;for(let n=0;n<e.length;n+=1)if(t+=e[n].length,t>so){e.length=Math.max(n,1);break}return e}function Ce(e){try{localStorage.setItem(tn,JSON.stringify(e));return}catch{}const t=e.entries.slice(0,Math.max(Math.floor(e.entries.length*.75),1));try{localStorage.setItem(tn,JSON.stringify({...e,entries:t})),e.entries=t}catch{}}const h=ro();function co(e){const t=(e||"").trim();t&&h.entries[0]!==t&&(h.entries.unshift(t),lo(h.entries),h.cursor=-1,h.draft=null,Ce(h))}function sa(e){return h.cursor===at?-1:h.cursor!==-1?h.cursor:(e||"").trim()===h.entries[0]?0:-1}function uo(e=""){const t=h.entries.length;if(t===0)return null;const n=sa(e);if(n+1>=t)return null;if(h.cursor===-1){const a=(e||"").trim();h.draft=a&&a!==h.entries[0]?a:null}return h.cursor=n+1,Ce(h),h.entries[h.cursor]}function po(){return h.cursor===at?null:h.cursor<=0?h.cursor===0&&h.draft?(h.cursor=at,Ce(h),h.draft):(h.cursor=-1,Ce(h),null):(h.cursor-=1,Ce(h),h.entries[h.cursor])}function ra(){const e=h.entries.length;return e?h.cursor===at?{m:0,n:e}:{m:e-Math.max(h.cursor,0),n:e}:{m:0,n:0}}function fo(e=""){const t=h.entries.length;return t===0?!1:sa(e)+1<t}function mo(){return h.cursor===at||h.cursor===-1?!1:h.cursor>0?!0:!!h.draft}function ho(e,t){if(!e||!t)return null;const n=i=>String(i).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^\\s*${n(e)}\\s+${n(t)}(\\s|$)`);return h.entries.find(i=>a.test(i))||null}function go(){h.cursor===-1&&!h.draft||(h.cursor=-1,h.draft=null,Ce(h))}function bo(){h.entries=[],h.cursor=-1,h.draft=null,Ce(h)}function la(e){const t=Number(e),n=Number.isFinite(t)&&t>0?`Please try again in about ${t} second${t===1?"":"s"}.`:"Please give it a moment and try again.";return s("div",{className:"agg-ratelimit"},s("div",{className:"agg-ratelimit-icon"},s("i",{className:"bi bi-cup-hot"})),s("div",{},s("div",{className:"agg-ratelimit-title"},"Easy there. Grab a coffee ☕"),s("div",{className:"agg-ratelimit-msg"},"We're glad you're enjoying ",s("code",{},"aggregate"),"! It's a shared, free resource, so builds are gently rate-limited to keep it snappy for everyone. ",n),s("div",{className:"agg-ratelimit-sub small text-muted"},"Want unlimited builds? ",s("code",{},"aggregate")," is open source, so you can ",s("a",{href:"https://github.com/mynl/aggregate",target:"_blank",rel:"noopener"},"run it locally"),".")))}function vo(e,t){const n=e.kind?`${e.kind} ${e.name}`:e.name,a=ho(e.kind,e.name),i=[s("div",{className:"mb-1"},"The declaration ",s("code",{},n)," is not in this session any more, so the program cannot be built."),s("div",{className:"small text-muted mb-2"},e.message||"")];if(a&&typeof t=="function"){const o=s("button",{className:"btn btn-sm btn-outline-secondary",type:"button"},`Rebuild ${n}`);o.addEventListener("click",()=>t(a)),i.push(o)}else i.push(s("div",{className:"small"},"Build it again, then rebuild this program."));return s("div",{className:"alert alert-warning agg-error-pane",role:"alert"},...i)}function yo(e,t){const n=e&&e.body||{},a=n.detail||n||{};if(typeof a=="string")return s("div",{className:"alert alert-warning agg-error-pane",role:"alert"},a);if(a.error==="recipe_not_found")return vo(a,t);if(!a.line&&!a.message)return s("div",{className:"alert alert-danger",role:"alert"},e?.message||"Request failed");const i=[];if(a.line&&a.column&&i.push(s("div",{className:"small text-muted"},`Parse error at line ${a.line}, column ${a.column}.`)),a.source){const r=s("pre",{className:"agg-error-source mb-2"});r.appendChild(s("code",{},a.source+`
|
|
3
|
+
`)),a.caret&&r.appendChild(s("code",{className:"agg-error-caret"},a.caret)),i.push(r)}a.message&&i.push(s("div",{className:"mb-1"},a.message)),Array.isArray(a.suggestions)&&a.suggestions.length&&i.push(s("div",{className:"fst-italic mb-2"},"Did you mean: ",a.suggestions.join(", "),"?"));const o=a.expected||[];return o.length&&i.push(s("div",{className:"small text-muted"},"Expected: ",o.join(", "),".")),s("div",{className:"alert alert-warning agg-error-pane",role:"alert"},...i)}const K={overview:{label:"Overview",leaves:{plot:{label:"Plot",primaryChart:!0,why:"the library publishes no chart for this object yet",hint:"the distribution and its tail, linked on one cursor"},summary:{label:"Summary",exhibit:"summary",why:"a severity carries no summary frame",hint:"moments and key percentiles"},validation:{label:"Validation",exhibit:"validation",why:"needs computed moments",hint:"theoretical vs empirical moments; “not unreasonable” on a clean build"},stats:{label:"Stats",exhibit:"stats",why:"needs computed moments",hint:"frequency / severity / aggregate moments; raw moment rows are dropped"},tail:{label:"Tail",exhibit:"tail",why:"needs a full loss distribution: an aggregate, a portfolio, or the book under a P&L",hint:"VaR, TVaR and xsVaR by return period"}}},reinsurance:{label:"Re",alsoLive:"canReins",leaves:{diagram:{label:"Diagram",chart:"structure",why:"needs a cession; add one below",hint:"the reinsurance program: layers, shares, retention"},plot:{label:"Plot",chart:"reins",why:"needs a cession; add one below",hint:"impact of the cession on the shape and tail"},summary:{label:"Summary",exhibit:"reins",why:"needs a cession; add one below",hint:"the program layer by layer"},stats:{label:"Stats",exhibit:"reins",why:"needs a cession; add one below",hint:"gross, ceded and net moments"},density:{label:"Density",exhibit:"reins",why:"needs a cession; add one below",hint:"the three distributions on one grid"}}},pricing:{label:"Pricing",leaves:{calibrate:{label:"Calibrate",flag:"canPrice",why:"an aggregate or a portfolio only",hint:"one row per distortion family, each fitted to the same premium target"},standalone:{label:"Stand-alone",flag:"canPrice",why:"an aggregate or a portfolio only",hint:"the calibrated families applied to each part as prices in their own right, and the sum against the whole"},allocate:{label:"Allocate",flag:"canNaturalAllocation",why:"needs a book of units or an occurrence cession",hint:"one premium split across the parts on one basis: units of a book, or the layers of an occurrence program"},plot:{label:"Plot",chart:"kappa",why:"needs a book of units, an occurrence cession, or a reinsured P&L",hint:"the kappa curves behind the allocation: expectation by part, given the whole"},ruin:{label:"Pr Ruin",chart:"ruin",dividerBefore:!0,why:"needs a Poisson or renewal (wait) frequency",hint:"sample surplus paths and the probability of eventual default; Poisson or renewal frequency only"},evaluate:{label:"Evaluate",flag:"canEvaluate",dividerBefore:!0,why:"needs an object that can be priced",hint:"distortion parameter in each family that values the margin at zero"}}},economics:{label:"PnL",leaves:{ratios:{label:"Summary",exhibit:"economic_ratios",why:"a P&L only",hint:"premium, loss, expense, margin and its standard deviation, with the ratios, one row per block"},waterfall:{label:"Waterfall",exhibit:"economic_waterfall",why:"a P&L tower only",hint:"what each step of the tower spends and earns, then three capital bases and the cost of each"},ledger:{label:"Ledger",exhibit:"economic",why:"a P&L only",hint:"the P&L, line by line"},tail:{label:"Tail",exhibit:"economic_tail",why:"a P&L only",hint:"VaR and xsVaR on the closing margin by return period, read as a payoff: the adverse tail is the low one"},pentagon:{label:"Pentagon",flag:"canPnlPentagon",why:"a P&L only",hint:"gross, ceded and net on one figure: assets, loss, capital, margin, premium and the ratios between them, at a solvency level you pick"}}},bounds:{label:"Bounds",leaves:{bounds:{label:"Bounds",flag:"canBounds",why:"needs a loss distribution: an aggregate, a portfolio, or a P&L wrapping one",hint:"every distortion consistent with this premium, as a band"},pricing:{label:"Pricing Bounds",flag:"canBounds",why:"needs a loss distribution: an aggregate, a portfolio, or a P&L wrapping one",hint:"price of a second risk, given the base-line risk and price"},allocation:{label:"Allocation Bounds",flag:"canAllocate",why:"a portfolio only",hint:"per-unit ranges consistent with the total; a portfolio only"}}},more:{label:"More",leaves:{behavior:{label:"Tail behavior",exhibit:"tail_behavior",why:"needs a full loss distribution, so an aggregate or a portfolio",hint:"the left and right tail class; support bounded or unbounded"},approximation:{label:"Approximation",exhibit:"approximation",why:"needs a computed aggregate or portfolio",hint:"the five moment-matched families against the exact law: parameters, achieved moments, Kolmogorov distance, and the implied tail"},window:{label:"Window",exhibit:"bs_window",why:"needs an FFT grid",hint:"each row proposes a window [x_min, x_max] of width W = x_max - x_min, and the grid bs · 2^log2 that covers it; the selected row is indicated"},dependency:{label:"Dependency",exhibit:"dependency",why:"a bivariate only",hint:"the copula and its impact; a bivariate only"},sharpen:{label:"Sharpen",flag:"hasSharpen",why:"press Sharpen on the action row first; this is its audit",hint:"fit scores for every grid probed; lower is better; the selected row is indicated"},narrative:{label:"Narrative",hint:"the object’s info and various attribute description strings"},density:{label:"Density",hint:"binned probability mass, distribution, and survival functions"}}},lab:{label:"Lab",dynamic:!0,leaves:{}}};function wo(){const e=new Set;for(const[t,n]of Object.entries(K))if(t!=="lab")for(const a of Object.values(n.leaves||{}))a.exhibit&&e.add(`exhibit:${a.exhibit}`),a.chart&&e.add(`chart:${a.chart}`);return e}function xo(e){const t=wo(),n={};for(const a of e||[])for(const i of a.leaves||[]){if(i.kind!=="exhibit"&&i.kind!=="chart"||t.has(`${i.kind}:${i.name}`))continue;const o=`${i.kind}-${i.name}`;o in n||(n[o]={label:i.label||i.name,hint:i.hint||"",why:i.why||"not available for this object",[i.kind]:i.name,plugin:a.name,pluginVersion:a.version||null})}return n}function Co(e){return K.lab.leaves=xo(e),Object.keys(K.lab.leaves).length}function dt(e,t){return K[e]?.leaves?.[t]}function $o(e,t){return dt(e,t)?.why||"not available for this object"}function Lo(e){return Object.keys(K[e]?.leaves||{}).map(n=>dt(e,n)?.why).find(Boolean)||"not available for this object"}function kt(e,t,n){const a=dt(t,n);return!a||a.soon?!1:a.exhibit?e.exhibits.has(a.exhibit):a.primaryChart?!!e.primaryChart:a.chart?e.charts.has(a.chart):a.flag?!!e.flags?.[a.flag]:!!e.built}function ko(e,t){const n=K[t];return n?n.alsoLive&&e.flags?.[n.alsoLive]?!0:Object.keys(n.leaves||{}).some(a=>kt(e,t,a)):!1}function No(e,t,n){const a=Object.keys(K[n]?.leaves||{});return t&&kt(e,n,t)?t:a.find(i=>kt(e,n,i))||a[0]}function ca(e,t=!0){const n=e||{};return{built:t&&!!e,exhibits:new Set((n.exhibits||[]).map(a=>a.name)),charts:new Set(n.charts||[]),primaryChart:n.primary_chart||null,flags:{canPrice:!!n.can_price,canEvaluate:!!n.can_evaluate,canSharpen:!!n.can_sharpen,hasSharpen:!!n.has_sharpen,canPnl:!!n.can_pnl,canPnlRate:!!n.can_pnl_rate,canPnlPentagon:!!n.can_pnl_pentagon,canXpnl:!!n.can_xpnl,canExplode:!!n.can_explode,canHints:!!n.can_hints,canReins:!!n.can_reins,canViews:!!n.can_views,reinsBases:n.reins_bases||[],canBounds:!!n.can_bounds,canAllocate:!!n.can_allocate,canNaturalAllocation:!!n.can_natural_allocation,hasPremium:!!n.has_premium,premium:n.premium??null,needsPremium:!!n.needs_premium}}}const ua=[[0,1],[-.951,.309],[-.588,-.809],[.588,-.809],[.951,.309]],De={CX:500,CY:250,R:150,R_MAX:40,WY:600};De.EY=(De.CY+De.R+De.WY)/2;const Eo={x:235,y:78,w:620,h:580},nn=["pent-g","pent-c","pent-n"],jt=[0,66,128,176],So=1e-9;function Po(e,t,n=6,a=7,i=.12){const o=t[0]-e[0],r=t[1]-e[1],l=Math.hypot(o,r);if(!(l>0))return`M${e[0]},${e[1]}`;const p=o/l,d=r/l,g=-d,m=p,L=[e[0]+p*l*i,e[1]+d*l*i],v=[t[0]-p*l*i,t[1]-d*l*i];let $=`M${e[0].toFixed(1)},${e[1].toFixed(1)} L${L[0].toFixed(1)},${L[1].toFixed(1)}`;const C=n*2;for(let A=1;A<=C;A+=1){const D=A/(C+1),ye=L[0]+(v[0]-L[0])*D,N=L[1]+(v[1]-L[1])*D,O=A%2?a:-a;$+=` L${(ye+g*O).toFixed(1)},${(N+m*O).toFixed(1)}`}return $+=` L${v[0].toFixed(1)},${v[1].toFixed(1)} L${t[0].toFixed(1)},${t[1].toFixed(1)}`,$}function Ao(e,t){if(!(t>0)||!Number.isFinite(e))return 11;const n=Math.min(Math.max(e/t,0),1);return Math.max(11,De.R_MAX*Math.sqrt(n))}function _o(e,t){return!Number.isFinite(t)||Math.abs(t)<=So||!Number.isFinite(e)?null:Math.min(Math.max(e/t,0),1)}function To(e,t){return e>=18&&1.1*e*Math.sin(Math.min(Math.PI*t,Math.PI/2))>=22}const Bo=e=>-Math.PI/2+Math.PI*(1+e);function On(e,t,n,a,i){if(!Number.isFinite(a)||a<=5e-4)return"";if(a>=.9995)return`<circle class="${i}" cx="${e}" cy="${t}" r="${n}"/>`;const o=-Math.PI/2,r=o+2*Math.PI*a,l=e+n*Math.cos(o),p=t+n*Math.sin(o),d=e+n*Math.cos(r),g=t+n*Math.sin(r),m=a>.5?1:0;return`<path class="${i}" d="M${e},${t} L${l.toFixed(1)},${p.toFixed(1)} A${n},${n} 0 ${m},1 ${d.toFixed(1)},${g.toFixed(1)} Z"/>`}function Fo(e){if(!e||!Array.isArray(e.columns))return{};const[t,...n]=e.columns,a={};for(const i of e.rows||[]){if(t!=="Step")break;a[i[0]]=Object.fromEntries(n.map((o,r)=>[o,i[r+1]]))}return a}function da(e){const t=Fo(e),n=t.Gross;if(!n)return null;const a=t.All||n,i=t.Ceded||Object.fromEntries(Object.keys(n).map(o=>[o,0]));return{gross:n,ceded:i,net:a,steps:t}}function it(e){return`1-in-${Number(e).toLocaleString("en-US")}`}const pt="·",j=e=>Number.isFinite(e)?H(e):pt,q=e=>Number.isFinite(e)?he(e):pt,wt=e=>Number.isFinite(e)?e.toFixed(2):pt,Vt=e=>Number.isFinite(e)?`${e.toFixed(2)}:1`:pt;function Nt(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Mo(e,t,n,a,i,o){if(a===null)return`<circle class="pent-empty" cx="${e}" cy="${t}" r="${n}"/>`;const r=1-a;if(r<.005)return`<circle class="pent-ceded" cx="${e}" cy="${t}" r="${n}"/>`+On(e,t,n,a,"pent-net");const l=he(r);let p;if(i){const d=i==="upright"?1:-1,g=e+d*(.66*n+2),m=t-.66*n-2,L=Math.min(.22,2*Math.PI*r*.4),v=-Math.PI/2-L;p=`${o?`<line class="pent-lead" x1="${(g-d*3).toFixed(1)}" y1="${(m+1.5).toFixed(1)}" x2="${(e+.55*n*Math.cos(v)).toFixed(1)}" y2="${(t+.55*n*Math.sin(v)).toFixed(1)}"/>`:""}<text class="pent-pct" x="${g.toFixed(1)}" y="${m.toFixed(1)}" text-anchor="${d>0?"start":"end"}">${l}</text>`}else{const d=Bo(a),g=Math.max(6,Math.min(8.5,n*.25));p=`<text class="pent-pin" font-size="${g.toFixed(1)}" x="${(e+.58*n*Math.cos(d)).toFixed(1)}" y="${(t+.58*n*Math.sin(d)+g*.35).toFixed(1)}">${l}</text>`}return`<circle class="pent-ceded" cx="${e}" cy="${t}" r="${n}"/>`+On(e,t,n,a,"pent-net")+p}function Ro(e,t,n,a,i,o,r=0){const l=a==="left"?"end":"start",p=(a==="left"?e-n-12:e+n+12)+r,d=(g,m)=>{const L=t-11+m*15,v=Array.isArray(g)?g:[g];return v.length===1?`<text class="${nn[m]}" x="${a==="left"?p:p+jt[1]}" y="${L}" text-anchor="end">${v[0]}</text>`:v.map(($,C)=>{const A=a==="left"?p-jt[v.length-1-C]:p+jt[C+1];return`<text class="${nn[m]}" x="${A}" y="${L}" text-anchor="end">${$}</text>`}).join("")};return`<text class="pent-name" x="${p}" y="${t-26}" text-anchor="${l}">${Nt(i)}</text>`+o.map(d).join("")}function Wt(e,t,n,a,i=72){const o=15*a.length+22,r=i/n.length,l=p=>e-i/2+r*(p+1)-6;return`<g class="pent-chip"><rect x="${e-i/2}" y="${t-o/2}" width="${i}" height="${o}" rx="5"/>`+n.map((p,d)=>`<text class="pent-chip-head" x="${l(d)}" y="${t-o/2+12}" text-anchor="end">${Nt(p)}</text>`).join("")+a.map((p,d)=>p.map((g,m)=>`<text class="${nn[d]} pent-chip-v" x="${l(m)}" y="${t-o/2+28+d*15}" text-anchor="end">${g}</text>`).join("")).join("")+"</g>"}function Do(e=34){const t=e/2,n=e*.353,a=ua.map(([i,o])=>[(t+n*i).toFixed(2),(t+n*o).toFixed(2)].join(",")).join(" ");return`<svg class="pent-glyph" width="${e}" height="${e}" viewBox="0 0 ${e} ${e}" aria-hidden="true"><polygon points="${a}"/></svg>`}function qo(e,t){const n=da(e);if(!n)return"";const{gross:a,ceded:i,net:o}=n,{CX:r,CY:l,R:p,WY:d,EY:g}=De,m="**",L=ua.map(([x,B])=>[r+p*x,l+p*B]),[v,$,C,A,D]=L,ye=Math.max(a.a,a.L,a.M,a.P_tech,a.Q,a.P,1),N=[];N.push(`<path class="pent-edge" d="M${v[0]},${v[1]} L${$[0]},${$[1]} L${C[0]},${C[1]}"/><path class="pent-edge" d="M${A[0]},${A[1]} L${D[0]},${D[1]} L${v[0]},${v[1]}"/><path class="pent-edge" d="${Po(C,A,7,8)}"/><line class="pent-diag" x1="${$[0]}" y1="${$[1]}" x2="${D[0]}" y2="${D[1]}"/><line class="pent-diag" x1="${v[0]}" y1="${v[1]}" x2="${A[0]}" y2="${A[1]}"/><line class="pent-edge" x1="${r}" y1="${v[1]}" x2="${r}" y2="${d}"/><line class="pent-arc" x1="${$[0]}" y1="${$[1]}" x2="${r}" y2="${d}"/>`);const O=(x,B,we,ie,Se,Pe={})=>{const Ke=a[B],ce=Ao(Ke,ye),ue=_o(o[B],Ke),Ye=ue===null||To(ce,1-ue)?null:ie==="left"?"upright":"upleft";N.push(`<g class="pent-node" data-bs-toggle="tooltip" title="${Nt(Pe.tip||"")}">`+Mo(x[0],x[1],ce,ue,Ye,Pe.lead)+Ro(x[0],x[1],ce,ie,we,Se,Pe.dx||0)+"</g>")},He=x=>[j(a[x]),j(i[x]),j(o[x])],V=(x,B,we,ie)=>[[j(a[x]),B],[j(i[x]),we],[j(o[x]),ie]];O(C,"a",`assets${m}`,"left",He("a"),{tip:`Assets the solvency standard calls for at ${it(t)}: a = P + Q, with P the technical premium. The one figure in the picture the reader sets, through the strip above. Notional: nothing in the ledger is truncated here and no default is modeled.`}),O(A,"L","loss and CV","right",V("L",wt(a.CV),wt(i.CV),wt(o.CV)),{tip:"Expected loss, with the coefficient of variation of that law beside it. The ceded CV is the cession taken as one position, off the ledger, and prints a dot where the ledger has no joint to form it from."}),O($,"Q","capital","left",He("Q"),{lead:!0,tip:"Capital behind the book: Q = a − P. The red share is what the cession released, and it does not have to grow with the level: a program exhausted in the far tail releases less at a remoter standard."}),O(D,"M","margin and SD","right",V("M",j(a.SD),j(i.SD),j(o.SD)),{tip:"Margin, the price of risk: M = P − L, with the standard deviation of that result beside it. Red is the margin the cession took, which is the cost of the reinsurance."}),O(v,"P_tech","technical prem","right",He("P_tech"),{dx:16,tip:"Technical premium, loss plus margin, before expenses: P = L + M."}),O([r,g],"E","expenses and ER","right",V("E",q(a.ER),q(i.ER),q(o.ER)),{tip:"Expenses and the expense ratio on each basis, against written premium. A ceding commission books as a credit here, so the ceded line can read negative."});const ae=x=>Number.isFinite(x.SD)?wt(x.SD/(x.L+x.E)):pt;O([r,d],"P","gross prem, CR and CV","right",[[j(a.P),q(a.CR),ae(a)],[j(i.P),q(i.CR),ae(i)],[j(o.P),q(o.CR),ae(o)]],{tip:"Written premium, its combined ratio, and the cv of that combined ratio: the standard deviation over loss plus expense. The red line is the cession, ceded premium and what it bought."});const Ge=(x,B)=>`<g class="pent-node" data-bs-toggle="tooltip" title="${Nt(x)}">${B}</g>`;N.push(Ge("Cost of capital, margin over capital. The red row is the cession itself: margin given up over capital released, which is the rate the reinsurance was bought at.",Wt(($[0]+D[0])/2,($[1]+D[1])/2,["CoC"],[[q(a.CoC)],[q(i.CoC)],[q(o.CoC)]],62))),N.push(Ge("Loss over technical premium, then loss over written premium.",Wt(v[0]+(A[0]-v[0])*.66-16,v[1]+(A[1]-v[1])*.66,["TLR","LR"],[[q(a.TLR),q(a.LR)],[q(i.TLR),q(i.LR)],[q(o.TLR),q(o.LR)]],106))),N.push(Ge("Written premium to capital. The red row is ceded premium over the capital that cession released.",Wt(($[0]+r)/2-16,($[1]+d)/2,["P:Q"],[[Vt(a.PQ)],[Vt(i.PQ)],[Vt(o.PQ)]],72)));const{x:T,y:le,w:W,h:J}=Eo;return`<svg class="pent-figure" viewBox="${T} ${le} ${W} ${J}" role="img" aria-label="Pentagon report at ${it(t)}">`+N.join("")+"</svg>"}function Io(e,t){return'<div class="pent-strip" role="group" aria-label="Solvency level">'+e.map((n,a)=>{const i=da(n.frame),o=i?i.net.a:null;return`<button type="button" class="pent-mini${a===t?" on":""}" data-level="${a}" aria-pressed="${a===t}" title="Net assets at ${it(n.t)}: ${j(o)}">`+Do(30)+`<span class="pent-mini-t">${it(n.t)}</span><span class="pent-mini-a">net a ${j(o)}</span></button>`}).join("")+"</div>"}function Oo(e){return`<p class="pent-note"><b class="pent-key-g">gross</b> <span class="pent-dot">·</span> <b class="pent-key-c">ceded</b> <span class="pent-dot">·</span> <b class="pent-key-n">net</b><br><b>**</b> marks the one figure you set, the solvency level, now ${it(e)}. Disc area is the gross amount and the blue wedge its net share, so the red is the cession; the figure in the red sector is the percentage ceded, called out beside the disc where the sector is too small to hold it. <b>The capital is notional:</b> nothing in the ledger is truncated at these amounts, no default is modeled and no premium is reduced for the possibility of insolvency. Hover any node or chip.</p>`}function jo(e,t,n){if(!e)return;if(!t||!t.length){e.innerHTML='<p class="text-muted small">This P&L has no pentagon to draw.</p>';return}let a=0;const i=()=>{const o=t[a];e.innerHTML='<div class="control-band pent-band">'+Io(t,a)+`</div><div class="pent-scroll">${qo(o.frame,o.t)}</div>`+Oo(o.t),e.querySelectorAll(".pent-mini").forEach(r=>{r.addEventListener("click",()=>{const l=Number(r.dataset.level);l!==a&&(a=l,i())})}),n&&n(e)};i()}const jn=[1,1.5,2,2.5,3,4,5,7.5,10];function Ht(e){if(!(e>0))return 0;const t=Math.pow(10,Math.floor(Math.log10(e)));let n=jn[0]*t,a=1/0;for(const i of jn){const o=i*t,r=Math.abs(Math.log(o/e));r<a&&(a=r,n=o)}return n}const Vo=10;function Wo(e,t,n=null){const a=n!==null&&n>0&&Number.isFinite(n)?n:null,i=a===null?t:Math.min(t,a),o=!(e>0),r=Ht(o?Math.max(i,1)/64:e);if(a!==null&&r>=a)return[];const l=o?[0,r]:[r];for(;l[l.length-1]<i&&l.length<Vo;){const d=l[l.length-1],g=Math.max(Ht(d*2.1),d*1.5);l.push(a===null?g:Math.min(g,a))}const p=[];for(let d=0;d<l.length-1;d++)p.push({attach:l[d],limit:l[d+1]-l[d]});return p}const Ho=.95;function Go(e,t){if(t<=1)return t===1?[e]:[];const n=Math.max(e,Ho),a=(n-e)/(t-1),i=[e];for(let o=1;o<t-1;o++){const r=Math.round((e+a*o)*100)/100;i.push(Math.max(r,i[o-1]))}return i.push(Math.max(n,i[i.length-1])),i}const Ko=2,pa=6,Yo=24;function fa(e){const t=document.querySelector("header.sticky-top"),n=e.getBoundingClientRect().top+window.scrollY-(t?t.offsetHeight:0)-pa;return Math.max(0,n)}function be(){const e=document.getElementById("editor-box");e&&window.scrollTo({top:fa(e),behavior:"smooth"})}function ma(e){const t=document.querySelector(".out-tabs");if(!t)return;let n=fa(t);if(e){const a=e.getBoundingClientRect().bottom+window.scrollY-window.innerHeight+pa;n=Math.max(0,Math.min(n,a))}window.scrollY>=n-Ko||window.scrollTo({top:n,behavior:"smooth"})}async function fn(e,t,n=window.scrollY){try{await t}catch{}await new Promise(requestAnimationFrame),await new Promise(requestAnimationFrame),!(Math.abs(window.scrollY-n)>Yo)&&ma(e)}const Uo=230,Vn=8,Qo=7;function Xo(e,t,n=Uo){let i=e.left+e.width/2-n/2,o=0;const r=i+n-(t-Vn);r>0&&(o-=r,i-=r);const l=Vn-i;return l>0&&(o+=l),Math.round(o)}function zo(e=document){const t=e.ownerDocument||e,n=t.createElement("div");n.className="tip",n.setAttribute("role","tooltip"),n.setAttribute("aria-hidden","true"),n.hidden=!0,t.body.appendChild(n);let a=null;const i=()=>{a=null,n.hidden=!0},o=l=>{a=l,n.textContent=l.getAttribute("data-why")||"",n.hidden=!1;const p=l.getBoundingClientRect(),d=n.offsetWidth,g=p.left+p.width/2,m=g-d/2+Xo(p,t.documentElement.clientWidth,d);n.style.left=`${Math.round(m)}px`,n.style.top=`${Math.round(p.bottom+Qo)}px`,n.style.setProperty("--tip-arrow",`${Math.round(g-m)}px`)},r=l=>l instanceof Element?l.closest("[data-why]"):null;return e.addEventListener("pointerover",l=>{const p=r(l.target);p?o(p):a&&i()}),e.addEventListener("focusin",l=>{const p=r(l.target);let d=!1;try{d=!!p&&p.matches(":focus-visible")}catch{d=!!p}d?o(p):a&&i()}),e.addEventListener("focusout",()=>{a&&i()}),t.addEventListener("pointerleave",i),t.addEventListener("scroll",i,!0),(t.defaultView||globalThis).addEventListener("resize",i),{node:n,hide:i}}const ve={},c={id:null,kind:null,name:null,mean:null,hasReins:!1,policyLimit:null,caps:ca(null,!1),leaf:{},rendered:{}};let Ve="history";const E=oo(u("editor-host"),{onBuild:()=>{be(),Ee()},onHistoryPrev:()=>Et("prev"),onHistoryNext:()=>Et("next"),onExamplePrev:()=>zn("prev"),onExampleNext:()=>zn("next"),onEdit:e=>{e||(go(),Ve="history",_.caption&&(_.caption=null,mt())),Ne()}}),Zo=`agg BasicBook
|
|
4
|
+
250 claims
|
|
5
|
+
1000 xs 0
|
|
6
|
+
sev lognorm 100 cv 1.5
|
|
7
|
+
poisson
|
|
8
|
+
`;E.setText(Zo);E.focus();function Et(e){Ve="history";const t=e==="prev"?uo(E.getText()):po();t!==null&&(E.setText(t),qa()),Ne()}function Ne(){const e=u("history-pos");if(e){const{m:i,n:o}=Ve==="examples"?zs():ra();e.textContent=i?`[${i}/${o}]`:""}const t=E.getText(),n=u("history-prev"),a=u("history-next");n&&(n.disabled=!fo(t)),a&&(a.disabled=!mo())}function Mt(e){co(e),Ve="history",Ne()}let ft=null;u("history-prev").addEventListener("click",()=>Et("prev"));u("history-next").addEventListener("click",()=>Et("next"));const mn=ia();u("history-prev").title=`step back through your history (${mn}+↑)`;u("history-next").title=`step forward through your history (${mn}+↓)`;for(const e of document.querySelectorAll(".mod-key"))e.textContent=mn;u("editor-clear").addEventListener("click",()=>{if(E.getText().trim()){E.setText(""),E.focus();return}ra().n&&(bo(),Ne(),sn(u("history-pos"),"cleared")),E.focus()});const Ue=u("emacs-item");Ue&&(Ue.classList.toggle("active",oa()),Ue.addEventListener("click",()=>{const e=!Ue.classList.contains("active");Ue.classList.toggle("active",e),E.setEmacs(e)}));const Ze=u("build-btn");function hn(e){c.id=e.id,c.kind=e.kind,c.name=e.name,c.mean=e.mean,c.hasReins=!!e.has_reins,c.policyLimit=e.policy_limit??null,Wa(),Ca(e.capability),rs(e),xn(),Na()}function gn(){c.id=c.kind=c.name=c.mean=null,c.hasReins=!1,c.policyLimit=null,ft=null,Wa(),Ca(null)}async function Jo(e){try{await b.build(e,{}),Mt(e)}catch(t){yn(t);return}await Ee()}function ha(e,t="ok"){const n=u("summary-inner");ui(n,e),n.classList.remove("clustered"),u("status-strip").classList.remove("foldable"),vn(t),bn(),u("summary-clock").textContent=""}function ga(){const e=ia();ha(s("span",{className:"text-muted"},"Nothing to build. Type a DecL program, or an expression in parentheses such as ",s("span",{className:"mono"},"(2+2)"),", and press ",s("span",{className:"mono"},`${e}+Enter`),"."))}function es(e){gn(),xn(),ge(),ha([s("span",{className:"mono"},e.decl),s("span",{className:"mono"}," = "),s("span",{className:"mono nm"},Z(e.value))])}async function Ee(){const e=E.getText().trim();if(!e){ga();return}Ze.disabled=!0,Ze.textContent="Building…";try{const t=await b.build(e,{});if(t&&t.kind==="value"){es(t);return}hn(t),Mt(e),ft=e,ge()}catch(t){gn(),yn(t,Jo),ge()}finally{Ze.disabled=!1,Ze.textContent="Build"}}const an=u("sharpen-btn"),on=u("hints-btn"),St=u("pnl-btn"),ba=u("pnl-caret"),va=Array.from(document.querySelectorAll("[data-pnl-form]")),Fe=u("reformat-btn"),de=u("gcn-btn"),Ct=u("gcn-caret"),ts={"pnl-rate":"wrap in a P&L, each ceded premium written as a rate of the gross premium",xpnl:"the exploded P&L: wrapped if needed, then broken out layer by layer, lowest attaching first","xpnl-rate":"the exploded P&L, each ceded premium written as a rate of the gross premium"};function ns(e,t){return c.kind==="pnl"?t&&e?"already a P&L; xPnL explodes it as it stands":t?"already exploded, or built over a portfolio engine":"already a P&L":t&&!R("canXpnl")?c.kind==="port"?"the portfolio total hides its units, so there is nothing to explode":"a P&L wraps an Aggregate or a Portfolio":e&&R("canPnl")?"needs a library whose pnl_program writes rate premiums; this one does not yet":"a P&L wraps an Aggregate or a Portfolio"}function ge(){const e=(a,i)=>{a&&(a.classList.toggle("disabled",i),a.toggleAttribute("disabled",i),a.setAttribute("aria-disabled",i?"true":"false"))};e(an,!R("canSharpen")),e(on,!R("canHints"));const t=R("canPnlRate"),n=R("canXpnl");e(St,!R("canPnl")),e(ba,!(t||n));for(const a of va){const i=a.dataset.pnlPremium==="rate",o=a.dataset.pnlForm==="xpnl",r=(!i||t)&&(!o||n)&&(o||R("canPnl"));e(a,!r),a.title=r?ts[a.dataset.pnlForm+(i?"-rate":"")]:ns(i,o)}e(de,!R("canViews")),e(Ct,!R("canViews"))}async function ot(e,t,n,a){if(!c.id)return;be();const i=e.textContent;e.disabled=!0,e.textContent=t;try{const o=await n(c.id);E.setText(o.program),Mt(o.program),hn(o),ft=o.program.trim(),ge(),o.description&&ya(o.description),a&&ht(a)}catch(o){k(wn[Cn()]||"pane-overview",ne(o))}finally{e.disabled=!1,e.textContent=i,ge()}}function ya(e){_.derivation=e||"",mt()}const _={tags:[],declared:"",derivation:"",warnings:[],caption:null};function mt(){const e=u("summary-note");if(!e)return;P(e);const t=_.caption||{},n=_.tags.length?_.tags:t.tags||[],a=_.declared||t.note||"";for(const i of _.warnings)e.appendChild(s("span",{className:"note-warn"},i));if(_.derivation&&e.appendChild(s("span",{},_.derivation)),n.length||a){const i=s("span",{className:"note-declared"});for(const o of n)i.appendChild(s("span",{className:"note-tag"},o));a&&i.appendChild(s("span",{},a)),e.appendChild(i)}fs()}function bn(){_.tags=[],_.declared="",_.derivation="",_.warnings=[],mt()}an?.addEventListener("click",()=>ot(an,"Sharpening…",e=>b.sharpen(e)));on?.addEventListener("click",()=>ot(on,"Pinning…",e=>b.hints(e)));async function wa({form:e,premiumStyle:t}){ea.getInstance(ba)?.hide();const n=E.getText().trim();if(!n){ga();return}if(!(n!==(ft??"").trim()&&(await Ee(),!c.id))){if(c.kind==="pnl"){if(e!=="xpnl")return;await ot(St,"Exploding…",a=>b.explode(a));return}await ot(St,"Wrapping…",a=>b.pnl(a,{form:e,premium_style:t}),"economics")}}St?.addEventListener("click",()=>wa({form:"pnl",premiumStyle:"deposit"}));for(const e of va)e.addEventListener("click",()=>wa({form:e.dataset.pnlForm,premiumStyle:e.dataset.pnlPremium}));Fe?.addEventListener("click",async()=>{const e=E.getText();if(!(!e.trim()||Fe.hasAttribute("disabled"))){be(),Fe.disabled=!0;try{const{decl:t}=await b.formatDecl(e);t&&t!==e?E.setText(t):sn(Fe,"unchanged")}catch{sn(Fe,"unchanged")}finally{Fe.disabled=!1,ge()}}});function sn(e,t){const n=e.textContent;e.textContent=t,setTimeout(()=>{e.textContent=n},900)}const as={grossceded:"Gross / Ceded",grossnet:"Gross / Net",netceded:"Net / Ceded"};async function xa(e){if(!R("canViews")||de.hasAttribute("disabled"))return;const t=E.getText().trim();if(!t)return;be(),ea.getInstance(Ct)?.hide(),de.disabled=!0,Ct.disabled=!0;const n=de.textContent;de.textContent="Reading…";try{const a=t.replace(/^\s*(grossceded|grossnet|netceded)\s+/i,"");let i=`${e} ${a}`;try{const o=await b.formatDecl(i);o?.decl&&(i=o.decl)}catch{}E.setText(i),hn(await b.build(i,{})),Mt(i),ft=i,ya(`Read as ${as[e]||e}.`),ht("overview")}catch(a){gn(),yn(a)}finally{de.disabled=!1,Ct.disabled=!1,de.textContent=n,ge()}}de?.addEventListener("click",()=>xa("grossceded"));document.querySelectorAll("[data-views]").forEach(e=>{e.addEventListener("click",()=>xa(e.dataset.views))});function Ca(e){c.caps=ca(e,!!c.id),_s()}function R(e){return!!c.caps.flags[e]}Ze.addEventListener("click",()=>{be(),Ee()});const is={agg:"Aggregate",port:"Portfolio",sev:"Severity",distortion:"Distortion",bvagg:"Bivariate",pnl:"P&L"},os=new Set(["distortion","bvagg","sev"]);function ss(){return s("span",{className:"sep"},"·")}function Qe(...e){return s("span",{className:"grp"},...e)}function ee(e){return s("span",{className:"lbl"},e)}function se(e){return s("span",{className:"val"},e)}function Wn(e){if(e==null||!Number.isFinite(e))return"";if(e>=1)return Z(e);const t=1/e,n=Math.round(Math.log2(t));return Math.abs(2**n-t)<1e-6?`1/${2**n}`:Z(e)}function rs(e){const t=u("summary-inner");P(t),bs(),et.sync(),tt.sync(),Xa(),xe.sync(),t.classList.add("clustered");const n=is[e.kind]||"Aggregate",a=[s("span",{className:"nm"},e.name||"(anonymous)")],i=e.components||[],o=e.validation?us(e.validation):"ok";vn(o),e.validation&&o!=="ok"&&a.push(Qe(s("span",{className:`verdict ${o}`},e.validation))),a.push(Qe(s("span",{className:"kind"},n)));const r=[],l=[];if(i.length){const p=(d,g)=>`(${i.map(m=>m[g]==null?"?":d(m[g])).join(", ")})`;r.push(ee("bs"),se(p(Wn,"bs")),ee("log2"),se(p(String,"log2"))),l.push(ee("mean"),se(p(Z,"mean")),ee("CV"),se(p(Z,"cv")))}else e.bs!=null&&r.push(ee("bs"),se(Wn(e.bs))),e.log2!=null&&r.push(ee("log2"),se(String(e.log2))),e.value_type&&r.push(ee(e.value_type)),e.mean!=null&&l.push(ee("mean"),se(Z(e.mean))),e.cv!=null&&l.push(ee("CV"),se(Z(e.cv)));r.length&&a.push(Qe(...r)),l.length&&a.push(Qe(...l)),!e.validation&&i.length&&a.push(Qe(ee("validation"),se("n/a"))),t.append(...a),u("status-strip").classList.add("foldable"),bn(),_.tags=e.tags||[],_.declared=e.note||"",_.warnings=e.warnings||[],mt(),ds(e),ls()}function ls(){const e=u("status-strip");e&&(e.classList.remove("is-flash"),e.offsetWidth,e.classList.add("is-flash"))}const cs=/^reinsurance;\s*subject\s+/;function us(e){const t=String(e).trim().toLowerCase().replace(cs,"");return t==="not unreasonable"?"ok":/\bmean\b/.test(t)?"bad":"warn"}function vn(e){const t=u("status-strip");t&&(t.classList.toggle("is-warn",e==="warn"),t.classList.toggle("is-fail",e==="bad"))}function ds(e){const t=u("summary-clock");if(t){if(e.elapsed_ms==null){t.textContent="";return}t.textContent=e.cached?"cached":`${(e.elapsed_ms/1e3).toFixed(2)}s`}}function ps(e){if(e instanceof Lt&&e.status===429)return{text:"rate limited; please pause a moment",detail:null};const t=e&&e.body||{},n=t.detail||t||{};return typeof n=="string"?{text:"build failed",detail:n}:Array.isArray(n)?{text:"build failed",detail:n.map(a=>a.msg).join("; ")}:n.line&&n.column&&n.message?{text:"build failed",detail:`line ${n.line}, column ${n.column}: ${n.message}`}:n.message?{text:"build failed",detail:n.message}:{text:"build failed",detail:e?.message||null}}function yn(e,t){const n=e instanceof Lt&&e.status===429,a=u("summary-inner");P(a);const{text:i,detail:o}=ps(e);a.classList.remove("clustered"),u("status-strip").classList.remove("foldable"),a.appendChild(s("span",{className:"mono bad"},i)),o&&a.append(ss(),s("span",{className:"mono"},o)),vn("bad"),bn(),u("summary-clock").textContent="";const r=u("pane-overview");P(r),n?r.appendChild(la(e.retryAfter)):e instanceof Lt?r.appendChild(yo(e,t)):r.appendChild(s("div",{className:"alert alert-danger"},e.message)),ht("overview")}function fs(){const e=u("summary"),t=u("summary-more"),n=u("summary-more-text");if(!t||!n)return;if(!(u("status-strip").classList.contains("foldable")&&!!u("summary-note").firstChild)){t.hidden=!0,e.classList.remove("expanded"),t.setAttribute("aria-expanded","false");return}t.hidden=!1;const i=_.warnings.length;n.textContent=i?`${i} warning${i===1?"":"s"}`:"note",t.classList.toggle("has-warnings",i>0)}u("summary-more").addEventListener("click",()=>{const e=u("summary").classList.toggle("expanded");u("summary-more").setAttribute("aria-expanded",String(e))});const wn={overview:"pane-overview",economics:"pane-economics",reinsurance:"pane-reinsurance",pricing:"pane-calibrate",bounds:"pane-bounds",more:"pane-more",lab:"pane-lab"},ms=[...Object.values(wn),"pane-standalone","pane-allocate","pane-kappa","pane-evaluate","pane-ruin","pane-ruin-stats"];function xn(){di(),c.rendered={};for(const e of ms)P(u(e));P(u("reins-desc")),M&&(M.dispose(),M=null),Q&&(Q.dispose(),Q=null),X&&(X.dispose(),X=null),z&&(z.dispose(),z=null),fe&&(fe.dispose(),fe=null),me&&(me.dispose(),me=null)}function Cn(){const e=document.querySelector(".out-tabs [data-tab].active");return e?e.dataset.tab:"overview"}function ht(e){const t=document.querySelector(`.out-tabs [data-tab="${e}"]`);t&&vi.getOrCreateInstance(t).show()}const hs={"overview:plot":()=>ks(),"overview:summary":()=>I("pane-overview","summary",["overview","summary"]),"overview:tail":()=>I("pane-overview","tail",["overview","tail"]),"overview:validation":()=>I("pane-overview","validation",["overview","validation"]),"overview:stats":()=>I("pane-overview","stats",["overview","stats"]),"economics:ledger":()=>I("pane-economics","economic",["economics","ledger"]),"economics:ratios":()=>I("pane-economics","economic_ratios",["economics","ratios"]),"economics:waterfall":()=>I("pane-economics","economic_waterfall",["economics","waterfall"]),"economics:tail":()=>I("pane-economics","economic_tail",["economics","tail"]),"economics:pentagon":()=>Ps(),"reinsurance:diagram":()=>Hn("structure"),"reinsurance:summary":()=>Gn(0,["reinsurance","summary"]),"reinsurance:stats":()=>Gn(1,["reinsurance","stats"]),"reinsurance:density":()=>js("reins_density_df",["reinsurance","density"]),"reinsurance:plot":()=>Hn("reins"),"pricing:calibrate":()=>Me("calibrate"),"pricing:standalone":()=>Me("standalone"),"pricing:allocate":()=>Me("allocate"),"pricing:plot":()=>Me("plot"),"pricing:ruin":()=>Me("ruin"),"pricing:evaluate":()=>Me("evaluate"),"bounds:bounds":()=>Zt("bounds"),"bounds:pricing":()=>Zt("pricing"),"bounds:allocation":()=>Zt("allocation"),"more:density":()=>{const e={resolution:"display"};return Ba("pane-more","density_df",{...ve,maxRows:25,renderCap:8192},()=>os.has(c.kind)?b.density_df(c.id,e):b.density_df(c.id,{...e,cols:"loss,p_total,F,S"}),["more","density"])},"more:behavior":()=>I("pane-more","tail_behavior",["more","behavior"]),"more:approximation":()=>Va(),"more:window":()=>I("pane-more","bs_window",["more","window"]),"more:dependency":()=>I("pane-more","dependency",["more","dependency"]),"more:sharpen":()=>I("pane-more","sharpen",["more","sharpen"]),"more:narrative":()=>Ns()};function $a(e,t){return kt(c.caps,e,t)}function La(e){return ko(c.caps,e)}function $n(e){return No(c.caps,c.leaf[e],e)}function Ln(e){const t=u(`sub-${e}`);if(!t)return;P(t);const n=$n(e);for(const[a,i]of Object.entries(K[e].leaves)){const o=!$a(e,a);if(i.dividerBefore){const l=s("span",{className:"sub-divider"});l.setAttribute("aria-hidden","true"),t.appendChild(l)}const r=s("button",{type:"button",className:`sub-link${a===n?" active":""}`+(o?" nav-off":""),"data-label":i.label},i.label);if(r.setAttribute("role","tab"),r.setAttribute("aria-selected",String(a===n)),r.tabIndex=a===n&&!o?0:-1,o){const l=i.soon?"designed, not built yet":$o(e,a);r.setAttribute("aria-disabled","true"),r.setAttribute("data-why",l),r.setAttribute("aria-label",`${i.label}, ${l}`)}else r.addEventListener("click",()=>gs(e,a));t.appendChild(r)}}function Pt(e){return document.getElementById(`t-${e}`)}function gs(e,t){c.leaf[e]=t,Ln(e),fn(Pt(e),ka(e))}async function ka(e){if(!c.id)return;const t=$n(e),n=hs[`${e}:${t}`]||(e==="lab"?()=>Es(t):null);if(!(!n||!$a(e,t))&&c.rendered[e]!==t){c.rendered[e]=t;try{await n()}catch(a){delete c.rendered[e],k(wn[e],ne(a))}}}function bs(){let e=!1;for(const t of Object.keys(K)){const n=document.querySelector(`.out-tabs [data-tab="${t}"]`);if(!n)continue;const a=!La(t);if(n.classList.toggle("nav-off",a),n.classList.toggle("disabled",a),n.setAttribute("aria-disabled",a?"true":"false"),n.tabIndex=a?-1:0,a){const i=Lo(t);n.setAttribute("data-why",i),n.setAttribute("aria-label",`${K[t].label}, ${i}`)}else n.removeAttribute("data-why"),n.removeAttribute("aria-label");a&&Cn()===t&&(e=!0),Ln(t)}e&&ht("overview")}function Na(){Sa(Cn())}let Xe=null,Gt=null;document.querySelectorAll(".out-tabs [data-tab]").forEach(e=>{e.addEventListener("shown.bs.tab",()=>{const t=e.dataset.tab;Gt=t,queueMicrotask(()=>{Gt=null});const n=Sa(t);n.catch(()=>{}).then(()=>{if(Xe&&Xe.group===t){const{scrollY:a}=Xe;Xe=null,fn(Pt(t),n,a)}})}),e.addEventListener("click",t=>{e.classList.contains("nav-off")&&(t.preventDefault(),t.stopPropagation())},!0),e.addEventListener("click",()=>{if(e.classList.contains("nav-off"))return;const t=e.dataset.tab;Gt===t?Xe={group:t,scrollY:window.scrollY}:ma(Pt(t))})});function Ea(e,t){e.addEventListener("keydown",n=>{if(!["ArrowRight","ArrowLeft","Home","End"].includes(n.key))return;const a=[...e.querySelectorAll(t)].filter(p=>!p.classList.contains("nav-off"));if(!a.length)return;n.preventDefault();const i=a.indexOf(document.activeElement);let o;n.key==="Home"?o=0:n.key==="End"?o=a.length-1:i<0?o=0:o=(i+(n.key==="ArrowRight"?1:-1)+a.length)%a.length;const r=a[o];r.click(),([...e.querySelectorAll(t)].filter(p=>!p.classList.contains("nav-off"))[o]||r).focus()})}Ea(document.querySelector(".out-tabs"),"[data-tab]");document.querySelectorAll(".sub-tabs").forEach(e=>Ea(e,".sub-link"));document.addEventListener("keydown",e=>{if(!e.altKey||e.ctrlKey||e.metaKey)return;const t=Number(e.key),n=Object.keys(K);if(!Number.isInteger(t)||t<1||t>n.length)return;const a=n[t-1];La(a)&&(e.preventDefault(),ht(a))});async function Sa(e){!c.id||!K[e]||(Ln(e),e==="reinsurance"&&await As(),await ka(e))}let Q=null,X=null,z=null,fe=null,me=null;const Pa="aggapi.tableView";function vs(e){return e==="static"||e==="precise"}function ys(e){return b.frameIr(c.id,e)}const Aa="aggapi.perspective";let Ie=(()=>{try{return localStorage.getItem(Aa)||"insurer"}catch{return"insurer"}})(),Oe=(()=>{try{return localStorage.getItem(Pa)||localStorage.getItem("aggapi.overviewView")||"static"}catch{return"static"}})();const At=new Map;function je(e,t,n){At.set(e,{fn:t,node:n})}function ws(){for(const[e,t]of[...At]){if(t.node&&!t.node.isConnected){At.delete(e);continue}try{t.fn()}catch{}}}function xs(){c.id&&(xn(),At.clear(),Na())}function _a(e){if(e!==Oe){Oe=e;try{localStorage.setItem(Pa,e)}catch{}kn(),ws()}}function Ta(e){if(e!==Ie){Ie=e;try{localStorage.setItem(Aa,e)}catch{}kn(),xs()}}function kn(){for(const e of document.querySelectorAll("[data-table-view]"))e.classList.toggle("active",e.dataset.tableView===Oe);for(const e of document.querySelectorAll("[data-perspective]"))e.classList.toggle("active",e.dataset.perspective===Ie)}const Kt=["static","precise","interactive"];function Cs(){const e=Kt.indexOf(Oe);_a(Kt[(e+1)%Kt.length])}document.addEventListener("keydown",e=>{!e.ctrlKey||!e.shiftKey||e.altKey||e.code==="KeyU"&&(e.preventDefault(),e.stopPropagation(),Cs())},!0);function $s(){Ta(Ie==="raw"?"insurer":"raw")}function Ls(e){return!!(e instanceof Element?e:null)?.closest('input, textarea, select, [contenteditable="true"], .cm-editor')}document.addEventListener("keydown",e=>{!e.ctrlKey||!e.shiftKey||e.altKey||e.code==="KeyV"&&(Ls(e.target)||(e.preventDefault(),e.stopPropagation(),$s()))},!0);for(const e of document.querySelectorAll("[data-table-view]"))e.addEventListener("click",()=>_a(e.dataset.tableView));for(const e of document.querySelectorAll("[data-perspective]"))e.addEventListener("click",()=>Ta(e.dataset.perspective));kn();function gt(e,t,n,a=ve){const{doc:i,frame:o}=n||{},r=vs(Oe),l=(m,L)=>{t.isConnected&&(t.className="grid-host",hi(e,t,m,L))},p=()=>{t.isConnected&&(t.className="",P(t),t.appendChild(s("div",{className:"text-muted small fst-italic"},"This table could not be rendered.")))};if(!i){l(o,a);return}const d=()=>gi(i).then(m=>m?l(m.frame,{formats:m.formats,align:m.align,...a}):p()).catch(m=>{console.error("[table] the interactive view could not be mounted",m),p()});if(!r){d();return}t.className="gt-host";const g=Oe==="precise"?fi(i):i;mi(e,t,g).then(m=>{m||d()}).catch(m=>{console.error("[table] the static view could not be drawn",m),d()})}async function ks(){Q&&(Q.dispose(),Q=null);const e=u("pane-overview");ct("pane-overview"),P(e);const t=c.caps.primaryChart;if(!t){e.appendChild(ke());return}const n=s("div",{className:"overview-plot"});e.appendChild(n);let a=!1;try{Q=await Tt(n,{id:c.id,chart:t})}catch{a=!0}Q||(e.removeChild(n),e.appendChild(a?Bt():ke()))}async function Ns(){const e=await b.narrative(c.id),t=s("div",{className:"narrative"});e.info&&(t.appendChild(s("h6",{className:"exhibit-title"},"Info")),t.appendChild(s("pre",{className:"narrative-info"},e.info)));for(const n of e.sections||[])t.appendChild(s("h6",{className:"exhibit-title"},n.name)),n.description&&t.appendChild(s("p",{className:"narrative-lead"},n.description)),n.explanation&&t.appendChild(s("p",{className:"narrative-body"},n.explanation));t.firstChild||t.appendChild(s("div",{className:"text-muted small"},"This object carries no narrative text.")),k("pane-more",t)}function We(e,t){const n=dt(e,t);if(!n?.hint)return null;const a=s("p",{className:"exhibit-lede"},s("b",{},n.label));return a.appendChild(document.createTextNode(`: ${n.hint}`)),a}async function Es(e){const t=dt("lab",e);if(!t)return;if(xt&&(xt.dispose(),xt=null),t.exhibit){await I("pane-lab",t.exhibit,["lab",e]);return}const n=await b.chartDoc(c.id,t.chart),a=s("div"),i=We("lab",e);i&&a.appendChild(i);const o=s("div");a.appendChild(o),k("pane-lab",a),xt=cn(o,n)}let xt=null;async function I(e,t,n,a=null,i=null){const r=(await b.exhibit(c.id,t,Ie)).blocks||[],l=a===null?r:r.slice(a,a+1),p=()=>{const d=s("div",{className:"overview-exhibits exhibit-blocks"});k(e,d),i&&d.appendChild(i());const g=n&&We(n[0],n[1]);if(g&&d.appendChild(g),!l.length){d.appendChild(s("div",{className:"text-muted small"},"Nothing to show for this object."));return}for(const m of l){const{caption:L,...v}=m,$=s("div");d.appendChild($),gt(e,$,{doc:v},ve),L&&d.appendChild(s("div",{className:"exhibit-caption"},L))}je(e,p,d)};p()}function Ss(e){e==="pane-overview"&&Q?(Q.dispose(),Q=null):e==="pane-reinsurance"&&M?(M.dispose(),M=null):e==="pane-bounds"&&X?(X.dispose(),X=null):e==="pane-kappa"&&z?(z.dispose(),z=null):e==="pane-ruin"&&fe?(fe.dispose(),fe=null):e==="pane-more"&&me&&(me.dispose(),me=null)}function k(e,t){ct(e),Ss(e);const n=u(e);P(n),t&&n.appendChild(t)}async function Ba(e,t,n=ve,a=null,i=null){let o=null;if(!a){const l=await ys(t).catch(()=>null);l&&!pi(l)&&(o={doc:l})}o||(o={frame:await(a||(()=>b.frameOf(c.id,t)))()});const r=()=>{const l=s("div"),p=i&&We(i[0],i[1]);p&&l.appendChild(p);const d=s("div");l.appendChild(d),k(e,l),gt(e,d,o,n),je(e,r,l)};r()}function ne(e){return e instanceof Lt&&e.status===429?la(e.retryAfter):s("div",{className:"text-muted small"},Jn(e))}async function Ps(){const e=c.id;k("pane-economics",s("div",{className:"text-muted small"},"Reading the ledger at each solvency level…"));try{const t=await b.pnlPentagon(e);if(e!==c.id)return;const n=s("div",{className:"pent-leaf"});k("pane-economics",n);const a=We("economics","pentagon");a&&n.appendChild(a);const i=s("div");n.appendChild(i);let o=[];jo(i,t.levels,r=>{o.forEach(l=>l.dispose()),o=[...r.querySelectorAll('[data-bs-toggle="tooltip"]')].map(l=>un.getOrCreateInstance(l,{container:"body"}))})}catch(t){e===c.id&&k("pane-economics",ne(t))}}let M=null;async function As(){const e=u("reins-desc");if(!e||e.firstChild)return;const t=await b.reinsDescription(c.id).catch(()=>null);t?.text&&e.appendChild(s("span",{className:"mono"},t.text))}async function Hn(e){M&&(M.dispose(),M=null);const t=u("pane-reinsurance");ct("pane-reinsurance"),P(t);const n=s("div",{className:"overview-plot"});t.appendChild(n);let a=!1;try{M=await Tt(n,{id:c.id,chart:e})}catch{a=!0}M||(P(t),t.appendChild(a?Bt():ke()))}function _s(){const e=u("reins-entry");if(!e)return;const t=!R("canReins"),n="a cession applies to an aggregate";e.classList.toggle("is-off",t);for(const o of e.querySelectorAll("input, button"))o.disabled=t,o.id!=="qr-help"&&(t?o.setAttribute("title",n):o.removeAttribute("title"));const a=e.querySelector(".reins-entry-hint");a&&a.classList.toggle("d-none",t);let i=e.querySelector(".reins-entry-off");t&&!i?(i=s("p",{className:"reins-entry-hint reins-entry-off"},n),e.appendChild(i)):!t&&i&&i.remove(),t&&Sn(null),bt()}const Fa=u("reins-btn"),Ma=u("tower-btn"),Nn=["qr-share","qr-attach","qr-detach"],Ts={"qr-share":"100%","qr-attach":"50%","qr-detach":"95%"};function Yt(e,{allowZero:t=!1}={}){const n=String(e||"").trim().replace(/,/g,"");if(!n)return null;const a=n.endsWith("%"),i=Number.parseFloat(a?n.slice(0,-1):n);if(!Number.isFinite(i))return null;if(a){const o=i/100;return o>0&&o<1?{kind:"p",value:o}:null}return i>0||t&&i===0?{kind:"amount",value:i}:null}function G(e){return Number.isInteger(e)?String(e):String(Number(e.toPrecision(6)))}function Bs(e,t,n,a){const i=String(e).trim(),o=String(t).trim();return n===a?`attach ${i} and detach ${o} both read ${G(n)} on this object, so the layer has no width`:`detach ${o} is ${G(a)} here, below attach ${i} at ${G(n)}`}function Fs(){return u("qr-basis-agg")?.checked?"aggregate":"occurrence"}const Ut=new Map;async function En(){const e=u("qr-attach").value,t=u("qr-detach").value,n=Yt(e,{allowZero:!0}),a=Yt(t);if(!n||!a)throw new Error("attach and detach are both needed");const i=Yt(u("qr-share").value),o=Fs(),r=m=>`${c.id}:${o}:${m}`,l=[n,a].filter(m=>m.kind==="p").map(m=>m.value).filter(m=>!Ut.has(r(m)));if(l.length){const{quantiles:m}=await b.quantiles(c.id,l,o);for(const L of m)Ut.set(r(L.p),L.snapped)}const p=m=>m.kind==="p"?Ut.get(r(m.value)):m.value,d=p(n),g=p(a);if(!(g>d))throw new Error(Bs(e,t,d,g));return{attachAmount:d,detachAmount:g,share:i,basis:o}}function Ra(e){return e?e.kind==="amount"?`${G(e.value)} po `:Math.abs(e.value-1)>1e-9?`${G(e.value*100)}% po `:"":""}function Da({attachAmount:e,detachAmount:t,share:n,basis:a}){const i=`${G(t-e)} xs ${G(e)}`;return`${a} net of ${Ra(n)}${i}`}function Ms(e,t){return e?e.kind==="amount"?e.value/t:e.value:1}async function Rs(){return Da(await En())}async function Ds(){const{attachAmount:e,detachAmount:t,share:n,basis:a}=await En();if(n&&n.kind==="amount")throw new Error(`Tower needs the share as a percentage: ${G(n.value)} is an amount of cover, which means something on one layer only`);const i=a==="aggregate"?null:c.policyLimit;let o=Wo(e,t,i);if(!o.length){if(i!==null&&!(e<i))throw new Error(`attach reads ${G(e)} here, at or above the policy limit of ${G(i)}: an occurrence layer there covers nothing, since no one claim can reach it`);const d=i===null?t:Math.min(t,i);o=[{attach:e,limit:d-e}]}const r=Go(n?n.value:1,o.length),l=a==="aggregate"?"Agg":"Occ",p=o.map((d,g)=>Ra({kind:"p",value:r[g]})+`${G(d.limit)} xs ${G(d.attach)} as "${l} ${g+1}"`);return`${a} net of ${p.join(" and ")}`}let Qt=0;async function bt(){const e=u("qr-preview");if(!e)return;if(!c.id||!R("canReins")){e.textContent="",e.classList.remove("is-pending");return}const t=++Qt,n=setTimeout(()=>{t===Qt&&e.classList.add("is-pending")},120),a=i=>{clearTimeout(n),t===Qt&&(e.textContent=i,e.classList.remove("is-pending"))};try{const i=await En(),o=Da(i);a(`Preview: ${o}
|
|
9
|
+
${await qs(i)}`)}catch(i){a(i.message)}}async function qs(e){const t=e.detachAmount-e.attachAmount,n={tier:e.basis,attach:e.attachAmount,limit:t,share:Ms(e.share,t)};let a;try{({indications:[a]}=await b.layerIndication(c.id,[n]))}catch{return""}if(!a)return"";const i=[`EL ${Z(Number(a.el.toPrecision(3)))}`];return a.lol!==null&&i.push(`lol ${he(a.lol)}`),a.count!==null&&i.push(`${a.count.toPrecision(2)} claims`),a.cv!==null&&i.push(`cv ${a.cv.toPrecision(3)}`),i.push(`indication ${Z(a.premium)}`),a.loss_ratio!==null&&(i[i.length-1]+=` (LR ${he(a.loss_ratio)})`),` ${i.join(", ")}`}const Is=Ft(bt,350);for(const e of Nn)u(e)?.addEventListener("input",Is);for(const e of["qr-basis-occ","qr-basis-agg"])u(e)?.addEventListener("change",bt);function qa(){for(const e of Nn){const t=u(e);t&&(t.value=Ts[e])}Sn(null),bt()}function Sn(e){const t=u("qr-quotes");if(!t)return;t.classList.toggle("d-none",!e);const n=()=>{if(ct("qr-quotes"),P(t),!e)return;const a=s("div");t.appendChild(a),a.appendChild(s("p",{className:"qr-quotes-title"},"Last quote, layer by layer"));const i=s("div");a.appendChild(i),gt("qr-quotes",i,{doc:e},ve),je("qr-quotes",n,a)};n()}async function Ia(e,t){if(!c.id||!R("canReins")||!e||e.hasAttribute("disabled"))return;let n;try{n=await t()}catch(i){const o=u("qr-preview");o&&(o.textContent=i.message);return}let a=null;await ot(e,"Ceding…",async i=>{const o=await b.reins(i,n,{price:!0});return a=o.ir?.quotes||null,o},"reinsurance"),Sn(a),bt()}function Oa(){return Ia(Fa,Rs)}function Os(){return Ia(Ma,Ds)}Fa?.addEventListener("click",Oa);Ma?.addEventListener("click",Os);for(const e of Nn)u(e)?.addEventListener("keydown",t=>{t.key==="Enter"&&(t.preventDefault(),Oa())});u("qr-help")&&un.getOrCreateInstance(u("qr-help"));async function js(e,t=null){M&&(M.dispose(),M=null);const n=()=>b.frameOf(c.id,e,{resolution:"display"});await Ba("pane-reinsurance",e,{...ve,renderCap:8192},n,t)}async function Gn(e,t){M&&(M.dispose(),M=null),await I("pane-reinsurance","reins",t,e)}const Vs=[["plot","Plot"],["tails","Plot tail"],["summary","Summary"]],Rt={plot:"approximation",tails:"approximation_tails"},Kn="the implied tail needs a single severity, so an aggregate only";let $t="plot";function ja(e){const t=Rt[e];return!!t&&c.caps.charts.has(t)}function rn(){return Rt[$t]&&!ja($t)?"summary":$t}function Yn(){const e=s("div",{className:"tab-tools"}),t=s("div",{className:"btn-group btn-group-sm",role:"group"});t.setAttribute("aria-label","approximation reading");const n=rn();for(const[a,i]of Vs){const o=!!Rt[a]&&!ja(a),r=s("button",{type:"button",className:"btn btn-outline-secondary"+(a===n?" active":"")},i);r.setAttribute("aria-pressed",String(a===n)),o?(r.setAttribute("aria-disabled","true"),r.setAttribute("data-why",Kn),r.setAttribute("aria-label",`${i}, ${Kn}`)):r.addEventListener("click",()=>{a!==rn()&&($t=a,fn(Pt("more"),Va()))}),t.appendChild(r)}return e.appendChild(t),e}async function Va(){const e=rn();if(e==="summary"){await I("pane-more","approximation",["more","approximation"],null,Yn);return}const t=s("div");t.appendChild(Yn());const n=We("more","approximation");n&&t.appendChild(n);const a=s("div",{className:"overview-plot plot-half"});t.appendChild(a),k("pane-more",t);let i=!1;try{me=await Tt(a,{id:c.id,chart:Rt[e]})}catch{i=!0}me||(P(a),a.appendChild(i?Bt():ke()))}let st=null,_t=null,rt=null,Re=null,$e=null,Je=null,te=null;function Wa(){st=null,_t=null,rt=null,Re=null,$e=null,Je=null,te=null}const Un={calibrate:"leaf-price",standalone:"leaf-price",allocate:"leaf-allocate",plot:"leaf-kappa",evaluate:"leaf-evaluate",ruin:"leaf-ruin"};async function Me(e){const t=Un[e];for(const n of new Set(Object.values(Un)))u(n).classList.toggle("d-none",n!==t);u("pane-calibrate").classList.toggle("d-none",e!=="calibrate"),u("pane-standalone").classList.toggle("d-none",e!=="standalone"),e==="evaluate"?(Xa(),c.kind==="pnl"&&!rt?Za({}):Le("evaluate")):e==="ruin"?await Ys():e==="plot"?await Gs():e==="allocate"?(tt.write(te),Le(e)):(et.write(te),Le(e))}const Ws={calibrate:["pane-calibrate","pricing.calibrate",()=>st,"Calibrate"],standalone:["pane-standalone","pricing.stand_alone",()=>st,"Calibrate"],allocate:["pane-allocate","pricing.allocate",()=>_t,"Allocate"],evaluate:["pane-evaluate","pricing.evaluate",()=>rt,"Evaluate"],ruin:["pane-ruin-stats","ruin",()=>$e,"Draw"]};function Le(e){const[t,n,a,i]=Ws[e],o=a(),r=o?.exhibits?.[n]||null,l=r?r[Ie]||r.insurer:null,p=()=>{const d=s("div",{className:"overview-exhibits exhibit-blocks"});k(t,d);const g=We("pricing",e);if(g&&d.appendChild(g),!l){d.appendChild(s("div",{className:"text-muted small"},`Press ${i}.`)),je(t,p,d);return}for(const m of l.blocks||[]){const{caption:L,...v}=m,$=s("div");d.appendChild($),gt(t,$,{doc:v},ve),L&&d.appendChild(s("div",{className:"exhibit-caption"},L))}for(const m of o.warnings||[])d.appendChild(s("div",{className:"text-muted small fst-italic mt-1"},`⚠ ${m}`));je(t,p,d)};p()}const vt=()=>({id:c.id,kind:c.kind,bases:c.caps.flags.reinsBases||[],canPreview:R("canPrice")||c.kind==="pnl"});function Dt(e,t){t&&(te={octet:t,anchor:"a"in e?"a":"p",target:"premium"in e?"premium":"lr"in e?"lr":"coc",basis:e.basis||null,expense:e.expense_ratio??null})}const Qn=()=>$n("pricing")==="standalone"?"standalone":"calibrate",et=ut(u("price-form"),{verb:"Calibrate",basisLabel:"calibrate on",preview:!0,expense:!0,help:"Fix capital with a VaR probability p or an asset level, and name one target: a cost of capital, a loss ratio, or the premium itself. Calibrate fits the standard distortion families to that point on the chosen view. A non-zero expense ratio reads a premium target as gross and calibrates its technical part; the preview then reports both. The line below previews the completed pentagon as you type, and is where an impossible ask explains itself before the press.",context:vt,onSubmit:async e=>{if(c.id){et.setBusy(!0,"Calibrating…");try{st=await b.pricingCalibrate(c.id,e),Dt(e,et.held()),Le(Qn())}catch(t){st=null,k(Qn()==="standalone"?"pane-standalone":"pane-calibrate",ne(t))}finally{et.setBusy(!1)}}}}),Hs=(e,t)=>t==="port"?e:e.filter(n=>n==="gross"),tt=ut(u("allocate-form"),{verb:"Allocate",basisLabel:"allocate on",preview:!0,expense:!0,help:"The same anchor and target as Calibrate, struck once and split across the parts: the units of a book, or the ceded and net halves of an occurrence program. The allocation splits a gross premium, which is why an aggregate offers Gross alone here. A non-zero expense ratio reads a premium target as gross and allocates its technical part. The line below previews the pentagon as you type.",basisOnly:Hs,basisWhy:"net and ceded are this tab’s outputs, not its inputs",context:vt,onSubmit:async e=>{if(c.id){tt.setBusy(!0,"Allocating…");try{_t=await b.pricingAllocate(c.id,e),Dt(e,tt.held()),Le("allocate")}catch(t){_t=null,k("pane-allocate",ne(t))}finally{tt.setBusy(!1)}}}});async function Gs(){z&&(z.dispose(),z=null);const e=u("pane-kappa");ct("pane-kappa"),P(e);const t=s("div",{className:"overview-plot"});e.appendChild(t);let n=!1;try{z=await Tt(t,{id:c.id,chart:"kappa"})}catch{n=!0}z||(P(e),e.appendChild(n?Bt():ke()))}const Pn=s("input",{type:"number",step:"0.001",min:"0",max:"1",value:"0.05",autocomplete:"off"}),Ha=s("span",{className:"text-muted ms-2 form-gloss"}),lt=s("button",{className:"btn btn-outline-secondary btn-sm"},"Sample");lt.title="fresh paths, same question";const Ks=s("div",{className:"tab-tools price-form"},s("span",{className:"exhibit-group-label"},"Pr default"),s("label",{className:"price-field"},Pn),lt,Ha);let Xt=0;async function qt({sample:e=!1}={}){if(!c.id||!c.caps?.charts?.has("ruin"))return;const t=zt.read();if(!t)return;const n=parseFloat(Pn.value);if(Number.isFinite(n)&&n>0&&n<1)t.ruin_p=n;else return;e?t.sample=!0:Je!=null&&(t.seed=Je);const a=++Xt;zt.setBusy(!0,e?"Sampling…":"Drawing…"),lt.disabled=!0;try{const i=await b.ruin(c.id,t);if(a!==Xt)return;$e=i,Je=i.chart?.meta?.seed??Je,Ga()}catch(i){a===Xt&&k("pane-ruin",ne(i))}finally{zt.setBusy(!1),lt.disabled=!1}}function Ga(){if(!$e)return;const e=s("div");k("pane-ruin",e),fe=cn(e,$e.chart),fe||k("pane-ruin",ke()),Le("ruin");const t=$e.chart?.meta||{};Ha.textContent=`u ${H(t.u)}, psi ${he(t.psi_exact)}, simulated ${he(t.psi_sim)}, seed ${t.seed??""}`}async function Ys(){if($e){Ga();return}await qt()}const Ka=Ft(()=>qt(),350),zt=ut(u("ruin-form"),{verb:"Draw",preview:!0,help:"The premium half is the ordinary pricing row; Pr default below states a probability of eventual ruin, which the library resolves to an initial surplus. The picture tracks the form live. Draw asks now, without waiting out the debounce; Sample rolls fresh paths on a new seed. The readout reports the surplus bought, the exact and simulated ruin probabilities, and the seed.",context:vt,extras:Ks,onChange:Ka,onSubmit:()=>qt()});lt.addEventListener("click",()=>qt({sample:!0}));Pn.addEventListener("input",Ka);const Us={bounds:"the band every consistent distortion sweeps, with fifty of them drawn",pricing:"name a unit of this object, or write DecL for a line that does not exist yet",allocation:"each unit’s range, consistent with the total premium"};let nt="bounds";const Ya=s("input",{type:"text",autocomplete:"off",autocorrect:"off",autocapitalize:"off",spellcheck:"false",placeholder:"a unit name, or DecL for a new line"}),Ua=s("label",{className:"price-field bounds-against d-none"},s("span",{className:"qr-op"},"against"),Ya);async function Zt(e){nt=e,Ua.classList.toggle("d-none",e!=="pricing"),u("bounds-hint").textContent=Us[e]||"",Qs(xe);const t=e==="bounds"&&c.kind==="pnl";if(k("pane-bounds",s("div",{className:"text-muted small"},t?"Computing at the ledger’s own premium…":"Set a premium and press Compute.")),!t)return;const n=c.id;try{const a=await b.pricingPreview(n,xe.read()||{p:.99,coc:.15});if(n!==c.id||nt!=="bounds")return;Number.isFinite(a.net_of_expense_premium)&&xe.write({anchor:"p",target:"premium",octet:{p:.99,premium:a.net_of_expense_premium}}),Qa(xe.read())}catch(a){n===c.id&&nt==="bounds"&&k("pane-bounds",ne(a))}}function Qs(e){if(te?.basis&&te.basis!=="net"){e.note(`The pricing on hand was struck on the ${te.basis} view. This group answers on the object’s own distribution, so it is not carried over; type a premium to sweep one.`);return}e.write(te)}function Xn(e,t){const n="pane-bounds",a=e.ir||{},i=t==="pricing"?`With this object priced at ${Z(e.premium)}`:`Consistent with a total premium of ${Z(e.premium)}`,o=t==="pricing"?"Lower and upper bound what the named risk can cost under every distortion that prices this object, the base risk, to the premium above. Width is the reading: it is how much of the answer the choice of distortion decides rather than the base pricing.":"Lower and upper are the ends of the range over every distortion that prices this object to the premium above. Width is the reading: it is how much of the answer the choice of distortion decides rather than the calibration.",r=()=>{const l=s("div",{className:"price-result"});k(n,l),l.appendChild(s("div",{className:"price-section-title"},i)),l.appendChild(s("div",{className:"exhibit-caption mb-2"},o));const p=s("div");l.appendChild(p),gt(n,p,a.table?{doc:a.table}:{frame:e.table},{...ve,maxRows:30}),je(n,r,l)};r()}const xe=ut(u("bounds-form"),{verb:"Compute",basisLabel:null,help:"Set the premium the sweep holds fixed: every distortion consistent with it is ranged over, and the width of the band is how much of the price the choice of distortion decides. A cost of capital or loss ratio target is resolved to its premium through the pentagon first; the line below previews that resolution, and is where a premium below the expected loss refuses before the press.",preview:!0,extras:Ua,context:vt,onSubmit:e=>Qa(e)});async function Qa(e){if(!(!c.id||!e)){xe.setBusy(!0,"Computing…");try{const t=await b.pricingPreview(c.id,e);Dt(e,t);const n=t.premium,a=Number.isFinite(t.assets)?t.assets:null;if(!Number.isFinite(n))return;if(nt==="bounds"){const i=await b.boundsEnvelope(c.id,{premium:n,assets:a}),o=s("div",{className:"bounds-figure"});k("pane-bounds",o),X&&(X.dispose(),X=null),X=cn(o,i),X||k("pane-bounds",ke())}else if(nt==="allocation")Xn(await b.allocationBounds(c.id,{premium:n,assets:a}),"allocation");else{const i=Ya.value.trim();if(!i)return;Xn(await b.pricingBounds(c.id,{premium:n,assets:a,against:[i]}),"pricing")}}catch(t){k("pane-bounds",ne(t))}finally{xe.setBusy(!1)}}}function Xa(){const e=c.kind==="pnl";if(pe.setDormant(e),pe.sync(),e){pe.note(za),Xs();return}if(te){pe.write(te);return}const t=c.caps.flags.premium;Number.isFinite(t)&&pe.write({octet:{premium:t},anchor:"p",target:"premium"})}const za="A P&L evaluates every row of its ledger on that row’s own terms; computed automatically.";async function Xs(){const e=c.id;if(!e)return;const t=n=>pe.note(`${za} Ledger: gross premium ${H(n.gross)}, net premium ${H(n.net)}, net of expense premium ${H(n.netOfExpense)}.`);if(Re&&Re.id===e){t(Re);return}try{const n=await b.pricingPreview(e,{p:.99,coc:.15});if(e!==c.id||c.kind!=="pnl"||n.gross_premium==null||n.net_of_expense_premium==null)return;Re={id:e,gross:n.gross_premium,net:n.net_premium,netOfExpense:n.net_of_expense_premium},t(Re)}catch{}}let Jt=!1;async function Za(e){if(!(!c.id||Jt)){Jt=!0,pe.setBusy(!0,"Evaluating…");try{if(rt=await b.pricingEvaluate(c.id,e),c.kind!=="pnl"){const t=await b.pricingPreview(c.id,{...Number.isFinite(e.a)?{a:e.a}:{p:e.p??.99},premium:e.premium??c.caps.flags.premium,...e.basis?{basis:e.basis}:{},...e.expense_ratio!=null?{expense_ratio:e.expense_ratio}:{}}).catch(()=>null);Dt({...e,premium:e.premium},t)}Le("evaluate")}catch(t){rt=null,k("pane-evaluate",ne(t))}finally{pe.setBusy(!1),Jt=!1}}}const pe=ut(u("evaluate-form"),{verb:"Evaluate",basisLabel:"premium is",allowBlank:!0,expense:!0,help:"Inputs to determine premium on gross, net of occurrence, or net basis, input assets or solvency p value, the cost of capital, loss ratio, or enter gross premium, and finally the expense ratio.",preview:!0,context:vt,onSubmit:async e=>{if(!c.id)return;const t={};if(c.kind!=="pnl"){if(Number.isFinite(e.p)&&(t.p=e.p),Number.isFinite(e.a)&&(t.a=e.a),e.basis&&(t.basis=e.basis),Number.isFinite(e.coc)||Number.isFinite(e.lr)){if(!("p"in t)&&!("a"in t))return;try{const n={..."a"in t?{a:t.a}:{p:t.p},...Number.isFinite(e.coc)?{coc:e.coc}:{lr:e.lr},...t.basis?{basis:t.basis}:{}},a=await b.pricingPreview(c.id,n);if(!Number.isFinite(a?.premium))return;t.premium=a.premium}catch(n){k("pane-evaluate",ne(n));return}}else if(Number.isFinite(e.premium))t.premium=e.premium,Number.isFinite(e.expense_ratio)&&(t.expense_ratio=e.expense_ratio);else if(R("needsPremium"))return}Za(t)}});document.querySelectorAll(".price-form .qr-help").forEach(e=>{un.getOrCreateInstance(e)});const re={cursor:-1};function zs(){const e=ln().length,t=re.cursor;return{m:t<0?0:t+1,n:e}}function An(e,t=!0){if(E.setText(e),qa(),E.focus(),be(),t)return;const n=re.cursor;b.formatDecl(e).then(a=>{re.cursor===n&&a&&a.decl&&E.setText(a.decl)}).catch(()=>{})}function Ja(e){_.caption=e?{note:e.note,tags:e.tags||[]}:null,mt()}function ei(e){Ve="examples",re.cursor=ln().indexOf(e),Ja(e),An(e.decl),Ne(),be(),Ee()}si(u("examples-menu"),ei);ri(ei);li().catch(()=>{});ci(()=>{re.cursor=-1,Ne()});function Zs(){Ee()}zo();ge();Zs();const Js=Ft(()=>{be(),Ee()},450);function zn(e){const t=ln(),n=t.length;if(!n)return;const a=re.cursor;a<0?re.cursor=e==="prev"?n-1:0:re.cursor=e==="prev"?(a-1+n)%n:(a+1)%n,Ve="examples";const i=t[re.cursor];Ja(i),An(i.decl),Ne(),Js()}const Zn=u("help-load");Zn&&Zn.addEventListener("click",()=>{const e=u("help-example").textContent.trim(),t=u("helpPanel");t.addEventListener("hidden.bs.offcanvas",()=>E.focus(),{once:!0}),An(e,!1),bi.getOrCreateInstance(t).hide()});u("about-grid").textContent="3.10.1";u("about-echarts").textContent="5.6.0";u("about-echarts-gl").textContent="2.1.0";u("about-bootstrap").textContent="5.3.8";b.meta().then(e=>{u("about-aggregate").textContent=e.aggregate_version,u("about-api").textContent=e.version,u("about-tables").textContent=e.tables_version;const t=u("nav-versions");t&&(t.textContent=`agg ${e.aggregate_version} · api ${e.version}`),er(e.plugins||[])}).catch(()=>{u("about-api").textContent="(api offline)"});function er(e){const t=Co(e),n=u("tab-lab-slot");n&&n.classList.toggle("d-none",t===0);const a=u("about-plugins");if(a){if(!e.length){a.textContent="none";return}a.textContent=e.map(i=>{const o=i.version?` ${i.version}`:"";return i.error?`${i.name}${o} (failed: ${i.error})`:`${i.name}${o}`}).join(", ")}}u("dl-agg")?.addEventListener("click",()=>window.open(b.sessionModelsUrl("agg")));"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js").catch(()=>{})});
|