dhruv575 commited on
Commit
5a590e8
·
1 Parent(s): 277da82

Education tab

Browse files
app.py CHANGED
@@ -239,12 +239,28 @@ async def serve_frontend():
239
  """Serve the custom frontend HTML."""
240
  html_path = Path(__file__).parent / "assets" / "static" / "index.html"
241
  if html_path.exists():
242
- with open(html_path) as f:
243
  content = f.read()
244
  return HTMLResponse(content=content)
245
  else:
246
  return {"error": "Frontend HTML file not found"}
247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  @app.get("/api/tickers_by_sector")
249
  async def get_tickers_by_sector():
250
  """Return the tickers grouped by sector."""
 
239
  """Serve the custom frontend HTML."""
240
  html_path = Path(__file__).parent / "assets" / "static" / "index.html"
241
  if html_path.exists():
242
+ with open(html_path, 'r', encoding='utf-8') as f:
243
  content = f.read()
244
  return HTMLResponse(content=content)
245
  else:
246
  return {"error": "Frontend HTML file not found"}
247
 
248
+ @app.get("/index.html")
249
+ async def serve_index():
250
+ """Serve the index page HTML."""
251
+ return await serve_frontend()
252
+
253
+ @app.get("/education.html")
254
+ async def serve_education():
255
+ """Serve the education page HTML."""
256
+ html_path = Path(__file__).parent / "assets" / "static" / "education.html"
257
+ if html_path.exists():
258
+ with open(html_path, 'r', encoding='utf-8') as f:
259
+ content = f.read()
260
+ return HTMLResponse(content=content)
261
+ else:
262
+ return {"error": "Education HTML file not found"}
263
+
264
  @app.get("/api/tickers_by_sector")
265
  async def get_tickers_by_sector():
266
  """Return the tickers grouped by sector."""
assets/static/education.html ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Portfolio Optimizer - Education</title>
7
+ <link rel="stylesheet" href="/static/style.css">
8
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap">
9
+ <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
10
+ <script src="https://cdn.jsdelivr.net/npm/luxon@3.0.1/build/global/luxon.min.js"></script>
11
+ <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@1.2.0/dist/chartjs-adapter-luxon.min.js"></script>
12
+ <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@2.1.0/dist/chartjs-plugin-annotation.min.js"></script>
13
+ <script src="https://cdn.jsdelivr.net/npm/katex@0.16.0/dist/katex.min.js"></script>
14
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.0/dist/katex.min.css">
15
+ </head>
16
+ <body>
17
+ <div class="container">
18
+ <header class="header">
19
+ <div class="title-container">
20
+ <h1>Portfolio Optimizer</h1>
21
+ </div>
22
+ <nav class="nav-menu">
23
+ <a href="/index.html" class="nav-link">Simulation</a>
24
+ <a href="/education.html" class="nav-link active">Education</a>
25
+ </nav>
26
+ </header>
27
+
28
+ <div class="education-container">
29
+ <div class="education-header">
30
+ <h2>Educational Resources</h2>
31
+ <p>
32
+ This page is designed to help you understand the components of our portfolio optimization objective function.
33
+ Through interactive demonstrations with synthetic data, you'll see how different components affect portfolio performance
34
+ and learn the mathematical concepts behind modern portfolio theory and online convex optimization.
35
+ </p>
36
+ </div>
37
+
38
+ <div class="variable-definitions">
39
+ <h3>Variable Definitions</h3>
40
+ <div class="variable-grid">
41
+ <div class="variable-math">
42
+ <span class="math-symbol">w<sub>t</sub> ∈ ℝ<sup>N</sup></span>
43
+ </div>
44
+ <div class="variable-description">
45
+ Portfolio weights at time t
46
+ </div>
47
+
48
+ <div class="variable-math">
49
+ <span class="math-symbol">R<sub>t</sub> ∈ ℝ</span>
50
+ </div>
51
+ <div class="variable-description">
52
+ Portfolio return at time t
53
+ </div>
54
+
55
+ <div class="variable-math">
56
+ <span class="math-symbol">r<sub>f,t</sub> ∈ ℝ</span>
57
+ </div>
58
+ <div class="variable-description">
59
+ Risk-free rate at time t
60
+ </div>
61
+
62
+ <div class="variable-math">
63
+ <span class="math-symbol">a<sub>i</sub> ∈ ℝ<sub>+</sub></span>
64
+ </div>
65
+ <div class="variable-description">
66
+ Objective weights, i ∈ {1,2,3,4}
67
+ </div>
68
+
69
+ <div class="variable-math">
70
+ <span class="math-symbol">ε ∈ ℝ<sub>+</sub></span>
71
+ </div>
72
+ <div class="variable-description">
73
+ Small constant for numerical stability
74
+ </div>
75
+ </div>
76
+ </div>
77
+
78
+ <!-- Sortino Ratio Section -->
79
+ <div class="subsection" id="sortino-ratio">
80
+ <h3>Sortino Ratio</h3>
81
+ <p>
82
+ The Sortino ratio is a modification of the Sharpe ratio that differentiates harmful volatility from total overall volatility.
83
+ It was developed by Frank A. Sortino in the early 1980s and has become an important risk-adjusted performance metric in
84
+ portfolio management. Unlike the Sharpe ratio, which penalizes both upside and downside volatility equally,
85
+ the Sortino ratio only penalizes downside volatility - recognizing that investors are typically concerned
86
+ with the risk of losing money rather than the "risk" of making more than expected.
87
+ </p>
88
+
89
+ <div class="formula-container">
90
+ <div class="formula">
91
+ <p class="formula-header">Sortino Ratio Formula:</p>
92
+ <div class="formula-content">
93
+ <p>Sortino(r, r<sub>f</sub>) = <span class="fraction"><span class="numerator">E[R<sub>t</sub> - r<sub>f,t</sub>]</span><span class="denominator">σ<sub>downside</sub> + ε</span></span></p>
94
+ <p class="formula-notation">where</p>
95
+ <p>σ<sub>downside</sub> = <span class="sqrt"><span class="sqrt-content"><span class="fraction"><span class="numerator">1</span><span class="denominator">T</span></span> ∑<sub>t=1</sub><sup>T</sup> min(R<sub>t</sub> - r<sub>f,t</sub>, 0)<sup>2</sup></span></span></p>
96
+ </div>
97
+ </div>
98
+ <div class="formula-explanation">
99
+ <p><strong>E[R<sub>t</sub> - r<sub>f,t</sub>]</strong>: Expected excess return (portfolio return minus risk-free rate)</p>
100
+ <p><strong>σ<sub>downside</sub></strong>: Downside deviation (standard deviation of negative returns only)</p>
101
+ <p><strong>ε</strong>: Small constant to avoid division by zero when downside deviation is zero</p>
102
+ </div>
103
+ </div>
104
+
105
+ <p>
106
+ In our objective function, maximizing the Sortino ratio is the first term. By focusing on downside risk,
107
+ our optimization algorithm seeks to maximize returns while minimizing the risk of significant losses,
108
+ which aligns with most investors' preferences and behavioral tendencies.
109
+ </p>
110
+
111
+ <div class="interactive-demo">
112
+ <h4>Interactive Demonstration</h4>
113
+ <p>
114
+ Below are two charts showing the performance of three synthetic assets with distinctly different risk-return profiles over a 4-month period.
115
+ The left chart shows the cumulative returns of each asset, while the right chart displays their corresponding 10-day Sortino ratios.
116
+ Notice how the Sortino ratio responds to downside volatility while ignoring positive volatility, making it a valuable measure for risk-averse investors.
117
+ </p>
118
+
119
+ <div class="chart-container">
120
+ <div class="edu-chart">
121
+ <h4>Cumulative Returns</h4>
122
+ <canvas id="returnsChart"></canvas>
123
+ </div>
124
+ <div class="edu-chart">
125
+ <h4>Sortino Ratios</h4>
126
+ <canvas id="sortinoChart"></canvas>
127
+ </div>
128
+ </div>
129
+
130
+ <div class="asset-descriptions">
131
+ <div class="asset-description">
132
+ <h5>Asset A: Volatile with Spike Patterns</h5>
133
+ <p>This asset exhibits a "spikey" pattern with dramatic upward and downward movements, resulting in high volatility and unpredictable Sortino ratios.</p>
134
+ </div>
135
+ <div class="asset-description">
136
+ <h5>Asset B: Exponential Growth with Limited Downside</h5>
137
+ <p>This asset follows an exponential growth curve with very limited downside risk, resulting in a consistently high Sortino ratio despite moderate returns.</p>
138
+ </div>
139
+ <div class="asset-description">
140
+ <h5>Asset C: Linear Growth with Minimal Volatility</h5>
141
+ <p>This asset shows a nearly linear growth pattern with very low volatility in both directions, making it highly predictable but with limited return potential.</p>
142
+ </div>
143
+ </div>
144
+ </div>
145
+ </div>
146
+
147
+ <!-- Maximum Drawdown Section -->
148
+ <div class="subsection" id="maximum-drawdown">
149
+ <h3>Maximum Drawdown</h3>
150
+ <p>
151
+ Maximum Drawdown (MDD) is a key risk metric that measures the largest peak-to-trough decline in the value of a portfolio
152
+ before a new peak is achieved. Unlike volatility-based metrics that treat upward and downward movements equally,
153
+ maximum drawdown specifically focuses on the largest sustained loss an investor might experience, making it
154
+ particularly important for assessing downside risk.
155
+ </p>
156
+
157
+ <div class="formula-container">
158
+ <div class="formula">
159
+ <p class="formula-header">Maximum Drawdown Formula:</p>
160
+ <div class="formula-content">
161
+ <p>MaxDD(r) = <span class="fraction"><span class="numerator">max<sub>t∈[1,T]</sub> CR<sub>t</sub> - CR<sub>T</sub></span><span class="denominator">max<sub>t∈[1,T]</sub> CR<sub>t</sub> + ε</span></span></p>
162
+ <p class="formula-notation">where</p>
163
+ <p>CR<sub>t</sub> = ∏<sub>i=1</sub><sup>t</sup>(1 + R<sub>i</sub>)</p>
164
+ </div>
165
+ </div>
166
+ <div class="formula-explanation">
167
+ <p><strong>CR<sub>t</sub></strong>: Cumulative return at time t</p>
168
+ <p><strong>max<sub>t∈[1,T]</sub> CR<sub>t</sub></strong>: Maximum cumulative return up to time T</p>
169
+ <p><strong>CR<sub>T</sub></strong>: Final cumulative return</p>
170
+ <p><strong>ε</strong>: Small constant for numerical stability</p>
171
+ </div>
172
+ </div>
173
+
174
+ <p>
175
+ In our objective function, minimizing maximum drawdown is the second term. By reducing the severity of prolonged
176
+ declines, our optimization algorithm aims to protect capital during market downturns while still seeking growth
177
+ opportunities. This is especially valuable for investors with lower risk tolerance or shorter time horizons.
178
+ </p>
179
+
180
+ <div class="interactive-demo">
181
+ <h4>Interactive Demonstration</h4>
182
+ <p>
183
+ Below are two charts demonstrating maximum drawdown for three synthetic assets over a 4-month period.
184
+ The left chart shows the cumulative returns with the maximum drawdown periods highlighted, while the right chart
185
+ displays the drawdown percentage over time (distance from previous peak). Notice how different return patterns lead to
186
+ varying drawdown profiles, even for assets with similar overall returns.
187
+ </p>
188
+
189
+ <div class="chart-container">
190
+ <div class="edu-chart">
191
+ <h4>Cumulative Returns with Drawdown Periods</h4>
192
+ <canvas id="mddReturnsChart"></canvas>
193
+ </div>
194
+ <div class="edu-chart">
195
+ <h4>Drawdown Percentage</h4>
196
+ <canvas id="drawdownChart"></canvas>
197
+ </div>
198
+ </div>
199
+
200
+ <div class="asset-descriptions">
201
+ <div class="asset-description">
202
+ <h5>Asset D: Steady Growth with One Major Correction</h5>
203
+ <p>This asset shows generally positive performance but experiences one significant correction, creating a large maximum drawdown despite good overall returns.</p>
204
+ </div>
205
+ <div class="asset-description">
206
+ <h5>Asset E: Volatile with Frequent Drawdowns</h5>
207
+ <p>This asset has multiple smaller drawdowns throughout the period, demonstrating how frequent minor corrections affect the drawdown profile.</p>
208
+ </div>
209
+ <div class="asset-description">
210
+ <h5>Asset F: Declining Trend with Recovery</h5>
211
+ <p>This asset shows a prolonged decline followed by recovery, illustrating how a negative trend creates extended drawdown periods even with eventual improvement.</p>
212
+ </div>
213
+ </div>
214
+ </div>
215
+ </div>
216
+
217
+ <!-- Turnover Ratio Section -->
218
+ <div class="subsection" id="turnover-ratio">
219
+ <h3>Turnover Ratio</h3>
220
+ <p>
221
+ The Turnover Ratio measures the frequency and magnitude of changes in portfolio weights between consecutive time periods.
222
+ High turnover typically results in increased transaction costs, which can significantly impact net returns, especially in
223
+ strategies with frequent rebalancing. In optimization, controlling turnover is essential for creating portfolios that are
224
+ both profitable and practically implementable.
225
+ </p>
226
+
227
+ <div class="formula-container">
228
+ <div class="formula">
229
+ <p class="formula-header">Turnover Ratio Formula:</p>
230
+ <div class="formula-content">
231
+ <p>Turnover(w<sub>t</sub>, w<sub>t-1</sub>) = <span class="fraction"><span class="numerator">1</span><span class="denominator">2</span></span> ∑<sub>i=1</sub><sup>N</sup> |w<sub>t,i</sub> - w<sub>t-1,i</sub>|</p>
232
+ </div>
233
+ </div>
234
+ <div class="formula-explanation">
235
+ <p><strong>w<sub>t,i</sub></strong>: Weight of asset i at time t</p>
236
+ <p><strong>w<sub>t-1,i</sub></strong>: Weight of asset i at time t-1</p>
237
+ <p><strong>N</strong>: Number of assets in the portfolio</p>
238
+ <p><strong>0.5 multiplier</strong>: Makes the measure represent the minimum fraction of the portfolio that must be traded</p>
239
+ </div>
240
+ </div>
241
+
242
+ <p>
243
+ In our objective function, minimizing turnover is the third term. The measure ranges from 0 (no change in weights) to 1
244
+ (complete portfolio turnover). By penalizing excessive turnover, the optimization algorithm balances the desire for
245
+ optimal positioning against the practical costs of frequent trading, resulting in more efficient portfolio adjustments.
246
+ </p>
247
+
248
+ <div class="interactive-demo">
249
+ <h4>Interactive Demonstration</h4>
250
+ <p>
251
+ Below are three examples of different portfolio turnover patterns, each showing a 3-asset portfolio over time.
252
+ The left charts show weight allocations for each strategy, while the right charts display the corresponding turnover ratio.
253
+ These examples illustrate how different rebalancing approaches impact turnover and associated trading costs.
254
+ </p>
255
+
256
+ <!-- Portfolio 1: Stable Weights -->
257
+ <h5 class="demo-title">Portfolio 1: Stable Allocation</h5>
258
+ <p class="demo-description">
259
+ This portfolio maintains relatively stable weights over time (approximately 40%, 35%, 25%), with only minor
260
+ adjustments to maintain target allocations. Note the consistently low turnover values.
261
+ </p>
262
+ <div class="chart-container">
263
+ <div class="edu-chart">
264
+ <h4>Portfolio Weights</h4>
265
+ <canvas id="weightsChart1"></canvas>
266
+ </div>
267
+ <div class="edu-chart">
268
+ <h4>Turnover Ratio</h4>
269
+ <canvas id="turnoverChart1"></canvas>
270
+ </div>
271
+ </div>
272
+
273
+ <!-- Portfolio 2: Erratic Trading -->
274
+ <h5 class="demo-title">Portfolio 2: Erratic Trading</h5>
275
+ <p class="demo-description">
276
+ This portfolio exhibits extreme day-to-day changes in allocations, frequently shifting substantial portions
277
+ of capital between assets. The resulting high turnover indicates excessive trading costs.
278
+ </p>
279
+ <div class="chart-container">
280
+ <div class="edu-chart">
281
+ <h4>Portfolio Weights</h4>
282
+ <canvas id="weightsChart2"></canvas>
283
+ </div>
284
+ <div class="edu-chart">
285
+ <h4>Turnover Ratio</h4>
286
+ <canvas id="turnoverChart2"></canvas>
287
+ </div>
288
+ </div>
289
+
290
+ <!-- Portfolio 3: Gradual Concentration -->
291
+ <h5 class="demo-title">Portfolio 3: Gradual Concentration</h5>
292
+ <p class="demo-description">
293
+ This portfolio starts with equal weights but gradually concentrates all capital into a single asset.
294
+ While daily turnover is moderate, the cumulative effect represents a complete portfolio transformation.
295
+ </p>
296
+ <div class="chart-container">
297
+ <div class="edu-chart">
298
+ <h4>Portfolio Weights</h4>
299
+ <canvas id="weightsChart3"></canvas>
300
+ </div>
301
+ <div class="edu-chart">
302
+ <h4>Turnover Ratio</h4>
303
+ <canvas id="turnoverChart3"></canvas>
304
+ </div>
305
+ </div>
306
+ </div>
307
+ </div>
308
+
309
+ <!-- Concentration Penalty Section -->
310
+ <div class="subsection" id="concentration-penalty">
311
+ <h3>Concentration Penalty</h3>
312
+ <p>
313
+ The Concentration Penalty helps maintain a balanced portfolio by discouraging excessive concentration in a small number of assets
314
+ or excessive diversification across too many assets. It uses the concept of Effective Number of Positions (ENP),
315
+ which measures portfolio diversification based on the Herfindahl-Hirschman Index (HHI),
316
+ a common measure of market concentration used in economics and finance.
317
+ </p>
318
+
319
+ <div class="formula-container">
320
+ <div class="formula">
321
+ <p class="formula-header">Concentration Penalty Formula:</p>
322
+ <div class="formula-content">
323
+ <p>CP(w<sub>t</sub>) = max(ENP<sub>min</sub> - ENP(w<sub>t</sub>), 0) + max(ENP(w<sub>t</sub>) - ENP<sub>max</sub>, 0)</p>
324
+ <p class="formula-notation">where</p>
325
+ <p>ENP(w<sub>t</sub>) = <span class="fraction"><span class="numerator">1</span><span class="denominator">HHI(w<sub>t</sub>) + ε</span></span></p>
326
+ <p>HHI(w<sub>t</sub>) = ∑<sub>i=1</sub><sup>N</sup> w<sub>t,i</sub><sup>2</sup></p>
327
+ </div>
328
+ </div>
329
+ <div class="formula-explanation">
330
+ <p><strong>ENP<sub>min</sub></strong>: Minimum target for the effective number of positions</p>
331
+ <p><strong>ENP<sub>max</sub></strong>: Maximum target for the effective number of positions</p>
332
+ <p><strong>ENP(w<sub>t</sub>)</strong>: Effective number of positions at time t</p>
333
+ <p><strong>HHI(w<sub>t</sub>)</strong>: Herfindahl-Hirschman Index at time t</p>
334
+ <p><strong>w<sub>t,i</sub></strong>: Weight of asset i at time t</p>
335
+ <p><strong>ε</strong>: Small constant for numerical stability</p>
336
+ </div>
337
+ </div>
338
+
339
+ <p>
340
+ In our objective function, the concentration penalty is the fourth term. It creates a "target range" for portfolio
341
+ diversification, adding a penalty when the portfolio's ENP falls below ENP<sub>min</sub> or exceeds ENP<sub>max</sub>.
342
+ This approach allows us to control portfolio concentration within desired bounds, balancing the benefits of diversification
343
+ against the potential for overdiversification.
344
+ </p>
345
+
346
+ <div class="interactive-demo">
347
+ <h4>Interactive Demonstration</h4>
348
+ <p>
349
+ Below are examples showing how different portfolio weight distributions affect concentration metrics,
350
+ with ENP targets of 3 (minimum) and 8 (maximum). The visualizations demonstrate how portfolios
351
+ with the same number of assets can have very different effective concentrations.
352
+ </p>
353
+
354
+ <!-- Portfolio Concentration Demo -->
355
+ <div class="chart-container">
356
+ <div class="edu-chart">
357
+ <h4>Portfolio Weight Distributions</h4>
358
+ <canvas id="concentrationWeightsChart"></canvas>
359
+ </div>
360
+ <div class="edu-chart">
361
+ <h4>Effective Number of Positions (ENP)</h4>
362
+ <canvas id="enpChart"></canvas>
363
+ </div>
364
+ </div>
365
+
366
+ <div class="concentration-explanations">
367
+ <div class="concentration-example">
368
+ <h5>Highly Concentrated Portfolio</h5>
369
+ <p>
370
+ This portfolio has most of its weight in just a few assets, resulting in an ENP below the minimum target.
371
+ The concentration penalty encourages adding more diversification to reach the target range.
372
+ </p>
373
+ <div class="enp-indicator">
374
+ <span class="enp-value">ENP ≈ 2.1</span>
375
+ <div class="enp-bar">
376
+ <div class="enp-progress" style="width: 26%;"></div>
377
+ <div class="enp-marker min-marker" style="left: 37.5%;">Min</div>
378
+ <div class="enp-marker max-marker" style="left: 100%;">Max</div>
379
+ </div>
380
+ </div>
381
+ </div>
382
+
383
+ <div class="concentration-example">
384
+ <h5>Balanced Portfolio</h5>
385
+ <p>
386
+ This portfolio has a balanced distribution of weights across assets, with an ENP within the target range.
387
+ No concentration penalty is applied since the portfolio diversification is optimal.
388
+ </p>
389
+ <div class="enp-indicator">
390
+ <span class="enp-value">ENP ≈ 5.8</span>
391
+ <div class="enp-bar">
392
+ <div class="enp-progress" style="width: 72.5%;"></div>
393
+ <div class="enp-marker min-marker" style="left: 37.5%;">Min</div>
394
+ <div class="enp-marker max-marker" style="left: 100%;">Max</div>
395
+ </div>
396
+ </div>
397
+ </div>
398
+
399
+ <div class="concentration-example">
400
+ <h5>Overly Diversified Portfolio</h5>
401
+ <p>
402
+ This portfolio has weights spread too thinly across many assets, with an ENP exceeding the maximum target.
403
+ The concentration penalty encourages more focus on fewer positions.
404
+ </p>
405
+ <div class="enp-indicator">
406
+ <span class="enp-value">ENP ≈ 9.6</span>
407
+ <div class="enp-bar">
408
+ <div class="enp-progress" style="width: 120%;"></div>
409
+ <div class="enp-marker min-marker" style="left: 37.5%;">Min</div>
410
+ <div class="enp-marker max-marker" style="left: 100%;">Max</div>
411
+ </div>
412
+ </div>
413
+ </div>
414
+ </div>
415
+
416
+ <!-- HHI vs ENP Relationship -->
417
+ <h5 class="demo-title">Relationship Between HHI and ENP</h5>
418
+ <p class="demo-description">
419
+ The chart below shows the inverse relationship between the Herfindahl-Hirschman Index (HHI) and the Effective Number of Positions (ENP).
420
+ As HHI increases (more concentration), ENP decreases (fewer effective positions).
421
+ </p>
422
+ <div class="chart-container">
423
+ <div class="edu-chart">
424
+ <h4>HHI vs ENP Relationship</h4>
425
+ <canvas id="hhiEnpChart"></canvas>
426
+ </div>
427
+ </div>
428
+ </div>
429
+ </div>
430
+
431
+ <!-- Integrated Objective Function Section -->
432
+ <div class="subsection" id="objective-function">
433
+ <h3>Integrated Objective Function</h3>
434
+ <p>
435
+ Our portfolio optimization approach combines all the previously discussed components into a single objective function.
436
+ This integrated approach allows us to balance multiple competing goals simultaneously:
437
+ maximizing risk-adjusted returns (Sortino ratio), minimizing maximum drawdown, controlling turnover,
438
+ and maintaining an appropriate level of diversification.
439
+ </p>
440
+
441
+ <div class="formula-container">
442
+ <div class="formula">
443
+ <p class="formula-header">Objective Function:</p>
444
+ <div class="formula-content">
445
+ <p>max<sub>w<sub>t</sub></sub> α<sub>1</sub> · Sortino(r, r<sub>f</sub>) - α<sub>2</sub> · MaxDD(r) - α<sub>3</sub> · Turnover(w<sub>t</sub>, w<sub>t-1</sub>) - α<sub>4</sub> · CP(w<sub>t</sub>)</p>
446
+ <p class="formula-notation">subject to:</p>
447
+ <p>Σ<sub>i=1</sub><sup>N</sup> w<sub>t,i</sub> = 1 and w<sub>t,i</sub> ≥ 0 ∀t,i</p>
448
+ </div>
449
+ </div>
450
+ <div class="formula-explanation">
451
+ <p><strong>α<sub>1</sub>, α<sub>2</sub>, α<sub>3</sub>, α<sub>4</sub></strong>: Objective weights that control the relative importance of each component</p>
452
+ <p><strong>Sortino(r, r<sub>f</sub>)</strong>: The Sortino ratio</p>
453
+ <p><strong>MaxDD(r)</strong>: Maximum drawdown</p>
454
+ <p><strong>Turnover(w<sub>t</sub>, w<sub>t-1</sub>)</strong>: Portfolio turnover</p>
455
+ <p><strong>CP(w<sub>t</sub>)</strong>: Concentration penalty</p>
456
+ </div>
457
+ </div>
458
+
459
+ <p>
460
+ The objective weights (α) allow us to customize the optimization for different investor preferences and market conditions.
461
+ For example, increasing α<sub>2</sub> puts more emphasis on drawdown protection, which may be preferable during volatile markets,
462
+ while increasing α<sub>3</sub> reduces turnover for more tax-efficient or lower-cost implementations.
463
+ </p>
464
+ </div>
465
+ </div>
466
+ </div>
467
+
468
+ <script src="/static/education.js"></script>
469
+ </body>
470
+ </html>
assets/static/education.js ADDED
@@ -0,0 +1,1354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Register the Chart.js annotation plugin if available
2
+ try {
3
+ // In Chart.js 3.x, the plugin is imported separately but needs to be registered
4
+ // In some bundled versions, it might be automatically available
5
+ const hasAnnotationPlugin =
6
+ typeof window.ChartAnnotation !== 'undefined' ||
7
+ (Chart && Chart.Annotation) ||
8
+ (Chart && Chart.registry && Chart.registry.plugins && Chart.registry.plugins.get('annotation'));
9
+
10
+ console.log('Chart.js version:', Chart.version);
11
+ console.log('Annotation plugin available:', hasAnnotationPlugin);
12
+
13
+ if (typeof window.ChartAnnotation !== 'undefined') {
14
+ Chart.register(window.ChartAnnotation);
15
+ console.log('Registered external ChartAnnotation plugin');
16
+ } else {
17
+ console.log('Using bundled annotation plugin or proceeding without it');
18
+ }
19
+ } catch (error) {
20
+ console.error('Error during Chart.js plugin setup:', error);
21
+ }
22
+
23
+ // Education page JavaScript
24
+
25
+ document.addEventListener('DOMContentLoaded', function() {
26
+ console.log('Education page loaded');
27
+
28
+ // Mark the current page in the navigation
29
+ const currentPath = window.location.pathname;
30
+ const navLinks = document.querySelectorAll('.nav-link');
31
+
32
+ navLinks.forEach(link => {
33
+ const linkPath = link.getAttribute('href');
34
+ if (currentPath.endsWith(linkPath) ||
35
+ (currentPath.endsWith('/') && linkPath === '/index.html')) {
36
+ link.classList.add('active');
37
+ } else {
38
+ link.classList.remove('active');
39
+ }
40
+ });
41
+
42
+ // Initialize the Sortino ratio demonstration
43
+ initializeSortinoDemo();
44
+
45
+ // Initialize the Maximum Drawdown demonstration
46
+ initializeMDDDemo();
47
+
48
+ // Initialize the Turnover Ratio demonstration
49
+ initializeTurnoverDemo();
50
+
51
+ // Initialize the Concentration Penalty demonstration
52
+ initializeConcentrationDemo();
53
+ });
54
+
55
+ // Utility function to calculate cumulative returns
56
+ function calculateCumulativeReturns(returns) {
57
+ let cumulative = 1.0;
58
+ return returns.map(ret => {
59
+ cumulative *= (1 + ret);
60
+ return cumulative;
61
+ });
62
+ }
63
+
64
+ // Utility function to calculate drawdowns from cumulative returns
65
+ function calculateDrawdowns(cumulativeReturns) {
66
+ let peak = cumulativeReturns[0];
67
+ return cumulativeReturns.map(cr => {
68
+ peak = Math.max(peak, cr);
69
+ return (peak - cr) / peak; // Drawdown as a percentage of the peak
70
+ });
71
+ }
72
+
73
+ // Utility function to calculate maximum drawdown
74
+ function calculateMaxDrawdown(cumulativeReturns) {
75
+ let peak = cumulativeReturns[0];
76
+ let maxDrawdown = 0;
77
+
78
+ cumulativeReturns.forEach(cr => {
79
+ peak = Math.max(peak, cr);
80
+ const drawdown = (peak - cr) / peak;
81
+ maxDrawdown = Math.max(maxDrawdown, drawdown);
82
+ });
83
+
84
+ return maxDrawdown;
85
+ }
86
+
87
+ // Utility function to find drawdown periods
88
+ function findDrawdownPeriods(cumulativeReturns, threshold = 0.05) {
89
+ const periods = [];
90
+ let inDrawdown = false;
91
+ let startIndex = 0;
92
+ let peak = cumulativeReturns[0];
93
+ let peakIndex = 0;
94
+
95
+ cumulativeReturns.forEach((cr, i) => {
96
+ if (cr > peak) {
97
+ peak = cr;
98
+ peakIndex = i;
99
+
100
+ // If we were in a drawdown, it's now over
101
+ if (inDrawdown) {
102
+ periods.push({
103
+ start: startIndex,
104
+ end: i - 1,
105
+ peakIndex: peakIndex
106
+ });
107
+ inDrawdown = false;
108
+ }
109
+ } else {
110
+ const drawdown = (peak - cr) / peak;
111
+
112
+ // Start tracking a new drawdown once it exceeds the threshold
113
+ if (!inDrawdown && drawdown >= threshold) {
114
+ inDrawdown = true;
115
+ startIndex = i;
116
+ }
117
+ }
118
+ });
119
+
120
+ // If we're still in a drawdown at the end, add the final period
121
+ if (inDrawdown) {
122
+ periods.push({
123
+ start: startIndex,
124
+ end: cumulativeReturns.length - 1,
125
+ peakIndex: peakIndex
126
+ });
127
+ }
128
+
129
+ return periods;
130
+ }
131
+
132
+ // Utility function to calculate Sortino ratio
133
+ function calculateSortinoRatio(returns, riskFreeRate, windowSize) {
134
+ if (returns.length < windowSize) {
135
+ return 0;
136
+ }
137
+
138
+ // Calculate excess returns
139
+ const excessReturns = returns.map(r => r - riskFreeRate);
140
+
141
+ // Calculate average excess return
142
+ const avgExcessReturn = excessReturns.reduce((a, b) => a + b, 0) / excessReturns.length;
143
+
144
+ // Calculate downside deviation (only consider negative excess returns)
145
+ const negativeExcessReturns = excessReturns.filter(r => r < 0);
146
+ if (negativeExcessReturns.length === 0) {
147
+ return 10; // Arbitrary high value when there are no negative returns
148
+ }
149
+
150
+ const downsideDeviation = Math.sqrt(
151
+ negativeExcessReturns.reduce((sum, r) => sum + r * r, 0) / negativeExcessReturns.length
152
+ );
153
+
154
+ // Small constant to avoid division by zero
155
+ const epsilon = 0.0001;
156
+
157
+ // Calculate Sortino ratio
158
+ return avgExcessReturn / (downsideDeviation + epsilon);
159
+ }
160
+
161
+ // Generate synthetic data for assets with different risk-return profiles
162
+ function generateSyntheticData(days = 120) {
163
+ const riskFreeRate = 0.0001; // Daily risk-free rate (approximately 2.5% annually)
164
+ const dates = [];
165
+ const today = new Date();
166
+
167
+ // Generate dates for the past 4 months
168
+ for (let i = days; i >= 0; i--) {
169
+ const date = new Date(today);
170
+ date.setDate(today.getDate() - i);
171
+ dates.push(date);
172
+ }
173
+
174
+ // Asset A: Highly volatile with spikey behavior (dramatic ups and downs)
175
+ const assetAReturns = Array(days + 1).fill(0).map((_, i) => {
176
+ // Base pattern with occasional sharp spikes both positive and negative
177
+ let baseReturn = 0.0005;
178
+
179
+ // Add spikes every ~10 days
180
+ if (i % 10 === 0) {
181
+ // Alternate between positive and negative spikes
182
+ return (i % 20 === 0) ? 0.025 : -0.02;
183
+ } else if (i % 10 === 1) {
184
+ // Follow-up correction
185
+ return (i % 20 === 1) ? -0.01 : 0.008;
186
+ }
187
+
188
+ // Regular volatility on other days
189
+ return baseReturn + (Math.random() - 0.5) * 0.012;
190
+ });
191
+
192
+ // Asset B: Smooth exponential growth with minimal downside
193
+ const assetBReturns = Array(days + 1).fill(0).map((_, i) => {
194
+ // Gradually increasing return rate to create exponential curve
195
+ const growthFactor = 1 + (i / (days * 5));
196
+ const baseReturn = 0.001 * growthFactor;
197
+
198
+ // Add very limited downside with 20% chance of small negative returns
199
+ const rand = Math.random();
200
+ if (rand < 0.2) {
201
+ return -0.0015; // Small controlled negative returns
202
+ } else {
203
+ return baseReturn + (rand * 0.005); // Positive returns with upward trend
204
+ }
205
+ });
206
+
207
+ // Asset C: Nearly linear growth with minimal volatility
208
+ const assetCReturns = Array(days + 1).fill(0).map(() => {
209
+ // Very consistent returns with minimal variation
210
+ return 0.0003 + (Math.random() - 0.5) * 0.0006;
211
+ });
212
+
213
+ // Calculate cumulative returns
214
+ const assetACumulative = calculateCumulativeReturns(assetAReturns);
215
+ const assetBCumulative = calculateCumulativeReturns(assetBReturns);
216
+ const assetCCumulative = calculateCumulativeReturns(assetCReturns);
217
+
218
+ // Calculate rolling Sortino ratios with a 10-day window (shorter window for more variation)
219
+ const windowSize = 10;
220
+ const assetASortino = [];
221
+ const assetBSortino = [];
222
+ const assetCSortino = [];
223
+
224
+ for (let i = 0; i <= days; i++) {
225
+ const startIdx = Math.max(0, i - windowSize + 1);
226
+ const windowA = assetAReturns.slice(startIdx, i + 1);
227
+ const windowB = assetBReturns.slice(startIdx, i + 1);
228
+ const windowC = assetCReturns.slice(startIdx, i + 1);
229
+
230
+ assetASortino.push(calculateSortinoRatio(windowA, riskFreeRate, windowSize));
231
+ assetBSortino.push(calculateSortinoRatio(windowB, riskFreeRate, windowSize));
232
+ assetCSortino.push(calculateSortinoRatio(windowC, riskFreeRate, windowSize));
233
+ }
234
+
235
+ return {
236
+ dates,
237
+ returns: {
238
+ assetA: assetAReturns,
239
+ assetB: assetBReturns,
240
+ assetC: assetCReturns
241
+ },
242
+ cumulative: {
243
+ assetA: assetACumulative,
244
+ assetB: assetBCumulative,
245
+ assetC: assetCCumulative
246
+ },
247
+ sortino: {
248
+ assetA: assetASortino,
249
+ assetB: assetBSortino,
250
+ assetC: assetCSortino
251
+ }
252
+ };
253
+ }
254
+
255
+ // Initialize the Sortino ratio demonstration charts
256
+ function initializeSortinoDemo() {
257
+ console.log('Initializing Sortino demo');
258
+ const returnsChartCtx = document.getElementById('returnsChart');
259
+ const sortinoChartCtx = document.getElementById('sortinoChart');
260
+
261
+ if (!returnsChartCtx || !sortinoChartCtx) {
262
+ console.error('Chart canvas elements not found for Sortino demo');
263
+ return;
264
+ }
265
+
266
+ // Configure Chart.js global defaults for dark theme
267
+ Chart.defaults.color = '#b0b0b8';
268
+ Chart.defaults.scale.grid.color = 'rgba(56, 56, 64, 0.5)';
269
+ Chart.defaults.scale.grid.borderColor = 'rgba(56, 56, 64, 0.8)';
270
+
271
+ // Generate synthetic data
272
+ const syntheticData = generateSyntheticData();
273
+
274
+ // Create returns chart
275
+ const returnsChart = new Chart(returnsChartCtx, {
276
+ type: 'line',
277
+ data: {
278
+ labels: syntheticData.dates,
279
+ datasets: [
280
+ {
281
+ label: 'Asset A',
282
+ data: syntheticData.cumulative.assetA,
283
+ borderColor: '#3f88e2',
284
+ backgroundColor: 'rgba(63, 136, 226, 0.1)',
285
+ borderWidth: 2,
286
+ pointRadius: 0,
287
+ tension: 0.1
288
+ },
289
+ {
290
+ label: 'Asset B',
291
+ data: syntheticData.cumulative.assetB,
292
+ borderColor: '#4caf50',
293
+ backgroundColor: 'rgba(76, 175, 80, 0.1)',
294
+ borderWidth: 2,
295
+ pointRadius: 0,
296
+ tension: 0.1
297
+ },
298
+ {
299
+ label: 'Asset C',
300
+ data: syntheticData.cumulative.assetC,
301
+ borderColor: '#e2b53f',
302
+ backgroundColor: 'rgba(226, 181, 63, 0.1)',
303
+ borderWidth: 2,
304
+ pointRadius: 0,
305
+ tension: 0.1
306
+ }
307
+ ]
308
+ },
309
+ options: {
310
+ responsive: true,
311
+ maintainAspectRatio: false,
312
+ plugins: {
313
+ legend: {
314
+ position: 'top',
315
+ labels: {
316
+ usePointStyle: true,
317
+ padding: 15
318
+ }
319
+ },
320
+ tooltip: {
321
+ mode: 'index',
322
+ intersect: false,
323
+ backgroundColor: 'rgba(42, 42, 48, 0.9)',
324
+ titleColor: '#ffffff',
325
+ bodyColor: '#ffffff',
326
+ borderColor: 'rgba(56, 56, 64, 1)',
327
+ borderWidth: 1
328
+ }
329
+ },
330
+ scales: {
331
+ x: {
332
+ type: 'time',
333
+ time: {
334
+ unit: 'week',
335
+ displayFormats: {
336
+ week: 'MMM d'
337
+ },
338
+ tooltipFormat: 'MMM d, yyyy'
339
+ },
340
+ title: {
341
+ display: true,
342
+ text: 'Date'
343
+ }
344
+ },
345
+ y: {
346
+ title: {
347
+ display: true,
348
+ text: 'Cumulative Return'
349
+ },
350
+ beginAtZero: false,
351
+ suggestedMin: 0.9,
352
+ suggestedMax: 1.7
353
+ }
354
+ }
355
+ }
356
+ });
357
+
358
+ // Create Sortino chart
359
+ const sortinoChart = new Chart(sortinoChartCtx, {
360
+ type: 'line',
361
+ data: {
362
+ labels: syntheticData.dates,
363
+ datasets: [
364
+ {
365
+ label: 'Asset A',
366
+ data: syntheticData.sortino.assetA,
367
+ borderColor: '#3f88e2',
368
+ backgroundColor: 'rgba(63, 136, 226, 0.1)',
369
+ borderWidth: 2,
370
+ pointRadius: 0,
371
+ tension: 0.1
372
+ },
373
+ {
374
+ label: 'Asset B',
375
+ data: syntheticData.sortino.assetB,
376
+ borderColor: '#4caf50',
377
+ backgroundColor: 'rgba(76, 175, 80, 0.1)',
378
+ borderWidth: 2,
379
+ pointRadius: 0,
380
+ tension: 0.1
381
+ },
382
+ {
383
+ label: 'Asset C',
384
+ data: syntheticData.sortino.assetC,
385
+ borderColor: '#e2b53f',
386
+ backgroundColor: 'rgba(226, 181, 63, 0.1)',
387
+ borderWidth: 2,
388
+ pointRadius: 0,
389
+ tension: 0.1
390
+ }
391
+ ]
392
+ },
393
+ options: {
394
+ responsive: true,
395
+ maintainAspectRatio: false,
396
+ plugins: {
397
+ legend: {
398
+ position: 'top',
399
+ labels: {
400
+ usePointStyle: true,
401
+ padding: 15
402
+ }
403
+ },
404
+ tooltip: {
405
+ mode: 'index',
406
+ intersect: false,
407
+ backgroundColor: 'rgba(42, 42, 48, 0.9)',
408
+ titleColor: '#ffffff',
409
+ bodyColor: '#ffffff',
410
+ borderColor: 'rgba(56, 56, 64, 1)',
411
+ borderWidth: 1
412
+ }
413
+ },
414
+ scales: {
415
+ x: {
416
+ type: 'time',
417
+ time: {
418
+ unit: 'week',
419
+ displayFormats: {
420
+ week: 'MMM d'
421
+ },
422
+ tooltipFormat: 'MMM d, yyyy'
423
+ },
424
+ title: {
425
+ display: true,
426
+ text: 'Date'
427
+ }
428
+ },
429
+ y: {
430
+ title: {
431
+ display: true,
432
+ text: 'Sortino Ratio (10-day Window)'
433
+ },
434
+ min: 0,
435
+ suggestedMax: 5
436
+ }
437
+ }
438
+ }
439
+ });
440
+ }
441
+
442
+ // Generate synthetic data for assets with different drawdown characteristics
443
+ function generateMDDSyntheticData(days = 120) {
444
+ const dates = [];
445
+ const today = new Date();
446
+
447
+ // Generate dates for the past 4 months
448
+ for (let i = days; i >= 0; i--) {
449
+ const date = new Date(today);
450
+ date.setDate(today.getDate() - i);
451
+ dates.push(date);
452
+ }
453
+
454
+ // Asset D: Steady growth with one major correction
455
+ const assetDReturns = Array(days + 1).fill(0).map((_, i) => {
456
+ // Generally positive returns
457
+ let baseReturn = 0.0010;
458
+
459
+ // Add one major correction around day 50-65
460
+ if (i >= 50 && i < 65) {
461
+ // Sharp decline
462
+ return (i === 50) ? -0.06 : -0.008;
463
+ } else if (i >= 65 && i < 80) {
464
+ // Recovery period with strong returns
465
+ return 0.005;
466
+ }
467
+
468
+ // Regular positive drift with some noise
469
+ return baseReturn + (Math.random() - 0.45) * 0.003;
470
+ });
471
+
472
+ // Asset E: Volatile with frequent smaller drawdowns
473
+ const assetEReturns = Array(days + 1).fill(0).map((_, i) => {
474
+ // Base pattern with frequent corrections
475
+ let baseReturn = 0.0015;
476
+
477
+ // Cyclical pattern: every 15-20 days a correction
478
+ if (i % 20 > 15) {
479
+ return -0.01 - Math.random() * 0.005;
480
+ } else {
481
+ return baseReturn + (Math.random() - 0.3) * 0.004;
482
+ }
483
+ });
484
+
485
+ // Asset F: Declining trend with recovery
486
+ const assetFReturns = Array(days + 1).fill(0).map((_, i) => {
487
+ if (i < 60) {
488
+ // Gradual decline in first half
489
+ return -0.002 - Math.random() * 0.003;
490
+ } else if (i < 80) {
491
+ // Bottom formation
492
+ return -0.0005 + (Math.random() - 0.5) * 0.002;
493
+ } else {
494
+ // Recovery in last part
495
+ return 0.003 + Math.random() * 0.004;
496
+ }
497
+ });
498
+
499
+ // Calculate cumulative returns
500
+ const assetDCumulative = calculateCumulativeReturns(assetDReturns);
501
+ const assetECumulative = calculateCumulativeReturns(assetEReturns);
502
+ const assetFCumulative = calculateCumulativeReturns(assetFReturns);
503
+
504
+ // Calculate drawdowns
505
+ const assetDDrawdowns = calculateDrawdowns(assetDCumulative);
506
+ const assetEDrawdowns = calculateDrawdowns(assetECumulative);
507
+ const assetFDrawdowns = calculateDrawdowns(assetFCumulative);
508
+
509
+ // Find significant drawdown periods
510
+ const assetDPeriods = findDrawdownPeriods(assetDCumulative);
511
+ const assetEPeriods = findDrawdownPeriods(assetECumulative);
512
+ const assetFPeriods = findDrawdownPeriods(assetFCumulative);
513
+
514
+ return {
515
+ dates,
516
+ returns: {
517
+ assetD: assetDReturns,
518
+ assetE: assetEReturns,
519
+ assetF: assetFReturns
520
+ },
521
+ cumulative: {
522
+ assetD: assetDCumulative,
523
+ assetE: assetECumulative,
524
+ assetF: assetFCumulative
525
+ },
526
+ drawdowns: {
527
+ assetD: assetDDrawdowns,
528
+ assetE: assetEDrawdowns,
529
+ assetF: assetFDrawdowns
530
+ },
531
+ periods: {
532
+ assetD: assetDPeriods,
533
+ assetE: assetEPeriods,
534
+ assetF: assetFPeriods
535
+ },
536
+ maxDrawdowns: {
537
+ assetD: calculateMaxDrawdown(assetDCumulative),
538
+ assetE: calculateMaxDrawdown(assetECumulative),
539
+ assetF: calculateMaxDrawdown(assetFCumulative)
540
+ }
541
+ };
542
+ }
543
+
544
+ // Initialize the Maximum Drawdown demonstration charts
545
+ function initializeMDDDemo() {
546
+ console.log('Initializing Maximum Drawdown demo');
547
+ const mddReturnsChartCtx = document.getElementById('mddReturnsChart');
548
+ const drawdownChartCtx = document.getElementById('drawdownChart');
549
+
550
+ if (!mddReturnsChartCtx || !drawdownChartCtx) {
551
+ console.error('Chart canvas elements not found for MDD demo');
552
+ return;
553
+ }
554
+
555
+ // Generate synthetic data for MDD demo
556
+ const syntheticData = generateMDDSyntheticData();
557
+
558
+ // Create plugin for highlighting drawdown periods
559
+ const drawdownPeriodPlugin = {
560
+ id: 'drawdownPeriod',
561
+ beforeDraw: (chart) => {
562
+ const {ctx, chartArea, scales} = chart;
563
+
564
+ if (!chartArea) {
565
+ return;
566
+ }
567
+
568
+ // Get the datasets
569
+ const datasets = chart.data.datasets;
570
+ for (let i = 0; i < datasets.length; i++) {
571
+ const dataset = datasets[i];
572
+ // Skip if it's not a dataset we want to highlight periods for
573
+ if (!dataset.drawdownPeriods) continue;
574
+
575
+ const periods = dataset.drawdownPeriods;
576
+
577
+ // Draw each drawdown period
578
+ periods.forEach(period => {
579
+ const startX = scales.x.getPixelForValue(chart.data.labels[period.start]);
580
+ const endX = scales.x.getPixelForValue(chart.data.labels[period.end]);
581
+
582
+ // Draw a semi-transparent rectangle for the drawdown period
583
+ ctx.fillStyle = dataset.backgroundColor.replace('0.1', '0.2');
584
+ ctx.fillRect(startX, chartArea.top, endX - startX, chartArea.height);
585
+
586
+ // Mark the peak with a vertical line
587
+ const peakX = scales.x.getPixelForValue(chart.data.labels[period.peakIndex]);
588
+ ctx.strokeStyle = dataset.borderColor;
589
+ ctx.setLineDash([5, 3]);
590
+ ctx.beginPath();
591
+ ctx.moveTo(peakX, chartArea.top);
592
+ ctx.lineTo(peakX, chartArea.bottom);
593
+ ctx.stroke();
594
+ ctx.setLineDash([]);
595
+ });
596
+ }
597
+ }
598
+ };
599
+
600
+ // Create returns chart with drawdown periods highlighted
601
+ const mddReturnsChart = new Chart(mddReturnsChartCtx, {
602
+ type: 'line',
603
+ plugins: [drawdownPeriodPlugin],
604
+ data: {
605
+ labels: syntheticData.dates,
606
+ datasets: [
607
+ {
608
+ label: 'Asset D',
609
+ data: syntheticData.cumulative.assetD,
610
+ borderColor: '#ff6384',
611
+ backgroundColor: 'rgba(255, 99, 132, 0.1)',
612
+ borderWidth: 2,
613
+ pointRadius: 0,
614
+ tension: 0.1,
615
+ drawdownPeriods: syntheticData.periods.assetD
616
+ },
617
+ {
618
+ label: 'Asset E',
619
+ data: syntheticData.cumulative.assetE,
620
+ borderColor: '#36a2eb',
621
+ backgroundColor: 'rgba(54, 162, 235, 0.1)',
622
+ borderWidth: 2,
623
+ pointRadius: 0,
624
+ tension: 0.1,
625
+ drawdownPeriods: syntheticData.periods.assetE
626
+ },
627
+ {
628
+ label: 'Asset F',
629
+ data: syntheticData.cumulative.assetF,
630
+ borderColor: '#ffcd56',
631
+ backgroundColor: 'rgba(255, 205, 86, 0.1)',
632
+ borderWidth: 2,
633
+ pointRadius: 0,
634
+ tension: 0.1,
635
+ drawdownPeriods: syntheticData.periods.assetF
636
+ }
637
+ ]
638
+ },
639
+ options: {
640
+ responsive: true,
641
+ maintainAspectRatio: false,
642
+ plugins: {
643
+ tooltip: {
644
+ mode: 'index',
645
+ intersect: false,
646
+ callbacks: {
647
+ afterTitle: function(context) {
648
+ const datasetIndex = context[0].datasetIndex;
649
+ const dataIndex = context[0].dataIndex;
650
+ const value = context[0].dataset.data[dataIndex];
651
+ const maxValue = Math.max(...context[0].dataset.data.slice(0, dataIndex + 1));
652
+ const drawdown = ((maxValue - value) / maxValue * 100).toFixed(2);
653
+ return `Current Drawdown: ${drawdown}%`;
654
+ }
655
+ }
656
+ },
657
+ legend: {
658
+ position: 'top'
659
+ }
660
+ },
661
+ scales: {
662
+ x: {
663
+ type: 'time',
664
+ time: {
665
+ unit: 'week',
666
+ displayFormats: {
667
+ week: 'MMM d'
668
+ },
669
+ tooltipFormat: 'MMM d, yyyy'
670
+ },
671
+ title: {
672
+ display: true,
673
+ text: 'Date'
674
+ }
675
+ },
676
+ y: {
677
+ title: {
678
+ display: true,
679
+ text: 'Cumulative Return'
680
+ },
681
+ suggestedMin: 0.7,
682
+ suggestedMax: 1.5
683
+ }
684
+ }
685
+ }
686
+ });
687
+
688
+ // Create drawdown chart
689
+ const drawdownChart = new Chart(drawdownChartCtx, {
690
+ type: 'line',
691
+ data: {
692
+ labels: syntheticData.dates,
693
+ datasets: [
694
+ {
695
+ label: `Asset D (Max: ${(syntheticData.maxDrawdowns.assetD * 100).toFixed(1)}%)`,
696
+ data: syntheticData.drawdowns.assetD.map(d => d * 100), // Convert to percentage
697
+ borderColor: '#ff6384',
698
+ backgroundColor: 'rgba(255, 99, 132, 0.1)',
699
+ borderWidth: 2,
700
+ pointRadius: 0,
701
+ tension: 0.1,
702
+ fill: 'origin'
703
+ },
704
+ {
705
+ label: `Asset E (Max: ${(syntheticData.maxDrawdowns.assetE * 100).toFixed(1)}%)`,
706
+ data: syntheticData.drawdowns.assetE.map(d => d * 100), // Convert to percentage
707
+ borderColor: '#36a2eb',
708
+ backgroundColor: 'rgba(54, 162, 235, 0.1)',
709
+ borderWidth: 2,
710
+ pointRadius: 0,
711
+ tension: 0.1,
712
+ fill: 'origin'
713
+ },
714
+ {
715
+ label: `Asset F (Max: ${(syntheticData.maxDrawdowns.assetF * 100).toFixed(1)}%)`,
716
+ data: syntheticData.drawdowns.assetF.map(d => d * 100), // Convert to percentage
717
+ borderColor: '#ffcd56',
718
+ backgroundColor: 'rgba(255, 205, 86, 0.1)',
719
+ borderWidth: 2,
720
+ pointRadius: 0,
721
+ tension: 0.1,
722
+ fill: 'origin'
723
+ }
724
+ ]
725
+ },
726
+ options: {
727
+ responsive: true,
728
+ maintainAspectRatio: false,
729
+ plugins: {
730
+ tooltip: {
731
+ mode: 'index',
732
+ intersect: false,
733
+ callbacks: {
734
+ label: function(context) {
735
+ return `${context.dataset.label.split(' (')[0]}: ${context.parsed.y.toFixed(2)}%`;
736
+ }
737
+ }
738
+ },
739
+ legend: {
740
+ position: 'top'
741
+ }
742
+ },
743
+ scales: {
744
+ x: {
745
+ type: 'time',
746
+ time: {
747
+ unit: 'week',
748
+ displayFormats: {
749
+ week: 'MMM d'
750
+ },
751
+ tooltipFormat: 'MMM d, yyyy'
752
+ },
753
+ title: {
754
+ display: true,
755
+ text: 'Date'
756
+ }
757
+ },
758
+ y: {
759
+ title: {
760
+ display: true,
761
+ text: 'Drawdown (%)'
762
+ },
763
+ min: 0,
764
+ max: 35, // Max drawdown percentage to show
765
+ reverse: true // Invert axis so drawdowns go downward
766
+ }
767
+ }
768
+ }
769
+ });
770
+ }
771
+
772
+ // Utility function to calculate turnover ratio
773
+ function calculateTurnover(currentWeights, previousWeights) {
774
+ if (!previousWeights) {
775
+ return 0; // First period has no turnover
776
+ }
777
+
778
+ let sumAbsDiff = 0;
779
+ for (let i = 0; i < currentWeights.length; i++) {
780
+ sumAbsDiff += Math.abs(currentWeights[i] - previousWeights[i]);
781
+ }
782
+
783
+ // Multiply by 0.5 to get the turnover ratio (representing minimum fraction of portfolio that must be traded)
784
+ return sumAbsDiff * 0.5;
785
+ }
786
+
787
+ // Generate data for turnover ratio demonstration
788
+ function generateTurnoverDemoData(days = 60) {
789
+ const dates = [];
790
+ const today = new Date();
791
+
792
+ // Generate dates
793
+ for (let i = days; i >= 0; i--) {
794
+ const date = new Date(today);
795
+ date.setDate(today.getDate() - i);
796
+ dates.push(date);
797
+ }
798
+
799
+ // Portfolio 1: Stable allocations around 40%, 35%, 25%
800
+ const portfolio1Weights = [];
801
+ const portfolio1Turnover = [];
802
+ let prevWeights1 = null;
803
+
804
+ for (let i = 0; i <= days; i++) {
805
+ // Target weights with small random fluctuations
806
+ const target1 = 0.40;
807
+ const target2 = 0.35;
808
+ const target3 = 0.25;
809
+
810
+ // Small random adjustments (up to +/- 2%)
811
+ const adjust1 = (Math.random() - 0.5) * 0.02;
812
+ const adjust2 = (Math.random() - 0.5) * 0.02;
813
+
814
+ // Calculate weights ensuring they sum to 1
815
+ let weight1 = Math.max(0.01, Math.min(0.99, target1 + adjust1));
816
+ let weight2 = Math.max(0.01, Math.min(0.99 - weight1, target2 + adjust2));
817
+ let weight3 = 1 - weight1 - weight2;
818
+
819
+ const currentWeights = [weight1, weight2, weight3];
820
+ portfolio1Weights.push(currentWeights);
821
+
822
+ // Calculate turnover
823
+ const turnover = calculateTurnover(currentWeights, prevWeights1);
824
+ portfolio1Turnover.push(turnover);
825
+
826
+ prevWeights1 = currentWeights;
827
+ }
828
+
829
+ // Portfolio 2: Erratic trading with large daily changes
830
+ const portfolio2Weights = [];
831
+ const portfolio2Turnover = [];
832
+ let prevWeights2 = null;
833
+
834
+ for (let i = 0; i <= days; i++) {
835
+ // Significantly different weights each day
836
+ let weight1 = Math.random() * 0.8 + 0.1; // Between 10% and 90%
837
+ let weight2 = Math.random() * (1 - weight1 - 0.05); // Remaining, leaving at least 5% for asset 3
838
+ let weight3 = 1 - weight1 - weight2;
839
+
840
+ const currentWeights = [weight1, weight2, weight3];
841
+ portfolio2Weights.push(currentWeights);
842
+
843
+ // Calculate turnover
844
+ const turnover = calculateTurnover(currentWeights, prevWeights2);
845
+ portfolio2Turnover.push(turnover);
846
+
847
+ prevWeights2 = currentWeights;
848
+ }
849
+
850
+ // Portfolio 3: Gradual concentration from equal weights to all in one asset
851
+ const portfolio3Weights = [];
852
+ const portfolio3Turnover = [];
853
+ let prevWeights3 = null;
854
+
855
+ for (let i = 0; i <= days; i++) {
856
+ // Start with equal weights
857
+ if (i === 0) {
858
+ const currentWeights = [1/3, 1/3, 1/3];
859
+ portfolio3Weights.push(currentWeights);
860
+ portfolio3Turnover.push(0);
861
+ prevWeights3 = currentWeights;
862
+ continue;
863
+ }
864
+
865
+ // Gradually increase weight of asset 1, reduce others
866
+ const progressFactor = i / days; // 0 at start, 1 at end
867
+ let weight1 = 1/3 + progressFactor * 2/3; // Grows from 1/3 to 1
868
+ let weight2 = 1/3 * (1 - progressFactor); // Shrinks from 1/3 to 0
869
+ let weight3 = 1 - weight1 - weight2; // Shrinks from 1/3 to 0
870
+
871
+ const currentWeights = [weight1, weight2, weight3];
872
+ portfolio3Weights.push(currentWeights);
873
+
874
+ // Calculate turnover
875
+ const turnover = calculateTurnover(currentWeights, prevWeights3);
876
+ portfolio3Turnover.push(turnover);
877
+
878
+ prevWeights3 = currentWeights;
879
+ }
880
+
881
+ return {
882
+ dates,
883
+ portfolios: {
884
+ stable: {
885
+ weights: portfolio1Weights,
886
+ turnover: portfolio1Turnover
887
+ },
888
+ erratic: {
889
+ weights: portfolio2Weights,
890
+ turnover: portfolio2Turnover
891
+ },
892
+ concentration: {
893
+ weights: portfolio3Weights,
894
+ turnover: portfolio3Turnover
895
+ }
896
+ }
897
+ };
898
+ }
899
+
900
+ // Initialize the Turnover Ratio demonstration charts
901
+ function initializeTurnoverDemo() {
902
+ console.log('Initializing Turnover demo');
903
+ const weightsChart1Ctx = document.getElementById('weightsChart1');
904
+ const turnoverChart1Ctx = document.getElementById('turnoverChart1');
905
+ const weightsChart2Ctx = document.getElementById('weightsChart2');
906
+ const turnoverChart2Ctx = document.getElementById('turnoverChart2');
907
+ const weightsChart3Ctx = document.getElementById('weightsChart3');
908
+ const turnoverChart3Ctx = document.getElementById('turnoverChart3');
909
+
910
+ if (!weightsChart1Ctx || !turnoverChart1Ctx || !weightsChart2Ctx ||
911
+ !turnoverChart2Ctx || !weightsChart3Ctx || !turnoverChart3Ctx) {
912
+ console.error('Chart canvas elements not found for Turnover demo');
913
+ return;
914
+ }
915
+
916
+ // Generate data for all portfolios
917
+ const data = generateTurnoverDemoData();
918
+
919
+ // Define colors for assets
920
+ const assetColors = [
921
+ '#8844ee',
922
+ '#44bbee',
923
+ '#ee7744'
924
+ ];
925
+
926
+ // Create stacked area charts for portfolio weights
927
+ const createWeightsChart = (ctx, weights, title) => {
928
+ const datasets = [];
929
+
930
+ // Create a dataset for each asset
931
+ for (let assetIndex = 0; assetIndex < 3; assetIndex++) {
932
+ datasets.push({
933
+ label: `Asset ${assetIndex + 1}`,
934
+ data: weights.map(w => w[assetIndex] * 100), // Convert to percentage
935
+ backgroundColor: assetColors[assetIndex],
936
+ borderColor: assetColors[assetIndex],
937
+ borderWidth: 1,
938
+ fill: true,
939
+ tension: 0
940
+ });
941
+ }
942
+
943
+ return new Chart(ctx, {
944
+ type: 'line',
945
+ data: {
946
+ labels: data.dates,
947
+ datasets: datasets
948
+ },
949
+ options: {
950
+ responsive: true,
951
+ maintainAspectRatio: false,
952
+ scales: {
953
+ x: {
954
+ type: 'time',
955
+ time: {
956
+ unit: 'day',
957
+ displayFormats: {
958
+ day: 'MMM d'
959
+ },
960
+ tooltipFormat: 'MMM d, yyyy'
961
+ },
962
+ title: {
963
+ display: true,
964
+ text: 'Date'
965
+ },
966
+ stacked: true
967
+ },
968
+ y: {
969
+ stacked: true,
970
+ min: 0,
971
+ max: 100,
972
+ title: {
973
+ display: true,
974
+ text: 'Allocation (%)'
975
+ }
976
+ }
977
+ },
978
+ plugins: {
979
+ tooltip: {
980
+ mode: 'index',
981
+ intersect: false,
982
+ callbacks: {
983
+ label: function(context) {
984
+ return `${context.dataset.label}: ${context.parsed.y.toFixed(1)}%`;
985
+ }
986
+ }
987
+ },
988
+ legend: {
989
+ position: 'top'
990
+ }
991
+ }
992
+ }
993
+ });
994
+ };
995
+
996
+ // Create line charts for turnover values
997
+ const createTurnoverChart = (ctx, turnover, title) => {
998
+ return new Chart(ctx, {
999
+ type: 'line',
1000
+ data: {
1001
+ labels: data.dates,
1002
+ datasets: [{
1003
+ label: 'Turnover Ratio',
1004
+ data: turnover.map(t => t * 100), // Convert to percentage
1005
+ borderColor: '#3f88e2',
1006
+ backgroundColor: 'rgba(63, 136, 226, 0.1)',
1007
+ borderWidth: 2,
1008
+ pointRadius: 0,
1009
+ tension: 0.1,
1010
+ fill: 'origin'
1011
+ }]
1012
+ },
1013
+ options: {
1014
+ responsive: true,
1015
+ maintainAspectRatio: false,
1016
+ scales: {
1017
+ x: {
1018
+ type: 'time',
1019
+ time: {
1020
+ unit: 'day',
1021
+ displayFormats: {
1022
+ day: 'MMM d'
1023
+ },
1024
+ tooltipFormat: 'MMM d, yyyy'
1025
+ },
1026
+ title: {
1027
+ display: true,
1028
+ text: 'Date'
1029
+ }
1030
+ },
1031
+ y: {
1032
+ min: 0,
1033
+ max: 100,
1034
+ title: {
1035
+ display: true,
1036
+ text: 'Turnover (%)'
1037
+ }
1038
+ }
1039
+ },
1040
+ plugins: {
1041
+ tooltip: {
1042
+ mode: 'index',
1043
+ intersect: false,
1044
+ callbacks: {
1045
+ label: function(context) {
1046
+ return `Turnover: ${context.parsed.y.toFixed(1)}%`;
1047
+ }
1048
+ }
1049
+ },
1050
+ legend: {
1051
+ display: false
1052
+ }
1053
+ }
1054
+ }
1055
+ });
1056
+ };
1057
+
1058
+ // Create all charts
1059
+ createWeightsChart(weightsChart1Ctx, data.portfolios.stable.weights, 'Stable Portfolio');
1060
+ createTurnoverChart(turnoverChart1Ctx, data.portfolios.stable.turnover, 'Stable Portfolio Turnover');
1061
+
1062
+ createWeightsChart(weightsChart2Ctx, data.portfolios.erratic.weights, 'Erratic Portfolio');
1063
+ createTurnoverChart(turnoverChart2Ctx, data.portfolios.erratic.turnover, 'Erratic Portfolio Turnover');
1064
+
1065
+ createWeightsChart(weightsChart3Ctx, data.portfolios.concentration.weights, 'Concentration Portfolio');
1066
+ createTurnoverChart(turnoverChart3Ctx, data.portfolios.concentration.turnover, 'Concentration Portfolio Turnover');
1067
+ }
1068
+
1069
+ // Utility function to calculate HHI (Herfindahl-Hirschman Index)
1070
+ function calculateHHI(weights) {
1071
+ return weights.reduce((sum, weight) => sum + weight * weight, 0);
1072
+ }
1073
+
1074
+ // Utility function to calculate ENP (Effective Number of Positions)
1075
+ function calculateENP(weights, epsilon = 0.0001) {
1076
+ const hhi = calculateHHI(weights);
1077
+ return 1 / (hhi + epsilon);
1078
+ }
1079
+
1080
+ // Utility function to calculate concentration penalty
1081
+ function calculateConcentrationPenalty(weights, enpMin, enpMax, epsilon = 0.0001) {
1082
+ const enp = calculateENP(weights, epsilon);
1083
+ const lowerPenalty = Math.max(enpMin - enp, 0);
1084
+ const upperPenalty = Math.max(enp - enpMax, 0);
1085
+ return lowerPenalty + upperPenalty;
1086
+ }
1087
+
1088
+ // Initialize the Concentration Penalty demonstration
1089
+ function initializeConcentrationDemo() {
1090
+ console.log('Initializing Concentration demo');
1091
+ const concentrationWeightsChartCtx = document.getElementById('concentrationWeightsChart');
1092
+ const enpChartCtx = document.getElementById('enpChart');
1093
+ const hhiEnpChartCtx = document.getElementById('hhiEnpChart');
1094
+
1095
+ if (!concentrationWeightsChartCtx || !enpChartCtx || !hhiEnpChartCtx) {
1096
+ console.error('Concentration chart canvas elements not found', {
1097
+ concentrationWeightsChartCtx,
1098
+ enpChartCtx,
1099
+ hhiEnpChartCtx
1100
+ });
1101
+ return;
1102
+ }
1103
+
1104
+ // Define ENP target range
1105
+ const enpMin = 3;
1106
+ const enpMax = 8;
1107
+
1108
+ // Define example portfolios with different concentration levels
1109
+ const portfolios = [
1110
+ {
1111
+ name: 'Highly Concentrated',
1112
+ weights: [0.65, 0.20, 0.07, 0.03, 0.02, 0.01, 0.01, 0.01],
1113
+ color: '#ff6384'
1114
+ },
1115
+ {
1116
+ name: 'Balanced',
1117
+ weights: [0.25, 0.18, 0.15, 0.12, 0.10, 0.08, 0.07, 0.05],
1118
+ color: '#4caf50'
1119
+ },
1120
+ {
1121
+ name: 'Overly Diversified',
1122
+ weights: [0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125],
1123
+ color: '#ffcd56'
1124
+ }
1125
+ ];
1126
+
1127
+ // Calculate HHI and ENP for each portfolio
1128
+ portfolios.forEach(portfolio => {
1129
+ portfolio.hhi = calculateHHI(portfolio.weights);
1130
+ portfolio.enp = calculateENP(portfolio.weights);
1131
+ portfolio.penalty = calculateConcentrationPenalty(portfolio.weights, enpMin, enpMax);
1132
+ });
1133
+
1134
+ // Create weight distribution chart
1135
+ const concentrationWeightsChart = new Chart(concentrationWeightsChartCtx, {
1136
+ type: 'bar',
1137
+ data: {
1138
+ labels: ['Asset 1', 'Asset 2', 'Asset 3', 'Asset 4', 'Asset 5', 'Asset 6', 'Asset 7', 'Asset 8'],
1139
+ datasets: portfolios.map(portfolio => ({
1140
+ label: portfolio.name,
1141
+ data: portfolio.weights.map(w => w * 100), // Convert to percentage
1142
+ backgroundColor: portfolio.color,
1143
+ borderColor: portfolio.color,
1144
+ borderWidth: 1
1145
+ }))
1146
+ },
1147
+ options: {
1148
+ responsive: true,
1149
+ maintainAspectRatio: false,
1150
+ scales: {
1151
+ x: {
1152
+ title: {
1153
+ display: true,
1154
+ text: 'Assets'
1155
+ }
1156
+ },
1157
+ y: {
1158
+ title: {
1159
+ display: true,
1160
+ text: 'Weight (%)'
1161
+ },
1162
+ min: 0,
1163
+ max: 70
1164
+ }
1165
+ },
1166
+ plugins: {
1167
+ legend: {
1168
+ position: 'top'
1169
+ },
1170
+ tooltip: {
1171
+ callbacks: {
1172
+ label: function(context) {
1173
+ return `${context.dataset.label}: ${context.parsed.y.toFixed(1)}%`;
1174
+ }
1175
+ }
1176
+ }
1177
+ }
1178
+ }
1179
+ });
1180
+
1181
+ // Create ENP comparison chart
1182
+ const enpChart = new Chart(enpChartCtx, {
1183
+ type: 'bar',
1184
+ data: {
1185
+ labels: portfolios.map(p => p.name),
1186
+ datasets: [
1187
+ {
1188
+ label: 'Effective Number of Positions',
1189
+ data: portfolios.map(p => p.enp),
1190
+ backgroundColor: portfolios.map(p => p.color),
1191
+ borderColor: portfolios.map(p => p.color),
1192
+ borderWidth: 1
1193
+ }
1194
+ ]
1195
+ },
1196
+ options: {
1197
+ responsive: true,
1198
+ maintainAspectRatio: false,
1199
+ scales: {
1200
+ x: {
1201
+ title: {
1202
+ display: true,
1203
+ text: 'Portfolio'
1204
+ }
1205
+ },
1206
+ y: {
1207
+ title: {
1208
+ display: true,
1209
+ text: 'ENP'
1210
+ },
1211
+ min: 0,
1212
+ max: 10,
1213
+ ticks: {
1214
+ callback: function(value) {
1215
+ return value.toFixed(1);
1216
+ }
1217
+ }
1218
+ }
1219
+ },
1220
+ plugins: {
1221
+ annotation: {
1222
+ annotations: {
1223
+ minLine: {
1224
+ type: 'line',
1225
+ mode: 'horizontal',
1226
+ scaleID: 'y',
1227
+ value: enpMin,
1228
+ borderColor: '#ff9800',
1229
+ borderWidth: 2,
1230
+ borderDash: [5, 5],
1231
+ label: {
1232
+ content: 'ENP Min = ' + enpMin,
1233
+ enabled: true,
1234
+ position: 'end'
1235
+ }
1236
+ },
1237
+ maxLine: {
1238
+ type: 'line',
1239
+ mode: 'horizontal',
1240
+ scaleID: 'y',
1241
+ value: enpMax,
1242
+ borderColor: '#8bc34a',
1243
+ borderWidth: 2,
1244
+ borderDash: [5, 5],
1245
+ label: {
1246
+ content: 'ENP Max = ' + enpMax,
1247
+ enabled: true,
1248
+ position: 'end'
1249
+ }
1250
+ }
1251
+ }
1252
+ },
1253
+ legend: {
1254
+ display: false
1255
+ },
1256
+ tooltip: {
1257
+ callbacks: {
1258
+ label: function(context) {
1259
+ const portfolio = portfolios[context.dataIndex];
1260
+ let label = `ENP: ${context.parsed.y.toFixed(2)}`;
1261
+ if (portfolio.penalty > 0) {
1262
+ label += ` (Penalty: ${portfolio.penalty.toFixed(2)})`;
1263
+ }
1264
+ return label;
1265
+ },
1266
+ afterLabel: function(context) {
1267
+ const portfolio = portfolios[context.dataIndex];
1268
+ return `HHI: ${portfolio.hhi.toFixed(3)}`;
1269
+ }
1270
+ }
1271
+ }
1272
+ }
1273
+ }
1274
+ });
1275
+
1276
+ // Create HHI vs ENP relationship chart
1277
+ // Generate data points for the inverse relationship curve
1278
+ const hhiValues = [];
1279
+ const enpValues = [];
1280
+
1281
+ // Generate data points from HHI = 0.125 (equal weights) to HHI = 1 (complete concentration)
1282
+ for (let hhi = 0.125; hhi <= 1; hhi += 0.01) {
1283
+ hhiValues.push(hhi);
1284
+ enpValues.push(1 / hhi);
1285
+ }
1286
+
1287
+ // Add actual portfolio data points
1288
+ const portfolioPoints = portfolios.map(p => ({
1289
+ x: p.hhi,
1290
+ y: p.enp
1291
+ }));
1292
+
1293
+ const hhiEnpChart = new Chart(hhiEnpChartCtx, {
1294
+ type: 'scatter',
1295
+ data: {
1296
+ datasets: [
1297
+ {
1298
+ label: 'HHI-ENP Curve',
1299
+ data: hhiValues.map((hhi, i) => ({ x: hhi, y: enpValues[i] })),
1300
+ showLine: true,
1301
+ borderColor: '#3f88e2',
1302
+ backgroundColor: 'rgba(63, 136, 226, 0.1)',
1303
+ borderWidth: 2,
1304
+ pointRadius: 0
1305
+ },
1306
+ {
1307
+ label: 'Portfolio Examples',
1308
+ data: portfolioPoints,
1309
+ borderColor: '#ffffff',
1310
+ backgroundColor: portfolios.map(p => p.color),
1311
+ pointRadius: 6,
1312
+ pointHoverRadius: 8
1313
+ }
1314
+ ]
1315
+ },
1316
+ options: {
1317
+ responsive: true,
1318
+ maintainAspectRatio: false,
1319
+ scales: {
1320
+ x: {
1321
+ type: 'linear',
1322
+ title: {
1323
+ display: true,
1324
+ text: 'HHI (Herfindahl-Hirschman Index)'
1325
+ },
1326
+ min: 0,
1327
+ max: 1
1328
+ },
1329
+ y: {
1330
+ title: {
1331
+ display: true,
1332
+ text: 'ENP (Effective Number of Positions)'
1333
+ },
1334
+ min: 0,
1335
+ max: 10
1336
+ }
1337
+ },
1338
+ plugins: {
1339
+ tooltip: {
1340
+ callbacks: {
1341
+ label: function(context) {
1342
+ if (context.datasetIndex === 0) {
1343
+ return `HHI: ${context.parsed.x.toFixed(3)}, ENP: ${context.parsed.y.toFixed(2)}`;
1344
+ } else {
1345
+ const portfolio = portfolios[context.dataIndex];
1346
+ return `${portfolio.name}: HHI = ${portfolio.hhi.toFixed(3)}, ENP = ${portfolio.enp.toFixed(2)}`;
1347
+ }
1348
+ }
1349
+ }
1350
+ }
1351
+ }
1352
+ }
1353
+ });
1354
+ }
assets/static/index.html CHANGED
@@ -16,6 +16,10 @@
16
  <div class="title-container">
17
  <h1>Portfolio Optimizer</h1>
18
  </div>
 
 
 
 
19
  </header>
20
 
21
  <div class="main-content">
@@ -108,86 +112,26 @@
108
 
109
  <!-- Stats Row -->
110
  <div class="stats-row">
111
- <!-- OGD Portfolio Stats -->
112
- <div class="stat-card">
113
- <div class="stat-title">OGD Portfolio</div>
114
- <div class="stat-value" id="ogdSharpeRatio">-</div>
115
- <div class="stat-subtitle">Sharpe Ratio</div>
116
- </div>
117
- <div class="stat-card">
118
- <div class="stat-title">OGD Portfolio</div>
119
- <div class="stat-value" id="ogdMaxDrawdown">-</div>
120
- <div class="stat-subtitle">Max Drawdown</div>
121
- </div>
122
- <div class="stat-card">
123
- <div class="stat-title">OGD Portfolio</div>
124
- <div class="stat-value" id="ogdReturn">-</div>
125
- <div class="stat-subtitle">Return</div>
126
- </div>
127
- <div class="stat-card">
128
- <div class="stat-title">OGD Portfolio</div>
129
- <div class="stat-value" id="ogdCAPMAlpha">-</div>
130
- <div class="stat-subtitle">CAPM Alpha</div>
131
- </div>
132
- <div class="stat-card">
133
- <div class="stat-title">OGD Portfolio</div>
134
- <div class="stat-value" id="ogdFF3Alpha">-</div>
135
- <div class="stat-subtitle">FF3 Alpha</div>
136
- </div>
137
-
138
- <!-- Equal Weight Portfolio Stats -->
139
- <div class="stat-card">
140
- <div class="stat-title">Equal Weight</div>
141
- <div class="stat-value" id="ewSharpeRatio">-</div>
142
- <div class="stat-subtitle">Sharpe Ratio</div>
143
- </div>
144
- <div class="stat-card">
145
- <div class="stat-title">Equal Weight</div>
146
- <div class="stat-value" id="ewMaxDrawdown">-</div>
147
- <div class="stat-subtitle">Max Drawdown</div>
148
- </div>
149
- <div class="stat-card">
150
- <div class="stat-title">Equal Weight</div>
151
- <div class="stat-value" id="ewReturn">-</div>
152
- <div class="stat-subtitle">Return</div>
153
- </div>
154
- <div class="stat-card">
155
- <div class="stat-title">Equal Weight</div>
156
- <div class="stat-value" id="ewCAPMAlpha">-</div>
157
- <div class="stat-subtitle">CAPM Alpha</div>
158
- </div>
159
- <div class="stat-card">
160
- <div class="stat-title">Equal Weight</div>
161
- <div class="stat-value" id="ewFF3Alpha">-</div>
162
- <div class="stat-subtitle">FF3 Alpha</div>
163
- </div>
164
-
165
- <!-- Random Portfolio Stats -->
166
- <div class="stat-card">
167
- <div class="stat-title">Random Portfolio</div>
168
- <div class="stat-value" id="randomSharpeRatio">-</div>
169
- <div class="stat-subtitle">Sharpe Ratio</div>
170
- </div>
171
- <div class="stat-card">
172
- <div class="stat-title">Random Portfolio</div>
173
- <div class="stat-value" id="randomMaxDrawdown">-</div>
174
- <div class="stat-subtitle">Max Drawdown</div>
175
- </div>
176
- <div class="stat-card">
177
- <div class="stat-title">Random Portfolio</div>
178
- <div class="stat-value" id="randomReturn">-</div>
179
- <div class="stat-subtitle">Return</div>
180
- </div>
181
- <div class="stat-card">
182
- <div class="stat-title">Random Portfolio</div>
183
- <div class="stat-value" id="randomCAPMAlpha">-</div>
184
- <div class="stat-subtitle">CAPM Alpha</div>
185
- </div>
186
- <div class="stat-card">
187
- <div class="stat-title">Random Portfolio</div>
188
- <div class="stat-value" id="randomFF3Alpha">-</div>
189
- <div class="stat-subtitle">FF3 Alpha</div>
190
- </div>
191
  </div>
192
  </div>
193
  </div>
 
16
  <div class="title-container">
17
  <h1>Portfolio Optimizer</h1>
18
  </div>
19
+ <nav class="nav-menu">
20
+ <a href="/index.html" class="nav-link active">Simulation</a>
21
+ <a href="/education.html" class="nav-link">Education</a>
22
+ </nav>
23
  </header>
24
 
25
  <div class="main-content">
 
112
 
113
  <!-- Stats Row -->
114
  <div class="stats-row">
115
+ <!-- Dynamically generated stats grid will be placed here -->
116
+ </div>
117
+
118
+ <!-- Legacy elements for backward compatibility -->
119
+ <div style="display:none" aria-hidden="true">
120
+ <span id="ogdSharpeRatio">-</span>
121
+ <span id="ogdMaxDrawdown">-</span>
122
+ <span id="ogdReturn">-</span>
123
+ <span id="ogdCAPMAlpha">-</span>
124
+ <span id="ogdFF3Alpha">-</span>
125
+ <span id="ewSharpeRatio">-</span>
126
+ <span id="ewMaxDrawdown">-</span>
127
+ <span id="ewReturn">-</span>
128
+ <span id="ewCAPMAlpha">-</span>
129
+ <span id="ewFF3Alpha">-</span>
130
+ <span id="randomSharpeRatio">-</span>
131
+ <span id="randomMaxDrawdown">-</span>
132
+ <span id="randomReturn">-</span>
133
+ <span id="randomCAPMAlpha">-</span>
134
+ <span id="randomFF3Alpha">-</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  </div>
136
  </div>
137
  </div>
assets/static/script.js CHANGED
@@ -21,6 +21,22 @@ function formatDate(date) {
21
  return date.toISOString().split('T')[0];
22
  }
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  // Populate the stock list with sectors and tickers
25
  function populateStockList(sectors) {
26
  const stockListElement = document.getElementById('stockList');
@@ -528,29 +544,165 @@ function updateCharts(returnsData, weightsData, concentrationData, enpMin, enpMa
528
 
529
  // Update performance metrics for all three portfolios
530
  function updateMetrics(metrics) {
531
- // OGD Portfolio metrics
532
- document.getElementById('ogdSharpeRatio').textContent = metrics.ogd.sharpe.toFixed(2);
533
- document.getElementById('ogdMaxDrawdown').textContent = (metrics.ogd.max_drawdown * 100).toFixed(2) + '%';
534
- document.getElementById('ogdReturn').textContent = ((metrics.ogd.cumulative_return - 1) * 100).toFixed(2) + '%';
535
-
536
- // Equal Weight Portfolio metrics
537
- document.getElementById('ewSharpeRatio').textContent = metrics.equal_weight.sharpe.toFixed(2);
538
- document.getElementById('ewMaxDrawdown').textContent = (metrics.equal_weight.max_drawdown * 100).toFixed(2) + '%';
539
- document.getElementById('ewReturn').textContent = ((metrics.equal_weight.cumulative_return - 1) * 100).toFixed(2) + '%';
540
-
541
- // Random Portfolio metrics
542
- document.getElementById('randomSharpeRatio').textContent = metrics.random.sharpe.toFixed(2);
543
- document.getElementById('randomMaxDrawdown').textContent = (metrics.random.max_drawdown * 100).toFixed(2) + '%';
544
- document.getElementById('randomReturn').textContent = ((metrics.random.cumulative_return - 1) * 100).toFixed(2) + '%';
545
-
546
- // Factor metrics (if available)
547
- if (metrics.ogd.capm_alpha !== undefined) {
548
- document.getElementById('ogdCAPMAlpha').textContent = metrics.ogd.capm_alpha.toFixed(2) + '%';
549
- document.getElementById('ogdFF3Alpha').textContent = metrics.ogd.ff3_alpha.toFixed(2) + '%';
550
- document.getElementById('ewCAPMAlpha').textContent = metrics.equal_weight.capm_alpha.toFixed(2) + '%';
551
- document.getElementById('ewFF3Alpha').textContent = metrics.equal_weight.ff3_alpha.toFixed(2) + '%';
552
- document.getElementById('randomCAPMAlpha').textContent = metrics.random.capm_alpha.toFixed(2) + '%';
553
- document.getElementById('randomFF3Alpha').textContent = metrics.random.ff3_alpha.toFixed(2) + '%';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
554
  }
555
  }
556
 
@@ -656,6 +808,9 @@ function runFakeSimulation() {
656
  // Initialize the application
657
  async function initialize() {
658
  try {
 
 
 
659
  // Initialize charts
660
  initializeCharts();
661
 
@@ -670,6 +825,31 @@ async function initialize() {
670
  // Add event listener to run button
671
  document.getElementById('runButton').addEventListener('click', runOptimization);
672
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673
  // Run fake simulation for initial visual
674
  runFakeSimulation();
675
 
 
21
  return date.toISOString().split('T')[0];
22
  }
23
 
24
+ // Set active navigation link
25
+ function setActiveNavLink() {
26
+ const currentPath = window.location.pathname;
27
+ const navLinks = document.querySelectorAll('.nav-link');
28
+
29
+ navLinks.forEach(link => {
30
+ const linkPath = link.getAttribute('href');
31
+ if (currentPath.endsWith(linkPath) ||
32
+ (currentPath.endsWith('/') && linkPath === '/index.html')) {
33
+ link.classList.add('active');
34
+ } else {
35
+ link.classList.remove('active');
36
+ }
37
+ });
38
+ }
39
+
40
  // Populate the stock list with sectors and tickers
41
  function populateStockList(sectors) {
42
  const stockListElement = document.getElementById('stockList');
 
544
 
545
  // Update performance metrics for all three portfolios
546
  function updateMetrics(metrics) {
547
+ // Format values for display
548
+ const formatValue = (value, format = 'decimal') => {
549
+ if (value === undefined || value === null) return '-';
550
+
551
+ if (format === 'percent') {
552
+ // For cumulative returns, we need to subtract 1 first to get the percent change
553
+ if (format === 'percent' && value > 1) {
554
+ // This is a cumulative return (started at 1)
555
+ return ((value - 1) * 100).toFixed(2) + '%';
556
+ }
557
+ return (value * 100).toFixed(2) + '%';
558
+ } else if (format === 'decimal') {
559
+ return value.toFixed(2);
560
+ }
561
+ return value;
562
+ };
563
+
564
+ // Make sure metrics objects exist to avoid errors
565
+ if (!metrics) {
566
+ console.error('No metrics data provided to updateMetrics');
567
+ metrics = {
568
+ ogd: { sharpe: 0, max_drawdown: 0, cumulative_return: 1, capm_alpha: 0, ff3_alpha: 0 },
569
+ equal_weight: { sharpe: 0, max_drawdown: 0, cumulative_return: 1, capm_alpha: 0, ff3_alpha: 0 },
570
+ random: { sharpe: 0, max_drawdown: 0, cumulative_return: 1, capm_alpha: 0, ff3_alpha: 0 }
571
+ };
572
+ }
573
+
574
+ // Initialize metric objects if missing
575
+ if (!metrics.ogd) metrics.ogd = {};
576
+ if (!metrics.equal_weight) metrics.equal_weight = {};
577
+ if (!metrics.random) metrics.random = {};
578
+
579
+ const statsRow = document.querySelector('.stats-row');
580
+ if (!statsRow) {
581
+ console.error('Stats row element not found');
582
+ return;
583
+ }
584
+
585
+ // Clear the grid
586
+ statsRow.innerHTML = '';
587
+
588
+ // Create strategy titles (column headers)
589
+ const strategies = [
590
+ { id: 'ogd', name: 'OGD Portfolio', class: 'ogd-strategy' },
591
+ { id: 'equal_weight', name: 'Equal Weight', class: 'equal-weight-strategy' },
592
+ { id: 'random', name: 'Random Portfolio', class: 'random-strategy' }
593
+ ];
594
+
595
+ // Define metrics to display (row headers)
596
+ const metricTypes = [
597
+ { id: 'sharpe', name: 'Sharpe Ratio', format: 'decimal' },
598
+ { id: 'max_drawdown', name: 'Max Drawdown', format: 'percent' },
599
+ { id: 'cumulative_return', name: 'Return', format: 'percent' },
600
+ { id: 'capm_alpha', name: 'CAPM Alpha', format: 'percent' },
601
+ { id: 'ff3_alpha', name: 'FF3 Alpha', format: 'percent' }
602
+ ];
603
+
604
+ // Add column headers (strategy names)
605
+ // Empty cell for top-left corner
606
+ const emptyHeader = document.createElement('div');
607
+ emptyHeader.className = 'stat-card metric-label strategy-header';
608
+ emptyHeader.innerHTML = '<div class="stat-value">Metrics</div>';
609
+ statsRow.appendChild(emptyHeader);
610
+
611
+ // Create strategy headers
612
+ strategies.forEach(strategy => {
613
+ const strategyHeader = document.createElement('div');
614
+ strategyHeader.className = `stat-card strategy-header ${strategy.class}`;
615
+ strategyHeader.innerHTML = `<div class="stat-value">${strategy.name}</div>`;
616
+ statsRow.appendChild(strategyHeader);
617
+ });
618
+
619
+ // Add metric rows
620
+ metricTypes.forEach(metric => {
621
+ // Add row label
622
+ const metricLabel = document.createElement('div');
623
+ metricLabel.className = 'stat-card metric-label';
624
+ metricLabel.innerHTML = `<div class="stat-value">${metric.name}</div>`;
625
+ statsRow.appendChild(metricLabel);
626
+
627
+ // Add values for each strategy
628
+ strategies.forEach(strategy => {
629
+ // Get the value safely
630
+ const value = metrics[strategy.id][metric.id] || 0;
631
+ let formattedValue = '-';
632
+
633
+ // Handle cumulative return differently
634
+ if (metric.id === 'cumulative_return') {
635
+ formattedValue = ((value - 1) * 100).toFixed(2) + '%';
636
+ } else if (metric.format === 'percent') {
637
+ formattedValue = (value * 100).toFixed(2) + '%';
638
+ } else {
639
+ formattedValue = formatValue(value, metric.format);
640
+ }
641
+
642
+ const metricCell = document.createElement('div');
643
+ metricCell.className = `stat-card metric-row ${strategy.class}`;
644
+ metricCell.setAttribute('data-metric', metric.name);
645
+ metricCell.innerHTML = `<div class="stat-value">${formattedValue}</div>`;
646
+ statsRow.appendChild(metricCell);
647
+ });
648
+ });
649
+
650
+ // Log grid creation
651
+ console.log('Metrics grid created with', strategies.length * metricTypes.length, 'cells');
652
+
653
+ // Update legacy hidden elements
654
+ try {
655
+ // Legacy element ID updates for backward compatibility
656
+ const ogdSharpe = document.getElementById('ogdSharpeRatio');
657
+ if (ogdSharpe) ogdSharpe.textContent = formatValue(metrics.ogd.sharpe);
658
+
659
+ const ogdDrawdown = document.getElementById('ogdMaxDrawdown');
660
+ if (ogdDrawdown) ogdDrawdown.textContent = formatValue(metrics.ogd.max_drawdown, 'percent');
661
+
662
+ const ogdReturn = document.getElementById('ogdReturn');
663
+ if (ogdReturn) ogdReturn.textContent = ((metrics.ogd.cumulative_return - 1) * 100).toFixed(2) + '%';
664
+
665
+ const ewSharpe = document.getElementById('ewSharpeRatio');
666
+ if (ewSharpe) ewSharpe.textContent = formatValue(metrics.equal_weight.sharpe);
667
+
668
+ const ewDrawdown = document.getElementById('ewMaxDrawdown');
669
+ if (ewDrawdown) ewDrawdown.textContent = formatValue(metrics.equal_weight.max_drawdown, 'percent');
670
+
671
+ const ewReturn = document.getElementById('ewReturn');
672
+ if (ewReturn) ewReturn.textContent = ((metrics.equal_weight.cumulative_return - 1) * 100).toFixed(2) + '%';
673
+
674
+ const randomSharpe = document.getElementById('randomSharpeRatio');
675
+ if (randomSharpe) randomSharpe.textContent = formatValue(metrics.random.sharpe);
676
+
677
+ const randomDrawdown = document.getElementById('randomMaxDrawdown');
678
+ if (randomDrawdown) randomDrawdown.textContent = formatValue(metrics.random.max_drawdown, 'percent');
679
+
680
+ const randomReturn = document.getElementById('randomReturn');
681
+ if (randomReturn) randomReturn.textContent = ((metrics.random.cumulative_return - 1) * 100).toFixed(2) + '%';
682
+
683
+ // Update factor alphas if available
684
+ if (metrics.ogd.capm_alpha !== undefined) {
685
+ const ogdCAPM = document.getElementById('ogdCAPMAlpha');
686
+ if (ogdCAPM) ogdCAPM.textContent = formatValue(metrics.ogd.capm_alpha, 'percent');
687
+
688
+ const ogdFF3 = document.getElementById('ogdFF3Alpha');
689
+ if (ogdFF3) ogdFF3.textContent = formatValue(metrics.ogd.ff3_alpha, 'percent');
690
+
691
+ const ewCAPM = document.getElementById('ewCAPMAlpha');
692
+ if (ewCAPM) ewCAPM.textContent = formatValue(metrics.equal_weight.capm_alpha, 'percent');
693
+
694
+ const ewFF3 = document.getElementById('ewFF3Alpha');
695
+ if (ewFF3) ewFF3.textContent = formatValue(metrics.equal_weight.ff3_alpha, 'percent');
696
+
697
+ const randomCAPM = document.getElementById('randomCAPMAlpha');
698
+ if (randomCAPM) randomCAPM.textContent = formatValue(metrics.random.capm_alpha, 'percent');
699
+
700
+ const randomFF3 = document.getElementById('randomFF3Alpha');
701
+ if (randomFF3) randomFF3.textContent = formatValue(metrics.random.ff3_alpha, 'percent');
702
+ }
703
+ } catch (e) {
704
+ console.warn('Error updating legacy elements:', e);
705
+ // Continue execution even if legacy element update fails
706
  }
707
  }
708
 
 
808
  // Initialize the application
809
  async function initialize() {
810
  try {
811
+ // Set active navigation link
812
+ setActiveNavLink();
813
+
814
  // Initialize charts
815
  initializeCharts();
816
 
 
825
  // Add event listener to run button
826
  document.getElementById('runButton').addEventListener('click', runOptimization);
827
 
828
+ // Create initial metrics grid
829
+ updateMetrics({
830
+ ogd: {
831
+ sharpe: 1.2,
832
+ max_drawdown: 0.12,
833
+ cumulative_return: 1.3,
834
+ capm_alpha: 2.5,
835
+ ff3_alpha: 1.8
836
+ },
837
+ equal_weight: {
838
+ sharpe: 0.9,
839
+ max_drawdown: 0.15,
840
+ cumulative_return: 1.2,
841
+ capm_alpha: 1.2,
842
+ ff3_alpha: 0.8
843
+ },
844
+ random: {
845
+ sharpe: 0.6,
846
+ max_drawdown: 0.2,
847
+ cumulative_return: 1.1,
848
+ capm_alpha: 0.4,
849
+ ff3_alpha: 0.2
850
+ }
851
+ });
852
+
853
  // Run fake simulation for initial visual
854
  runFakeSimulation();
855
 
assets/static/style.css CHANGED
@@ -78,6 +78,40 @@ body {
78
  color: var(--text-secondary);
79
  }
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  .main-content {
82
  display: flex;
83
  flex: 1;
@@ -198,20 +232,71 @@ body {
198
 
199
  .stats-row {
200
  display: grid;
201
- grid-template-columns: repeat(5, 1fr);
202
- grid-template-rows: repeat(3, auto);
203
  gap: var(--spacing-sm);
204
- margin-top: var(--spacing-sm);
 
 
 
 
 
 
205
  }
206
 
207
  .stat-card {
208
- background-color: var(--bg-secondary);
209
- border-radius: 8px;
210
  padding: var(--spacing-sm);
211
  display: flex;
212
  flex-direction: column;
213
  align-items: center;
214
  justify-content: center;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  }
216
 
217
  .stat-title {
@@ -453,7 +538,7 @@ body {
453
  }
454
 
455
  .right-panel {
456
- max-height: 300px;
457
  }
458
 
459
  .config-grid {
@@ -465,15 +550,14 @@ body {
465
  }
466
 
467
  .stats-row {
468
- grid-template-columns: repeat(3, 1fr); /* Show 3 columns on medium screens */
469
- grid-template-rows: repeat(5, auto);
470
  }
471
  }
472
 
473
  @media (max-width: 768px) {
474
  .stats-row {
475
- grid-template-columns: 1fr; /* Show 1 column on small screens */
476
- grid-template-rows: repeat(15, auto);
477
  }
478
 
479
  .ticker-grid {
@@ -481,6 +565,31 @@ body {
481
  }
482
  }
483
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
484
  .alpha-controls {
485
  margin-top: var(--spacing-md);
486
  }
@@ -517,4 +626,432 @@ body {
517
  display: grid;
518
  grid-template-columns: 1fr 1fr 1fr;
519
  gap: var(--spacing-md);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
520
  }
 
78
  color: var(--text-secondary);
79
  }
80
 
81
+ /* Navigation Menu Styles */
82
+ .nav-menu {
83
+ display: flex;
84
+ gap: var(--spacing-lg);
85
+ }
86
+
87
+ .nav-link {
88
+ position: relative;
89
+ color: var(--text-secondary);
90
+ text-decoration: none;
91
+ font-size: var(--font-size-md);
92
+ font-weight: 500;
93
+ padding: var(--spacing-sm) 0;
94
+ transition: color 0.2s;
95
+ }
96
+
97
+ .nav-link:hover {
98
+ color: var(--text-primary);
99
+ }
100
+
101
+ .nav-link.active {
102
+ color: var(--accent-primary);
103
+ }
104
+
105
+ .nav-link.active::after {
106
+ content: '';
107
+ position: absolute;
108
+ left: 0;
109
+ right: 0;
110
+ bottom: -2px;
111
+ height: 2px;
112
+ background-color: var(--accent-primary);
113
+ }
114
+
115
  .main-content {
116
  display: flex;
117
  flex: 1;
 
232
 
233
  .stats-row {
234
  display: grid;
235
+ grid-template-columns: repeat(4, 1fr);
236
+ grid-auto-rows: auto;
237
  gap: var(--spacing-sm);
238
+ margin-top: var(--spacing-md);
239
+ width: 100%;
240
+ background-color: var(--bg-secondary);
241
+ border-radius: 8px;
242
+ padding: var(--spacing-md);
243
+ border: 1px solid var(--border-color);
244
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
245
  }
246
 
247
  .stat-card {
248
+ background-color: var(--bg-tertiary);
249
+ border-radius: 6px;
250
  padding: var(--spacing-sm);
251
  display: flex;
252
  flex-direction: column;
253
  align-items: center;
254
  justify-content: center;
255
+ min-height: 60px;
256
+ border: none;
257
+ box-shadow: none;
258
+ }
259
+
260
+ /* Style for strategy headers (first row) */
261
+ .stat-card.strategy-header {
262
+ background-color: var(--bg-primary);
263
+ border-bottom: 2px solid var(--accent-primary);
264
+ border-top: 2px solid var(--accent-primary);
265
+ font-weight: 600;
266
+ padding: var(--spacing-md) var(--spacing-sm);
267
+ }
268
+
269
+ /* Styling for metric rows */
270
+ .stat-card.metric-row {
271
+ border-left: 3px solid transparent;
272
+ transition: all 0.2s ease;
273
+ }
274
+
275
+ .stat-card.metric-row:hover {
276
+ transform: translateY(-2px);
277
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
278
+ }
279
+
280
+ /* Specific styling for each strategy column */
281
+ .stat-card.ogd-strategy {
282
+ border-left-color: var(--accent-primary);
283
+ }
284
+
285
+ .stat-card.equal-weight-strategy {
286
+ border-left-color: var(--equal-weight-color);
287
+ }
288
+
289
+ .stat-card.random-strategy {
290
+ border-left-color: var(--random-color);
291
+ }
292
+
293
+ /* Specific styling for metric labels */
294
+ .stat-card.metric-label {
295
+ justify-content: flex-start;
296
+ background-color: var(--bg-primary);
297
+ font-weight: 500;
298
+ border-right: 2px solid var(--border-color);
299
+ padding-left: var(--spacing-md);
300
  }
301
 
302
  .stat-title {
 
538
  }
539
 
540
  .right-panel {
541
+ max-height: none;
542
  }
543
 
544
  .config-grid {
 
550
  }
551
 
552
  .stats-row {
553
+ grid-template-columns: repeat(3, 1fr);
 
554
  }
555
  }
556
 
557
  @media (max-width: 768px) {
558
  .stats-row {
559
+ grid-template-columns: 1fr 1fr 1fr;
560
+ font-size: 0.9em;
561
  }
562
 
563
  .ticker-grid {
 
565
  }
566
  }
567
 
568
+ @media (max-width: 576px) {
569
+ .stats-row {
570
+ grid-template-columns: 1fr;
571
+ grid-template-rows: auto;
572
+ }
573
+
574
+ .stat-card.strategy-header {
575
+ grid-column: 1 / -1;
576
+ text-align: center;
577
+ margin-top: var(--spacing-md);
578
+ }
579
+
580
+ .stat-card.metric-label {
581
+ display: none;
582
+ }
583
+
584
+ .stat-card.metric-row::before {
585
+ content: attr(data-metric);
586
+ display: block;
587
+ font-size: var(--font-size-xs);
588
+ color: var(--text-secondary);
589
+ margin-bottom: var(--spacing-xs);
590
+ }
591
+ }
592
+
593
  .alpha-controls {
594
  margin-top: var(--spacing-md);
595
  }
 
626
  display: grid;
627
  grid-template-columns: 1fr 1fr 1fr;
628
  gap: var(--spacing-md);
629
+ }
630
+
631
+ /* Education Page Styles */
632
+ .education-container {
633
+ width: 100%;
634
+ max-width: 100%;
635
+ margin: 0 auto;
636
+ padding: var(--spacing-lg);
637
+ overflow-y: auto;
638
+ height: calc(100vh - 80px);
639
+ }
640
+
641
+ .education-header {
642
+ margin-bottom: var(--spacing-xl);
643
+ text-align: center;
644
+ }
645
+
646
+ .education-header h2 {
647
+ font-size: var(--font-size-xxl);
648
+ margin-bottom: var(--spacing-md);
649
+ color: var(--accent-primary);
650
+ }
651
+
652
+ .education-header p {
653
+ font-size: var(--font-size-md);
654
+ color: var(--text-secondary);
655
+ max-width: 800px;
656
+ margin: 0 auto;
657
+ }
658
+
659
+ .variable-definitions {
660
+ background-color: var(--bg-secondary);
661
+ border-radius: 8px;
662
+ padding: var(--spacing-xl);
663
+ margin-bottom: var(--spacing-xl);
664
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
665
+ }
666
+
667
+ .variable-definitions h3 {
668
+ font-size: var(--font-size-xl);
669
+ margin-bottom: var(--spacing-lg);
670
+ text-align: center;
671
+ color: var(--accent-primary);
672
+ }
673
+
674
+ .variable-grid {
675
+ display: grid;
676
+ grid-template-columns: auto 1fr;
677
+ gap: var(--spacing-lg) var(--spacing-xl);
678
+ max-width: 800px;
679
+ margin: 0 auto;
680
+ }
681
+
682
+ .variable-math {
683
+ font-size: var(--font-size-lg);
684
+ color: var(--text-primary);
685
+ display: flex;
686
+ align-items: center;
687
+ }
688
+
689
+ .variable-math .math-symbol {
690
+ color: var(--accent-primary);
691
+ margin-right: var(--spacing-sm);
692
+ }
693
+
694
+ .variable-description {
695
+ font-size: var(--font-size-md);
696
+ color: var(--text-secondary);
697
+ }
698
+
699
+ .subsection {
700
+ margin-bottom: var(--spacing-xl);
701
+ }
702
+
703
+ .subsection h3 {
704
+ font-size: var(--font-size-lg);
705
+ margin-bottom: var(--spacing-md);
706
+ color: var(--accent-primary);
707
+ }
708
+
709
+ .subsection p {
710
+ margin-bottom: var(--spacing-md);
711
+ font-size: var(--font-size-md);
712
+ color: var(--text-secondary);
713
+ }
714
+
715
+ .chart-container {
716
+ display: flex;
717
+ flex-wrap: wrap;
718
+ gap: var(--spacing-lg);
719
+ margin-top: var(--spacing-lg);
720
+ margin-bottom: var(--spacing-xl);
721
+ position: relative; /* Add positioning context */
722
+ }
723
+
724
+ .edu-chart {
725
+ flex: 1;
726
+ min-width: 400px;
727
+ background-color: var(--bg-secondary);
728
+ border-radius: 8px;
729
+ padding: var(--spacing-md);
730
+ height: 300px;
731
+ position: relative; /* Ensure proper stacking context */
732
+ }
733
+
734
+ .edu-chart h4 {
735
+ text-align: center;
736
+ margin-bottom: var(--spacing-sm);
737
+ font-size: var(--font-size-md);
738
+ color: var(--text-primary);
739
+ }
740
+
741
+ /* Override fixed height for the grid container and apply proper spacing */
742
+ .edu-metrics-grid {
743
+ height: auto !important; /* Force override with !important */
744
+ min-height: 250px;
745
+ max-height: none;
746
+ overflow: visible;
747
+ padding-bottom: var(--spacing-lg);
748
+ margin-bottom: var(--spacing-lg);
749
+ }
750
+
751
+ /* Add new class for the objective-charts-wrapper */
752
+ .objective-charts-wrapper {
753
+ position: relative;
754
+ margin-bottom: 350px; /* Large margin to ensure space for descriptions */
755
+ }
756
+
757
+ /* Add new class for the objective-descriptions-wrapper */
758
+ .objective-descriptions-wrapper {
759
+ position: relative;
760
+ clear: both;
761
+ width: 100%;
762
+ }
763
+
764
+ .asset-descriptions {
765
+ display: flex;
766
+ flex-wrap: wrap;
767
+ gap: var(--spacing-md);
768
+ margin-top: var(--spacing-lg);
769
+ position: relative; /* Ensure proper position */
770
+ z-index: 1; /* Ensure it's above other elements */
771
+ }
772
+
773
+ .asset-description {
774
+ flex: 1;
775
+ min-width: 250px;
776
+ background-color: var(--bg-tertiary);
777
+ border-radius: 8px;
778
+ padding: var(--spacing-md);
779
+ position: relative; /* Ensure proper stacking */
780
+ }
781
+
782
+ .asset-description h5 {
783
+ font-size: var(--font-size-sm);
784
+ margin-bottom: var(--spacing-xs);
785
+ font-weight: 600;
786
+ }
787
+
788
+ .asset-description:nth-child(1) h5 {
789
+ color: #3f88e2; /* Asset A color */
790
+ }
791
+
792
+ .asset-description:nth-child(2) h5 {
793
+ color: #4caf50; /* Asset B color */
794
+ }
795
+
796
+ .asset-description:nth-child(3) h5 {
797
+ color: #e2b53f; /* Asset C color */
798
+ }
799
+
800
+ /* Maximum Drawdown asset colors */
801
+ #maximum-drawdown .asset-description:nth-child(1) h5 {
802
+ color: #ff6384; /* Asset D color */
803
+ }
804
+
805
+ #maximum-drawdown .asset-description:nth-child(2) h5 {
806
+ color: #36a2eb; /* Asset E color */
807
+ }
808
+
809
+ #maximum-drawdown .asset-description:nth-child(3) h5 {
810
+ color: #ffcd56; /* Asset F color */
811
+ }
812
+
813
+ .demo-title {
814
+ font-size: var(--font-size-md);
815
+ font-weight: 600;
816
+ margin: var(--spacing-lg) 0 var(--spacing-xs) 0;
817
+ color: var(--accent-primary);
818
+ }
819
+
820
+ .demo-description {
821
+ font-size: var(--font-size-sm);
822
+ color: var(--text-secondary);
823
+ margin-bottom: var(--spacing-md);
824
+ max-width: 900px;
825
+ }
826
+
827
+ /* Concentration Example Styles */
828
+ .concentration-explanations {
829
+ display: flex;
830
+ flex-wrap: wrap;
831
+ gap: var(--spacing-md);
832
+ margin-top: var(--spacing-lg);
833
+ }
834
+
835
+ .concentration-example {
836
+ flex: 1;
837
+ min-width: 300px;
838
+ background-color: var(--bg-tertiary);
839
+ border-radius: 8px;
840
+ padding: var(--spacing-md);
841
+ }
842
+
843
+ .concentration-example h5 {
844
+ font-size: var(--font-size-md);
845
+ margin-bottom: var(--spacing-xs);
846
+ font-weight: 600;
847
+ }
848
+
849
+ .concentration-example:nth-child(1) h5 {
850
+ color: #ff6384; /* Concentrated portfolio */
851
+ }
852
+
853
+ .concentration-example:nth-child(2) h5 {
854
+ color: #4caf50; /* Balanced portfolio */
855
+ }
856
+
857
+ .concentration-example:nth-child(3) h5 {
858
+ color: #ffcd56; /* Over-diversified portfolio */
859
+ }
860
+
861
+ /* ENP Indicator Styles */
862
+ .enp-indicator {
863
+ margin-top: var(--spacing-md);
864
+ }
865
+
866
+ .enp-value {
867
+ display: block;
868
+ font-size: var(--font-size-md);
869
+ font-weight: 600;
870
+ margin-bottom: var(--spacing-xs);
871
+ }
872
+
873
+ .concentration-example:nth-child(1) .enp-value {
874
+ color: #ff6384;
875
+ }
876
+
877
+ .concentration-example:nth-child(2) .enp-value {
878
+ color: #4caf50;
879
+ }
880
+
881
+ .concentration-example:nth-child(3) .enp-value {
882
+ color: #ffcd56;
883
+ }
884
+
885
+ .enp-bar {
886
+ height: 10px;
887
+ background-color: var(--bg-primary);
888
+ border-radius: 5px;
889
+ position: relative;
890
+ margin-top: var(--spacing-md);
891
+ margin-bottom: var(--spacing-lg);
892
+ overflow: hidden;
893
+ }
894
+
895
+ .enp-progress {
896
+ height: 100%;
897
+ border-radius: 5px;
898
+ position: absolute;
899
+ top: 0;
900
+ left: 0;
901
+ max-width: 100%;
902
+ }
903
+
904
+ .concentration-example:nth-child(1) .enp-progress {
905
+ background-color: #ff6384;
906
+ }
907
+
908
+ .concentration-example:nth-child(2) .enp-progress {
909
+ background-color: #4caf50;
910
+ }
911
+
912
+ .concentration-example:nth-child(3) .enp-progress {
913
+ background-color: #ffcd56;
914
+ }
915
+
916
+ .enp-marker {
917
+ position: absolute;
918
+ bottom: -25px;
919
+ transform: translateX(-50%);
920
+ font-size: var(--font-size-xs);
921
+ color: var(--text-secondary);
922
+ }
923
+
924
+ .enp-marker::before {
925
+ content: '';
926
+ position: absolute;
927
+ top: -15px;
928
+ left: 50%;
929
+ transform: translateX(-50%);
930
+ height: 12px;
931
+ width: 1px;
932
+ background-color: var(--border-color);
933
+ }
934
+
935
+ .min-marker::before {
936
+ background-color: #ff9800;
937
+ }
938
+
939
+ .max-marker::before {
940
+ background-color: #8bc34a;
941
+ }
942
+
943
+ /* Formula Styles */
944
+ .formula-container {
945
+ background-color: var(--bg-tertiary);
946
+ border-radius: 8px;
947
+ padding: var(--spacing-lg);
948
+ margin: var(--spacing-lg) 0;
949
+ display: flex;
950
+ flex-wrap: wrap;
951
+ gap: var(--spacing-xl);
952
+ }
953
+
954
+ .formula {
955
+ flex: 1;
956
+ min-width: 300px;
957
+ }
958
+
959
+ .formula-header {
960
+ font-size: var(--font-size-md);
961
+ font-weight: 600;
962
+ margin-bottom: var(--spacing-md);
963
+ color: var(--accent-primary);
964
+ }
965
+
966
+ .formula-content {
967
+ font-size: var(--font-size-lg);
968
+ color: var(--text-primary);
969
+ line-height: 2.2;
970
+ }
971
+
972
+ .formula-explanation {
973
+ flex: 1;
974
+ min-width: 300px;
975
+ font-size: var(--font-size-sm);
976
+ color: var(--text-secondary);
977
+ }
978
+
979
+ .formula-notation {
980
+ font-size: var(--font-size-md);
981
+ font-style: italic;
982
+ color: var(--text-secondary);
983
+ margin: var(--spacing-sm) 0;
984
+ }
985
+
986
+ /* Mathematical notation */
987
+ .fraction {
988
+ display: inline-block;
989
+ position: relative;
990
+ vertical-align: middle;
991
+ text-align: center;
992
+ font-size: var(--font-size-md);
993
+ }
994
+
995
+ .numerator, .denominator {
996
+ display: block;
997
+ }
998
+
999
+ .numerator {
1000
+ padding: 0 0.2em;
1001
+ border-bottom: 1px solid var(--text-primary);
1002
+ }
1003
+
1004
+ .denominator {
1005
+ padding: 0 0.2em;
1006
+ }
1007
+
1008
+ .sqrt {
1009
+ display: inline-block;
1010
+ position: relative;
1011
+ padding-left: 0.4em;
1012
+ }
1013
+
1014
+ .sqrt:before {
1015
+ content: "√";
1016
+ position: absolute;
1017
+ left: 0;
1018
+ top: -0.1em;
1019
+ font-size: 1.2em;
1020
+ }
1021
+
1022
+ .sqrt-content {
1023
+ display: inline-block;
1024
+ border-top: 1px solid var(--text-primary);
1025
+ padding: 0 0.2em;
1026
+ }
1027
+
1028
+ /* Interactive Demo Styles */
1029
+ .interactive-demo {
1030
+ background-color: var(--bg-secondary);
1031
+ border-radius: 8px;
1032
+ padding: var(--spacing-lg);
1033
+ margin: var(--spacing-lg) 0;
1034
+ }
1035
+
1036
+ .interactive-demo h4 {
1037
+ font-size: var(--font-size-lg);
1038
+ margin-bottom: var(--spacing-md);
1039
+ color: var(--accent-primary);
1040
+ }
1041
+
1042
+ .interactive-demo p {
1043
+ margin-bottom: var(--spacing-md);
1044
+ }
1045
+
1046
+ /* Ensure the grid has proper spacing between rows and columns */
1047
+ .stats-row {
1048
+ display: grid;
1049
+ grid-gap: var(--spacing-sm);
1050
+ width: 100%;
1051
+ background-color: var(--bg-secondary);
1052
+ border-radius: 8px;
1053
+ padding: var(--spacing-md);
1054
+ border: 1px solid var(--border-color);
1055
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
1056
+ position: relative; /* Add positioning context */
1057
  }
data/stock_data.csv CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ba1a04ffe09a116240c3d7bf2dfd1fac2fc817d83727c3d373f89bc23ec5eb2d
3
- size 14676155
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3baa73dc1a237a71c15ac4fcdfe76bc99b4a9bc7729dbdf780bfdedca057ea4c
3
+ size 46134809
data/tickers_by_sector.json CHANGED
@@ -1,42 +1 @@
1
- [
2
- {
3
- "sector": "Technology",
4
- "tickers": ["AAPL", "MSFT", "NVDA", "GOOGL", "META", "AVGO", "ORCL", "IBM", "CSCO", "TSM", "ASML", "AMD", "TXN", "INTC", "MU", "QCOM", "LRCX", "NXPI", "ADI"]
5
- },
6
- {
7
- "sector": "Consumer Discretionary",
8
- "tickers": ["AMZN", "TSLA", "NKE", "MCD", "SBUX", "YUM", "GM", "F", "RIVN", "NIO", "TTWO", "EA", "GME", "AMC"]
9
- },
10
- {
11
- "sector": "Financials",
12
- "tickers": ["JPM", "V", "MA", "GS", "MS", "BAC", "C", "AXP", "SCHW"]
13
- },
14
- {
15
- "sector": "Health Care",
16
- "tickers": ["UNH", "JNJ", "LLY", "PFE", "MRNA", "BMY", "GILD", "CVS", "VRTX", "ISRG"]
17
- },
18
- {
19
- "sector": "Consumer Staples",
20
- "tickers": ["WMT", "PG", "TGT", "KO", "PEP", "TSN", "CAG", "SYY", "HRL", "MDLZ"]
21
- },
22
- {
23
- "sector": "Energy",
24
- "tickers": ["XOM", "CVX", "NEE", "DUK", "SO", "D", "ENB", "SLB", "EOG", "PSX"]
25
- },
26
- {
27
- "sector": "Industrials",
28
- "tickers": ["DE", "LMT", "RTX", "BA", "CAT", "GE", "HON", "UPS", "EMR", "NOC", "FDX", "CSX", "UNP", "DAL"]
29
- },
30
- {
31
- "sector": "Real Estate",
32
- "tickers": ["PLD", "AMT", "EQIX", "O", "SPG", "VICI", "DLR", "WY", "EQR", "PSA"]
33
- },
34
- {
35
- "sector": "Materials",
36
- "tickers": ["ADM", "BG", "CF", "MOS", "FMC"]
37
- },
38
- {
39
- "sector": "Communication Services",
40
- "tickers": ["NFLX", "DIS", "PARA", "WBD", "CMCSA", "SPOT", "LYV"]
41
- }
42
- ]
 
1
+ [{"sector": "Technology", "tickers": ["AAPL", "MSFT", "NVDA", "GOOGL", "META", "AVGO", "ORCL", "IBM", "CSCO", "TSM", "ASML", "AMD", "TXN", "INTC", "MU", "QCOM", "LRCX", "NXPI", "ADI", "CRM", "INTU", "ADBE", "SNPS", "PANW", "CRWD", "ARM", "PLTR", "NOW", "DDOG", "MDB", "ZS", "OKTA", "SPLK", "NET", "FSLY", "DOCU", "AKAM", "ANET", "TWLO", "WDAY"]}, {"sector": "Consumer Discretionary", "tickers": ["AMZN", "TSLA", "NKE", "MCD", "SBUX", "YUM", "GM", "F", "RIVN", "NIO", "TTWO", "EA", "GME", "AMC", "HD", "LOW", "BKNG", "MAR", "TJX", "RCL", "RL", "FOXA", "NWSA", "WMT", "TGT", "BBY", "EBAY", "ROST", "DPZ", "ULTA", "EXPE", "DKS", "AZO", "ORLY", "KMX", "LEN", "DHI", "TOL", "PVH", "BBWI"]}, {"sector": "Financials", "tickers": ["JPM", "V", "MA", "GS", "MS", "BAC", "C", "AXP", "SCHW", "WFC", "TD", "RY", "BK", "NTRS", "ICE", "CME", "TW", "SPGI", "MSCI", "BLK", "COF", "DFS", "MTB", "FITB", "CFG", "ALLY", "PGR", "AFL", "PRU", "TRV"]}, {"sector": "Health Care", "tickers": ["UNH", "JNJ", "LLY", "PFE", "MRNA", "BMY", "GILD", "CVS", "VRTX", "ISRG", "MRK", "ABBV", "BSX", "MCK", "CAH", "DGX", "RMD", "PODD", "REGN", "TMO", "BDX", "ZBH", "EW", "IDXX", "IQV", "HUM", "CI", "ABC", "BAX", "ALGN"]}, {"sector": "Consumer Staples", "tickers": ["PG", "KO", "PEP", "TSN", "CAG", "SYY", "HRL", "MDLZ", "KDP", "CELH", "MNST", "CHD", "EL", "SJM", "STZ", "CL", "KMB", "KR", "GIS", "CPB", "HSY", "TAP", "K", "MO", "PM", "BTI", "UL", "NSRGY"]}, {"sector": "Energy", "tickers": ["XOM", "CVX", "NEE", "DUK", "SO", "D", "ENB", "SLB", "EOG", "PSX", "MPC", "VLO", "FANG", "DVN", "PXD", "MRO", "TRGP", "LNG", "BKR", "EQNR", "HAL", "APA", "OVV", "CNQ", "SU", "CEG", "COP", "CVE", "WMB", "OKE"]}, {"sector": "Industrials", "tickers": ["DE", "LMT", "RTX", "BA", "CAT", "GE", "HON", "UPS", "EMR", "NOC", "FDX", "CSX", "UNP", "DAL", "ITW", "GWW", "ODFL", "GEV", "PH", "IR", "TT", "TDG", "ETN", "CNM", "WM", "RHI", "MMM", "FAST", "LUV", "JCI"]}, {"sector": "Real Estate", "tickers": ["PLD", "AMT", "EQIX", "O", "SPG", "VICI", "DLR", "WY", "EQR", "PSA", "WELL", "VTR", "MPW", "STRW", "SILA", "EXR", "AVB", "SBAC", "CCI", "HST", "PEAK", "BXP", "SLG", "KIM", "REG", "ARE", "HIW", "STAG", "UBA", "FRT"]}, {"sector": "Materials", "tickers": ["ADM", "BG", "CF", "MOS", "FMC", "RIO", "NUE", "APD", "EXP", "LIN", "ECL", "CTVA", "DOW", "FCX", "AXTA", "CC", "ATR", "ASH", "SLGN", "DD", "PKG", "IP", "MLM", "VMC", "ALB", "LYB", "AVNT", "MP", "RS", "ATI"]}, {"sector": "Communication Services", "tickers": ["NFLX", "DIS", "PARA", "WBD", "CMCSA", "SPOT", "LYV", "TMUS", "VZ", "T", "CHTR", "BIDU", "TCEHY", "TTD", "RNG", "CXDO", "OOMA", "EVER", "NRDS", "ATVI", "Z", "BMBL", "MTCH", "BILI", "HUYA", "YY", "FWONA", "FWONK", "LSXMA"]}, {"sector": "Utilities", "tickers": ["AEP", "EXC", "SRE", "WEC", "ES", "EIX", "PEG", "XEL", "ED", "NRG", "AES", "AWK", "CMS", "PNW", "ATO", "UGI"]}, {"sector": "Information Services", "tickers": ["FDS", "MCO", "IHS", "TRU", "INFO", "DNB"]}, {"sector": "Semiconductors", "tickers": ["ON", "SWKS", "MPWR", "AMAT", "KLAC", "TER", "WOLF", "RMBS"]}]