Parthiban97 commited on
Commit
107cd56
·
verified ·
1 Parent(s): 6ac0646

Delete src/pdf_generator.py

Browse files
Files changed (1) hide show
  1. src/pdf_generator.py +0 -560
src/pdf_generator.py DELETED
@@ -1,560 +0,0 @@
1
- """
2
- PDF Generator: Produces the investor portfolio review PDF.
3
-
4
- Layout (matching the sample investor-portfolio-review PDF):
5
- Page 1:
6
- - Header (Advisor + Client details)
7
- - Executive Summary (total value, gain, metrics)
8
- - Holdings table (all schemes with score)
9
- - Market Cap Allocation pie
10
- - Sector Allocation bar
11
-
12
- Page 2+:
13
- - Per-scheme detail block (fund metrics vs top quartile vs benchmark)
14
- - Underperforming flags
15
- - Switch suggestion (if any)
16
- - Capital gains estimate (if switch suggested)
17
-
18
- Final Page:
19
- - Wealth Projection chart
20
- - Disclaimer
21
- """
22
-
23
- import io
24
- import os
25
- from pathlib import Path
26
- from datetime import datetime
27
- from typing import Optional, List
28
- from reportlab.lib.pagesizes import A4
29
- from reportlab.lib import colors
30
- from reportlab.lib.units import mm
31
- from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
32
- from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT
33
- from reportlab.platypus import (
34
- SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
35
- HRFlowable, PageBreak, Image, KeepTogether
36
- )
37
- from reportlab.platypus.flowables import Flowable
38
- from reportlab.graphics.shapes import Drawing, Rect, String
39
- import matplotlib
40
- matplotlib.use('Agg')
41
-
42
- from src.models import PortfolioReport, ClientHolding, Fund
43
- from src import charts as ch
44
-
45
-
46
- # ─── Theme ───────────────────────────────────────────────────────────────────
47
-
48
- DARK_BLUE = colors.HexColor("#1F3864")
49
- MID_BLUE = colors.HexColor("#2E75B6")
50
- LIGHT_BLUE = colors.HexColor("#BDD7EE")
51
- GREEN = colors.HexColor("#2ECC71")
52
- ORANGE = colors.HexColor("#E67E22")
53
- RED = colors.HexColor("#E74C3C")
54
- GREY_BG = colors.HexColor("#F5F5F5")
55
- LIGHT_GREY = colors.HexColor("#D9D9D9")
56
- WHITE = colors.white
57
- BLACK = colors.black
58
-
59
- W, H = A4
60
- MARGIN = 15 * mm
61
-
62
- styles = getSampleStyleSheet()
63
-
64
- def S(name, **kwargs):
65
- """Quick style builder."""
66
- return ParagraphStyle(name, parent=styles['Normal'], **kwargs)
67
-
68
-
69
- # ─── Style Definitions ────────────────────────────────────────────────────────
70
-
71
- STYLE_TITLE = S("Title", fontSize=18, textColor=DARK_BLUE, fontName="Helvetica-Bold",
72
- spaceAfter=2, alignment=TA_CENTER)
73
- STYLE_SUBTITLE = S("Subtitle", fontSize=9, textColor=MID_BLUE, fontName="Helvetica",
74
- spaceAfter=4, alignment=TA_CENTER)
75
- STYLE_H1 = S("H1", fontSize=11, textColor=DARK_BLUE, fontName="Helvetica-Bold",
76
- spaceAfter=3, spaceBefore=6)
77
- STYLE_H2 = S("H2", fontSize=9, textColor=DARK_BLUE, fontName="Helvetica-Bold",
78
- spaceAfter=2, spaceBefore=4)
79
- STYLE_BODY = S("Body", fontSize=8, textColor=BLACK,
80
- spaceAfter=2)
81
- STYLE_SMALL = S("Small", fontSize=7, textColor=colors.HexColor("#555555"),
82
- spaceAfter=1)
83
- STYLE_WARN = S("Warn", fontSize=8, textColor=colors.HexColor("#C0392B"),
84
- fontName="Helvetica-Bold")
85
- STYLE_OK = S("OK", fontSize=8, textColor=colors.HexColor("#27AE60"),
86
- fontName="Helvetica-Bold")
87
- STYLE_DISCLAIMER= S("Disc", fontSize=6, textColor=colors.HexColor("#666666"),
88
- spaceAfter=2, leading=8)
89
-
90
-
91
- def _fmt_inr(value: float) -> str:
92
- """Format as Indian currency string."""
93
- if value is None:
94
- return "N/A"
95
- if abs(value) >= 1e7:
96
- return f"₹{value/1e7:.2f} Cr"
97
- if abs(value) >= 1e5:
98
- return f"₹{value/1e5:.2f} L"
99
- return f"₹{value:,.0f}"
100
-
101
-
102
- def _fmt_pct(value: Optional[float], decimals: int = 2) -> str:
103
- if value is None:
104
- return "N/A"
105
- return f"{value:.{decimals}f}%"
106
-
107
-
108
- def _fmt_float(value: Optional[float], decimals: int = 2) -> str:
109
- if value is None:
110
- return "N/A"
111
- return f"{value:.{decimals}f}"
112
-
113
-
114
- def _img_from_buf(buf: io.BytesIO, width_mm: float, height_mm: float) -> Image:
115
- """Create a ReportLab Image from a BytesIO buffer."""
116
- img = Image(buf)
117
- img.drawWidth = width_mm * mm
118
- img.drawHeight = height_mm * mm
119
- return img
120
-
121
-
122
- def _table_style(header_color=DARK_BLUE, row_alt=GREY_BG):
123
- return TableStyle([
124
- ('BACKGROUND', (0, 0), (-1, 0), header_color),
125
- ('TEXTCOLOR', (0, 0), (-1, 0), WHITE),
126
- ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
127
- ('FONTSIZE', (0, 0), (-1, 0), 7),
128
- ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
129
- ('ROWBACKGROUNDS', (0, 1), (-1, -1), [WHITE, row_alt]),
130
- ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
131
- ('FONTSIZE', (0, 1), (-1, -1), 7),
132
- ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
133
- ('ALIGN', (0, 1), (0, -1), 'LEFT'),
134
- ('GRID', (0, 0), (-1, -1), 0.3, LIGHT_GREY),
135
- ('TOPPADDING', (0, 0), (-1, -1), 3),
136
- ('BOTTOMPADDING', (0, 0), (-1, -1), 3),
137
- ('LEFTPADDING', (0, 0), (-1, -1), 4),
138
- ('RIGHTPADDING', (0, 0), (-1, -1), 4),
139
- ])
140
-
141
-
142
- # ─── Section Builders ────────────────────────────────────────────────────────
143
-
144
- def _build_header(report: PortfolioReport) -> List:
145
- """Build the header section: advisor brand + client info."""
146
- adv = report.advisor
147
- cli = report.client
148
- today = datetime.now().strftime("%d %B %Y")
149
-
150
- elements = []
151
-
152
- # Top bar (advisor on left, date on right)
153
- header_data = [[
154
- Paragraph(f"<b>{adv.name}</b><br/>"
155
- f"<font size='8' color='#2E75B6'>{adv.location} | {adv.phone} | {adv.email}</font><br/>"
156
- f"<font size='7' color='#888888'>{adv.arn} | AMFI Registered Mutual Fund Distributor</font>",
157
- S("adv", fontName='Helvetica-Bold', fontSize=10, textColor=DARK_BLUE)),
158
- Paragraph(f"<para align='right'><font size='8' color='#888888'>"
159
- f"Date: {today}</font></para>",
160
- STYLE_SMALL),
161
- ]]
162
- header_table = Table(header_data, colWidths=[120*mm, 60*mm])
163
- header_table.setStyle(TableStyle([
164
- ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
165
- ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
166
- ]))
167
- elements.append(header_table)
168
- elements.append(HRFlowable(width="100%", thickness=2, color=MID_BLUE, spaceAfter=4))
169
-
170
- # Report title
171
- elements.append(Paragraph("Investor Portfolio Review", STYLE_TITLE))
172
- elements.append(Paragraph("Confidential | Prepared exclusively for the client", STYLE_SUBTITLE))
173
- elements.append(HRFlowable(width="100%", thickness=0.5, color=LIGHT_GREY, spaceAfter=6))
174
-
175
- # Client info box
176
- client_info = [
177
- ["Client Name", cli.name, "Age", str(cli.age or "N/A")],
178
- ["Mobile", cli.mobile or "N/A", "Email", cli.email or "N/A"],
179
- ["PAN", cli.pan or "N/A", "", ""],
180
- ]
181
- ct = Table(client_info, colWidths=[30*mm, 55*mm, 25*mm, 70*mm])
182
- ct.setStyle(TableStyle([
183
- ('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
184
- ('FONTNAME', (2, 0), (2, -1), 'Helvetica-Bold'),
185
- ('FONTSIZE', (0, 0), (-1, -1), 8),
186
- ('TEXTCOLOR', (0, 0), (0, -1), DARK_BLUE),
187
- ('TEXTCOLOR', (2, 0), (2, -1), DARK_BLUE),
188
- ('ROWBACKGROUNDS', (0, 0), (-1, -1), [GREY_BG, WHITE]),
189
- ('TOPPADDING', (0, 0), (-1, -1), 3),
190
- ('BOTTOMPADDING', (0, 0), (-1, -1), 3),
191
- ('LEFTPADDING', (0, 0), (-1, -1), 4),
192
- ('GRID', (0, 0), (-1, -1), 0.3, LIGHT_GREY),
193
- ]))
194
- elements.append(ct)
195
- elements.append(Spacer(1, 4*mm))
196
- return elements
197
-
198
-
199
- def _build_summary(report: PortfolioReport) -> List:
200
- """Portfolio snapshot summary cards."""
201
- elements = [Paragraph("📊 Portfolio Snapshot", STYLE_H1)]
202
-
203
- gain = report.unrealized_gain
204
- gain_color = "#27AE60" if gain >= 0 else "#E74C3C"
205
- gain_sign = "+" if gain >= 0 else ""
206
-
207
- summary_data = [
208
- ["Current Value", "Total Invested", "Unrealised Gain", "Sharpe Ratio", "Alpha", "Beta"],
209
- [
210
- _fmt_inr(report.total_current_value),
211
- _fmt_inr(report.total_invested),
212
- f"<font color='{gain_color}'>{gain_sign}{_fmt_inr(gain)}</font>",
213
- _fmt_float(report.sharpe),
214
- _fmt_pct(report.alpha),
215
- _fmt_float(report.beta),
216
- ],
217
- ]
218
-
219
- def para_cells(row):
220
- return [Paragraph(str(c), S("sc", fontSize=8, fontName='Helvetica-Bold' if i < 1 else 'Helvetica',
221
- alignment=TA_CENTER, textColor=DARK_BLUE))
222
- for i, c in enumerate(row)]
223
-
224
- tbl = Table(
225
- [para_cells(summary_data[0]), para_cells(summary_data[1])],
226
- colWidths=[30*mm] * 6
227
- )
228
- tbl.setStyle(TableStyle([
229
- ('BACKGROUND', (0, 0), (-1, 0), DARK_BLUE),
230
- ('TEXTCOLOR', (0, 0), (-1, 0), WHITE),
231
- ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
232
- ('FONTSIZE', (0, 0), (-1, -1), 8),
233
- ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
234
- ('ROWBACKGROUNDS', (0, 1), (-1, -1), [LIGHT_BLUE]),
235
- ('GRID', (0, 0), (-1, -1), 0.3, LIGHT_GREY),
236
- ('TOPPADDING', (0, 0), (-1, -1), 5),
237
- ('BOTTOMPADDING', (0, 0), (-1, -1), 5),
238
- ]))
239
- elements.append(tbl)
240
- elements.append(Spacer(1, 4*mm))
241
- return elements
242
-
243
-
244
- def _build_holdings_table(report: PortfolioReport) -> List:
245
- """Main holdings table."""
246
- elements = [Paragraph("📋 Existing Portfolio Holdings", STYLE_H1)]
247
-
248
- rows = [["#", "Scheme Name", "Current Value", "Allocation", "Score", "Status"]]
249
- for i, h in enumerate(report.holdings, 1):
250
- score = _fmt_float(h.fund.score) if h.fund and h.fund.score else "N/A"
251
- status = "⚠️ Underperforms" if h.is_underperforming else "✅ On Track"
252
- rows.append([
253
- str(i),
254
- h.scheme_name[:45],
255
- _fmt_inr(h.current_value),
256
- _fmt_pct(h.allocation_pct),
257
- score,
258
- status,
259
- ])
260
- rows.append(["", "<b>TOTAL</b>", _fmt_inr(report.total_current_value), "100%", "", ""])
261
-
262
- tbl = Table(rows, colWidths=[8*mm, 80*mm, 28*mm, 18*mm, 14*mm, 32*mm])
263
- style = _table_style()
264
-
265
- # Red for underperformers, green for on-track (in status column)
266
- for i, h in enumerate(report.holdings, 1):
267
- if h.is_underperforming:
268
- style.add('TEXTCOLOR', (5, i), (5, i), RED)
269
- else:
270
- style.add('TEXTCOLOR', (5, i), (5, i), GREEN)
271
-
272
- # Bold total row
273
- style.add('FONTNAME', (0, len(rows)-1), (-1, len(rows)-1), 'Helvetica-Bold')
274
- style.add('BACKGROUND', (0, len(rows)-1), (-1, len(rows)-1), LIGHT_BLUE)
275
-
276
- tbl.setStyle(style)
277
- elements.append(tbl)
278
- elements.append(Spacer(1, 3*mm))
279
-
280
- # Exposure warnings
281
- if report.exposure_warnings:
282
- elements.append(Paragraph("⚠️ Exposure Alerts", STYLE_H2))
283
- for warn in report.exposure_warnings:
284
- elements.append(Paragraph(warn, STYLE_WARN))
285
- elements.append(Spacer(1, 2*mm))
286
-
287
- return elements
288
-
289
-
290
- def _build_allocation_charts(report: PortfolioReport) -> List:
291
- """Market cap + sector charts side by side."""
292
- elements = [Paragraph("📈 Portfolio Allocation Analysis", STYLE_H1)]
293
-
294
- # Holdings pie
295
- holdings_data = {h.scheme_name: h.current_value for h in report.holdings}
296
- pie_buf = ch.holdings_pie_chart(holdings_data, "Fund-wise Allocation")
297
-
298
- # Market cap pie (use dummy data if not available)
299
- mc_data = report.market_cap_allocation or {
300
- "Large Cap": 10, "Mid Cap": 45, "Small Cap": 40, "Others": 5
301
- }
302
- mc_buf = ch.market_cap_pie(mc_data)
303
-
304
- chart_table = Table(
305
- [[_img_from_buf(pie_buf, 85, 70), _img_from_buf(mc_buf, 80, 70)]],
306
- colWidths=[90*mm, 90*mm]
307
- )
308
- chart_table.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')]))
309
- elements.append(chart_table)
310
- elements.append(Spacer(1, 3*mm))
311
-
312
- # Sector chart
313
- if report.sector_allocation:
314
- sec_buf = ch.sector_bar_chart(report.sector_allocation)
315
- elements.append(Paragraph("🏭 Sector Allocation", STYLE_H2))
316
- elements.append(_img_from_buf(sec_buf, 170, 65))
317
- elements.append(Spacer(1, 3*mm))
318
-
319
- return elements
320
-
321
-
322
- def _build_scheme_details(report: PortfolioReport) -> List:
323
- """Per-scheme detailed analysis blocks."""
324
- elements = [PageBreak(), Paragraph("🔍 Individual Scheme Analysis", STYLE_H1)]
325
-
326
- for h in report.holdings:
327
- fund = h.fund
328
- if not fund:
329
- continue
330
-
331
- # Scheme header
332
- elements.append(Spacer(1, 3*mm))
333
- status_color = "#E74C3C" if h.is_underperforming else "#27AE60"
334
- status_text = "Underperforming vs Benchmark" if h.is_underperforming else "Performing Well"
335
-
336
- elements.append(Paragraph(
337
- f"<b>{h.scheme_name}</b> &nbsp;&nbsp;"
338
- f"<font color='{status_color}' size='8'>[{status_text}]</font>",
339
- STYLE_H2
340
- ))
341
-
342
- # Metrics comparison table
343
- periods = ["1 Year", "3 Year", "5 Year", "10 Year"]
344
- cagr_vals = [
345
- [fund.cagr_1y, fund.cagr_1y_cat, fund.cagr_1y_bm],
346
- [fund.cagr_3y, fund.cagr_3y_cat, fund.cagr_3y_bm],
347
- [fund.cagr_5y, fund.cagr_5y_cat, fund.cagr_5y_bm],
348
- [fund.cagr_10y, fund.cagr_10y_cat, fund.cagr_10y_bm],
349
- ]
350
-
351
- cagr_header = ["Period", "Fund CAGR", "Category Avg", "Benchmark"]
352
- cagr_rows = [cagr_header]
353
- for period, (f_cagr, cat_cagr, bm_cagr) in zip(periods, cagr_vals):
354
- cagr_rows.append([
355
- period,
356
- _fmt_pct(f_cagr),
357
- _fmt_pct(cat_cagr),
358
- _fmt_pct(bm_cagr),
359
- ])
360
-
361
- cagr_tbl = Table(cagr_rows, colWidths=[30*mm, 30*mm, 30*mm, 30*mm])
362
- cagr_style = _table_style(header_color=MID_BLUE)
363
- # Colour fund CAGR red if below benchmark
364
- for row_i, (_, (f_cagr, _, bm_cagr)) in enumerate(zip(periods, cagr_vals), 1):
365
- if f_cagr is not None and bm_cagr is not None:
366
- color = RED if f_cagr < bm_cagr else GREEN
367
- cagr_style.add('TEXTCOLOR', (1, row_i), (1, row_i), color)
368
- cagr_tbl.setStyle(cagr_style)
369
-
370
- # Risk metrics row
371
- risk_header = ["Alpha", "Beta", "Sharpe", "Std Dev", "Sortino", "Max DD", "Score"]
372
- risk_vals = [
373
- _fmt_pct(fund.alpha), _fmt_float(fund.beta),
374
- _fmt_float(fund.sharpe), _fmt_pct(fund.std_dev),
375
- _fmt_float(fund.sortino), _fmt_pct(fund.max_drawdown),
376
- _fmt_float(fund.score),
377
- ]
378
- risk_tbl = Table(
379
- [risk_header, risk_vals],
380
- colWidths=[25*mm, 20*mm, 20*mm, 20*mm, 20*mm, 20*mm, 15*mm]
381
- )
382
- risk_tbl.setStyle(_table_style(header_color=colors.HexColor("#34495E")))
383
-
384
- # Charts: bar chart for this scheme
385
- cagr_chart_data = {
386
- "1Y": {"fund": fund.cagr_1y, "benchmark": fund.cagr_1y_bm, "category": fund.cagr_1y_cat},
387
- "3Y": {"fund": fund.cagr_3y, "benchmark": fund.cagr_3y_bm, "category": fund.cagr_3y_cat},
388
- "5Y": {"fund": fund.cagr_5y, "benchmark": fund.cagr_5y_bm, "category": fund.cagr_5y_cat},
389
- "10Y": {"fund": fund.cagr_10y, "benchmark": fund.cagr_10y_bm, "category": fund.cagr_10y_cat},
390
- }
391
- chart_buf = ch.holding_vs_benchmark_chart(fund.name, cagr_chart_data)
392
-
393
- row_layout = Table(
394
- [[cagr_tbl, _img_from_buf(chart_buf, 80, 55)]],
395
- colWidths=[100*mm, 80*mm]
396
- )
397
- row_layout.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')]))
398
-
399
- block = KeepTogether([
400
- row_layout,
401
- Spacer(1, 2*mm),
402
- risk_tbl,
403
- ])
404
-
405
- # Switch suggestion section
406
- if h.suggested_fund:
407
- sf = h.suggested_fund
408
- elements.append(block)
409
- elements.append(Paragraph(
410
- f"💡 <b>Suggested Switch:</b> {h.scheme_name} → <b>{sf.name}</b>",
411
- STYLE_H2
412
- ))
413
- comp_data = [
414
- ["Metric", "Current Fund", "Suggested Fund"],
415
- ["3Y CAGR", _fmt_pct(fund.cagr_3y), _fmt_pct(sf.cagr_3y)],
416
- ["5Y CAGR", _fmt_pct(fund.cagr_5y), _fmt_pct(sf.cagr_5y)],
417
- ["Alpha", _fmt_pct(fund.alpha), _fmt_pct(sf.alpha)],
418
- ["Sharpe", _fmt_float(fund.sharpe), _fmt_float(sf.sharpe)],
419
- ["TER", _fmt_pct(fund.ter), _fmt_pct(sf.ter)],
420
- ["Score", _fmt_float(fund.score), _fmt_float(sf.score)],
421
- ]
422
- comp_tbl = Table(comp_data, colWidths=[40*mm, 60*mm, 60*mm])
423
- comp_style = _table_style(header_color=colors.HexColor("#8E44AD"))
424
- comp_tbl.setStyle(comp_style)
425
- elements.append(comp_tbl)
426
- else:
427
- elements.append(block)
428
-
429
- elements.append(HRFlowable(width="100%", thickness=0.5, color=LIGHT_GREY, spaceAfter=2))
430
-
431
- return elements
432
-
433
-
434
- def _build_wealth_projection(report: PortfolioReport) -> List:
435
- """Wealth projection table and chart."""
436
- elements = [PageBreak(), Paragraph("💰 Wealth Projection @ 12% p.a.", STYLE_H1)]
437
-
438
- proj = report.wealth_projection
439
- if not proj:
440
- return elements
441
-
442
- proj_data = [["Time Horizon", "Projected Value", "Approx. Growth"]]
443
- current = report.total_current_value
444
- for yr, val in sorted(proj.items()):
445
- growth = ((val - current) / current * 100) if current else 0
446
- proj_data.append([f"{yr} Years", _fmt_inr(val), f"+{growth:.1f}%"])
447
-
448
- proj_tbl = Table(proj_data, colWidths=[40*mm, 60*mm, 40*mm])
449
- proj_tbl.setStyle(_table_style())
450
- elements.append(proj_tbl)
451
- elements.append(Spacer(1, 4*mm))
452
-
453
- # Chart
454
- wc_buf = ch.wealth_projection_chart(proj, current)
455
- elements.append(_img_from_buf(wc_buf, 160, 70))
456
- elements.append(Spacer(1, 4*mm))
457
- return elements
458
-
459
-
460
- DISCLAIMER_TEXT = (
461
- "Disclaimer: We have gathered all the data, information, and statistics from sources believed to be "
462
- "highly reliable and true. All necessary precautions have been taken to avoid any error, lapse or "
463
- "insufficiency; however, no representations or warranties are made (express or implied) as to the "
464
- "reliability, accuracy or completeness of such information. We cannot be held liable for any loss "
465
- "arising directly or indirectly from the use of, or any action taken on, any information appearing herein. "
466
- "The user is advised to verify the contents of the report independently. It is not an Investment recommendation "
467
- "or personal financial, Investment or professional advice and should not be treated as such. The Risk Level of "
468
- "any of the schemes must always be commensurate with the risk profile, Investment objective or financial goals "
469
- "of the investor concerned. Returns less than 1 year are in absolute (%) and greater than 1 year are compounded "
470
- "annualised (CAGR %). SIP returns are shown in XIRR (%). Mutual Fund Investments are subject to market risks, "
471
- "read all scheme related documents carefully. Past performance may or may not be sustained in the future."
472
- )
473
-
474
-
475
- # ─── Main Generator ──────────────────────────────────────────────────────────
476
-
477
- def _build_quartile_section(report: PortfolioReport) -> List:
478
- """
479
- Quartile Analysis Grid — based on senior's handwritten sketch.
480
- Shows BM / Category / Scheme rows × 1Y/3Y/5Y/10Y columns per holding.
481
- Scheme row is color-coded: Q1(green)/Q2(blue)/Q3(yellow)/Q4(red).
482
- """
483
- elements = [Paragraph("📊 Quartile Analysis — Scheme vs Benchmark & Category", STYLE_H1)]
484
- elements.append(Paragraph(
485
- "Each scheme is compared against its Benchmark Index and Category Average "
486
- "across 1Y/3Y/5Y/10Y periods. The Scheme row shows CAGR and is color-coded "
487
- "by quartile rank (Q1=Top, Q4=Bottom). ✓ = Fund beats Benchmark that period.",
488
- STYLE_SMALL
489
- ))
490
- elements.append(Spacer(1, 2*mm))
491
-
492
- grid_data = []
493
- for h in report.holdings:
494
- f = h.fund
495
- if not f:
496
- continue
497
- rank = f.rank_in_category or 1
498
- total = rank * 4 # approximate — will be corrected when fund_universe passed
499
- grid_data.append({
500
- "scheme_name": h.scheme_name,
501
- "rank_in_category": rank,
502
- "total_in_category": total,
503
- "cagr_1y": f.cagr_1y, "cagr_1y_bm": f.cagr_1y_bm, "cagr_1y_cat": f.cagr_1y_cat,
504
- "cagr_3y": f.cagr_3y, "cagr_3y_bm": f.cagr_3y_bm, "cagr_3y_cat": f.cagr_3y_cat,
505
- "cagr_5y": f.cagr_5y, "cagr_5y_bm": f.cagr_5y_bm, "cagr_5y_cat": f.cagr_5y_cat,
506
- "cagr_10y": f.cagr_10y,"cagr_10y_bm": f.cagr_10y_bm,"cagr_10y_cat": f.cagr_10y_cat,
507
- })
508
-
509
- if grid_data:
510
- grid_buf = ch.quartile_analysis_grid(grid_data)
511
- n = len(grid_data)
512
- chart_h = max(75, n * 28)
513
- elements.append(_img_from_buf(grid_buf, 175, min(chart_h, 210)))
514
- else:
515
- elements.append(Paragraph("No matched fund data available.", STYLE_BODY))
516
-
517
- elements.append(Spacer(1, 3*mm))
518
- return elements
519
-
520
-
521
- def generate_pdf(report: PortfolioReport, output_path: str) -> str:
522
- """
523
- Generate the complete PDF report.
524
- Returns: path to the generated PDF.
525
- """
526
- output_path = Path(output_path)
527
- output_path.parent.mkdir(parents=True, exist_ok=True)
528
-
529
- doc = SimpleDocTemplate(
530
- str(output_path),
531
- pagesize=A4,
532
- leftMargin=MARGIN,
533
- rightMargin=MARGIN,
534
- topMargin=MARGIN,
535
- bottomMargin=MARGIN,
536
- )
537
-
538
- story = []
539
-
540
- # ── Page 1 ──────────────────────────────────────────────────────────
541
- story += _build_header(report)
542
- story += _build_summary(report)
543
- story += _build_holdings_table(report)
544
- story += _build_quartile_section(report)
545
- story += _build_allocation_charts(report)
546
-
547
- # ── Per-scheme details ───────────────────────────────────────────────
548
- story += _build_scheme_details(report)
549
-
550
- # ── Wealth projection ────────────────────────────────────────────────
551
- story += _build_wealth_projection(report)
552
-
553
- # ── Disclaimer ───────────────────────────────────────────────────────
554
- story.append(HRFlowable(width="100%", thickness=0.5, color=LIGHT_GREY))
555
- story.append(Spacer(1, 3*mm))
556
- story.append(Paragraph("Disclaimer", STYLE_H2))
557
- story.append(Paragraph(DISCLAIMER_TEXT, STYLE_DISCLAIMER))
558
-
559
- doc.build(story)
560
- return str(output_path)