-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2104 lines (1717 loc) · 77 KB
/
Copy pathmain.py
File metadata and controls
2104 lines (1717 loc) · 77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Standard Library
import os
import math
import json
import base64
from io import BytesIO
from datetime import datetime, timedelta, date
from decimal import Decimal
# Third-Party Libraries
import numpy as np
import pandas as pd
import requests
from dotenv import load_dotenv
import psycopg2
# Plotting & Visualization
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
import matplotlib.font_manager as fm
# PDF Generation (ReportLab)
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.lib import colors
from reportlab.lib.utils import ImageReader
# PDF to Image Conversion
from pdf2image import convert_from_path
# Email (AWS SES)
import boto3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from botocore.exceptions import BotoCoreError, ClientError
# Load environment variables from .env
load_dotenv()
def send_email(image_folder):
# CONFIG
# image_folder = "pdf_image/5 - 9 May 2025" # folder where images are stored
allowed_extensions = {"jpg", "jpeg", "png"}
# AWS SES configuration
aws_access_key_id = os.getenv('AWS_ACCESS_KEY_ID')
aws_secret_access_key = os.getenv('AWS_SECRET_ACCESS_KEY')
aws_region = os.getenv('AWS_REGION', 'us-east-1')
from_email = "gerald@supertype.ai"
to_email = ["geraldbryan9914@gmail.com","shusi.evelyn@gmail.com"]
# Collect all image files from the folder
image_files = [
os.path.join(image_folder, f)
for f in os.listdir(image_folder)
if f.split(".")[-1].lower() in allowed_extensions
]
# Create AWS SES client
try:
ses_client = boto3.client(
'ses',
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
region_name=aws_region,
)
except Exception as e:
print("Failed to create SES client:", str(e))
return
# Create MIME message
msg = MIMEMultipart()
msg['Subject'] = "All Images in Folder Attached"
msg['From'] = from_email
msg['To'] = ", ".join(to_email)
# HTML body
html_content = """
<p>Hi,</p>
<p>Please find all image attachments for IDX Weekly Highlights.</p>
<p>Thank you<br><br><br>
Best regards,<br>
Gerald</p>
"""
html_body = MIMEText(html_content, 'html')
msg.attach(html_body)
# Attach images
for path in image_files:
try:
with open(path, "rb") as f:
# Determine mime type from extension when possible
ext = os.path.splitext(path)[1].lstrip('.').lower()
if ext in ('jpg', 'jpeg', 'png', 'gif', 'webp'):
main_type = 'image'
sub_type = 'jpeg' if ext in ('jpg', 'jpeg') else ext
else:
main_type = 'application'
sub_type = 'octet-stream'
attachment = MIMEBase(main_type, sub_type)
attachment.set_payload(f.read())
encoders.encode_base64(attachment)
# Use parameterized add_header so filename is quoted/escaped correctly
attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path))
msg.attach(attachment)
except Exception as e:
print(f"Failed to attach file {path}:", str(e))
# Send email via AWS SES
try:
response = ses_client.send_raw_email(
Source=from_email,
Destinations=to_email,
RawMessage={'Data': msg.as_string()}
)
print("Email sent successfully. MessageId:", response['MessageId'])
except (BotoCoreError, ClientError) as e:
print("Failed to send email:", str(e))
except Exception as e:
print("Failed to send email:", str(e))
def send_email_batched(image_folder):
import shutil
import tempfile
from pathlib import Path
# SES raw email limit (bytes)
SES_RAW_LIMIT = 10 * 1024 * 1024 # 10MB
MIME_OVERHEAD = 200_000
ALLOWED_EXT = {"jpg", "jpeg", "png"}
def gather_image_files(folder_path):
# Collect all image files from folder
folder = Path(folder_path)
if not folder.exists():
print(f"Folder not found: {folder}")
return []
files = [p for p in sorted(folder.iterdir())
if p.is_file() and p.suffix.lstrip('.').lower() in ALLOWED_EXT]
return files
def make_batches(file_paths):
# Batch files so that after base64 encoding (+~33%) and MIME overhead
allowed_original = int((SES_RAW_LIMIT - MIME_OVERHEAD) * 3 / 4)
batches = []
current = []
current_sum = 0
for p in file_paths:
size = p.stat().st_size
if current_sum + size <= allowed_original:
current.append(p)
current_sum += size
else:
if current:
batches.append(current)
current = [p]
current_sum = size
if current:
batches.append(current)
return batches
def copy_batch_to_temp(batch):
tmpdir = tempfile.mkdtemp(prefix="email_batch_")
for p in batch:
shutil.copy2(p, tmpdir)
return tmpdir
# Gather all image files
files = gather_image_files(image_folder)
if not files:
print("No image files found in folder")
return
# Create batches
batches = make_batches(files)
if len(batches) == 1:
# No batching needed, send directly
print(f"Sending {len(files)} image(s) in single email")
send_email(image_folder)
else:
# Send in batches
print(f"Split into {len(batches)} batch(es) to respect SES size limits")
for i, batch in enumerate(batches, 1):
print(f"Sending batch {i}/{len(batches)} with {len(batch)} file(s)")
tmpdir = copy_batch_to_temp(batch)
try:
send_email(tmpdir)
finally:
try:
shutil.rmtree(tmpdir)
except Exception as e:
print(f"Failed to remove tempdir {tmpdir}: {e}")
def set_connection():
# Fetch variables
USER = os.getenv("user")
PASSWORD = os.getenv("password")
HOST = os.getenv("host")
PORT = os.getenv("port")
DBNAME = os.getenv("dbname")
# Connect to the database
try:
connection = psycopg2.connect(
user=USER,
password=PASSWORD,
host=HOST,
port=PORT,
dbname=DBNAME
)
print("Connection successful!")
# Create a cursor to execute SQL queries
cur = connection.cursor()
return cur
except Exception as e:
print(f"Failed to connect: {e}")
def fetch_query(query, cur):
cur.execute(query)
rows = cur.fetchall()
colnames = [desc[0] for desc in cur.description]
# Create DataFrame
df = pd.DataFrame(rows, columns=colnames)
return df
def ffill_data(df,column):
# Count how many NaNs are at the end
reversed_vals = df[column][::-1]
n_trailing_nans = reversed_vals.isna().cumprod().sum()
# Forward fill everything except trailing NaNs
if n_trailing_nans > 0:
filled_part = df[column][:-n_trailing_nans].ffill()
trailing_nans = pd.Series([np.nan] * n_trailing_nans, index=df.index[-n_trailing_nans:])
df[f"{column}_ffill"] = pd.concat([filled_part, trailing_nans])
else:
df[f"{column}_ffill"] = df[column].ffill()
return df
def draw_shrinking_text(pdf, text, max_width, x, y, font_name='Inter-Bold', initial_font_size=30, min_font_size=5, color=colors.white):
"""
Draws text at (x, y) with shrinking font size if max_width is exceeded.
Parameters:
- pdf: ReportLab canvas object
- text: The string to draw
- max_width: Maximum allowed width for the text
- x, y: Coordinates to draw the text
- font_name: Font to use (default: 'Inter-Bold')
- initial_font_size: Starting font size (default: 30)
- min_font_size: Minimum font size allowed (default: 5)
- color: Text color (default: white)
"""
font_size = initial_font_size
pdf.setFont(font_name, font_size)
text_width = pdf.stringWidth(text, font_name, font_size)
while text_width > max_width and font_size > min_font_size:
font_size -= 1
pdf.setFont(font_name, font_size)
text_width = pdf.stringWidth(text, font_name, font_size)
pdf.setFillColor(color)
pdf.drawString(x, y, text)
def week_date():
today = datetime.today()
# Find Monday of this week
start_of_week = today - timedelta(days=today.weekday())
# Generate Monday to Friday dates (as date objects)
weekdays = [(start_of_week + timedelta(days=i)).date() for i in range(5)]
# Create DataFrame
df = pd.DataFrame({"date": weekdays})
return df
def full_week(db_data):
df = week_date()
df['date'] = df['date'].astype("str")
db_data['date'] = db_data['date'].astype("str")
df = df.merge(db_data, on="date", how='left')
df['date'] = pd.to_datetime(df['date'])
df['pct_change'] = (df['market_cap'].pct_change() * 100)
df['pct_change'] = df['pct_change'].astype("float").round(2)
df = ffill_data(df,"market_cap")
return df
def date_generator(output):
dt_start = week_date().iloc[0]['date']
dt_end = week_date().iloc[-1]['date']
if output == "cover":
if dt_start.year == dt_end.year:
if dt_start.month == dt_end.month:
return f"{dt_start.day} - {dt_end.day} {dt_end.strftime('%b')} {dt_end.year}"
else:
return f"{dt_start.day} {dt_start.strftime('%b')} - {dt_end.day} {dt_end.strftime('%b')} {dt_end.year}"
else:
return f"{dt_start.day} {dt_start.strftime('%b')} {dt_start.year} - {dt_end.day} {dt_end.strftime('%b')} {dt_end.year}"
if output == "calendar":
if dt_start.year == dt_end.year:
if dt_start.month == dt_end.month:
return f"{dt_end.strftime('%B')} {dt_end.year}"
else:
return f"{dt_start.strftime('%B')} - {dt_end.strftime('%B')} {dt_end.year}"
else:
return f"{dt_start.strftime('%b')} {dt_start.year} - {dt_end.strftime('%B')} {dt_end.year}"
def custom_formatter(x, pos):
"""
Formatter for large numbers, adding suffixes like B (billion), M (million), T (trillion), etc.
"""
if x >= 1e12: # Trillions
return f'{x/1e12:.0f} T'
elif x >= 1e9: # Billions
return f'{x/1e9:.0f} B'
elif x >= 1e6: # Millions
return f'{x/1e6:.0f} M'
else:
return f'{x:.0f}'
# Plot
def mcap_chart(hist_mcap):
# Convert dates to numeric format
date_nums = mdates.date2num(hist_mcap['date'])
# Shift tick positions
tick_spacing = (date_nums[-1] - date_nums[0]) / (len(date_nums) - 1)
shift_factor = 0.05
shifted_start = date_nums[0] + tick_spacing * shift_factor
shifted_xs = [shifted_start + i * tick_spacing for i in range(len(date_nums))]
# Create plot
fig, ax = plt.subplots(figsize=(15, 5))
fig.patch.set_alpha(0)
ax.patch.set_alpha(0)
# Fonts
inter_regular = fm.FontProperties(fname='asset/font/Inter-Regular.ttf')
inter_semi_bold = fm.FontProperties(fname='asset/font/Inter-SemiBold.ttf')
min_mcap = float(hist_mcap["market_cap"].min())
max_mcap = float(hist_mcap["market_cap"].max())
# Plot shifted line
ax.plot(shifted_xs, hist_mcap["market_cap"],
linewidth=8, marker='o', markersize=22,
color="#F29942", markerfacecolor='#F29942', markeredgecolor='#F29942')
ax.plot(shifted_xs, hist_mcap["market_cap"],
linestyle=' ', marker='o', markersize=22,
markerfacecolor='#F29942', markeredgecolor='#F29942')
ax.plot(shifted_xs, hist_mcap["market_cap_ffill"],
linewidth=8,
color="#F29942",
linestyle='dashed')
# # Market cap label
# for x, y in zip(shifted_xs, hist_mcap["market_cap"]):
# if np.isnan(float(y)):
# ax.text(x, ((hist_mcap["market_cap"].max() + hist_mcap["market_cap"].min())/2), "Exchange\nHoliday",
# fontsize=20, fontproperties=inter_semi_bold,
# ha='center', va='bottom', color="white")
# else:
# ax.text(x, float(y) * 1.05, f"IDR {format_number_short_2d(y)}",
# fontsize=20, fontproperties=inter_semi_bold,
# ha='center', va='bottom', color="#F29942")
# prev_y = float(y)
# # Percent change label
# for x, y, z in zip(shifted_xs, hist_mcap["market_cap"], hist_mcap["pct_change"]):
# if not np.isnan(z):
# label = f"{z:.2f}%"
# bbox = dict(
# boxstyle="round, pad=0.5",
# facecolor='#568475' if z >= 0 else '#D53E50',
# edgecolor='none',
# alpha=1
# )
# ax.text(x, float(y) * 1.17, label,
# fontsize=20, fontproperties=inter_semi_bold,
# ha='center', va='bottom', color="white", bbox=bbox)
# Style ticks with spacing
ax.tick_params(axis='x', labelsize=28, colors="white", pad=20) # Add horizontal padding (below x-axis)
ax.tick_params(axis='y', labelsize=28, colors="white", pad=15) # Add vertical padding (left of y-axis)
# Apply font to tick labels
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontproperties(inter_regular)
label.set_fontsize(24)
# Custom x-ticks
ax.set_xticks(shifted_xs)
ax.set_xticklabels(hist_mcap['date'].dt.strftime('%d %B'))
# Fix xlim to respect shifted ticks
padding = tick_spacing * 0.5 # Optional padding on the right
ax.set_xlim(shifted_xs[0] - tick_spacing * 0.5, shifted_xs[-1] + padding)
# Custom y-axis formatting
ax.yaxis.set_major_formatter(ticker.FuncFormatter(custom_formatter))
# Grid and spines
ax.yaxis.grid(True, alpha=0.3)
for spine in ['top', 'right']:
ax.spines[spine].set_visible(False)
for spine in ['left', 'bottom']:
ax.spines[spine].set_color('white')
# Y-limits
ax.set_ylim((min_mcap*0.98), (max_mcap*1.02))
for i in range(0,4):
ax.axvline(shifted_start+0.5+i, color='white', linestyle='dashed', linewidth=1, alpha=0.3)
# Save and show
plt.tight_layout()
plt.savefig("asset/plot/my_plot.png", transparent=True, dpi=300)
return plt
def ca_compilation(df_div,df_ipo,stock_split):
df_week = week_date()
df_div_proc = pd.DataFrame(df_div.groupby('ex_date')['symbol'].count()).reset_index()
df_div_proc.columns = ['date','div']
df_ipo_proc = pd.DataFrame(df_ipo.groupby('offering_end_date')['symbol'].count()).reset_index()
df_ipo_proc.columns = ['date','ipo']
df_stock_split_proc = pd.DataFrame(stock_split.groupby('date')['symbol'].count()).reset_index()
df_stock_split_proc.columns = ['date','split']
for i in [df_ipo_proc, df_div_proc, df_stock_split_proc]:
df_week = df_week.merge(i, on='date', how="left")
df_week = df_week.fillna(0)
df_week['total'] = df_week['ipo'] + df_week['div'] + df_week['split']
df_week[df_week.select_dtypes(include='number').columns] = df_week.select_dtypes(include='number').fillna(0).astype(int)
return df_week
def hex_to_rgb(hex_color):
hex_color = hex_color.lstrip('#')
return tuple(int(hex_color[i:i+2], 16)/255 for i in (0, 2, 4))
def format_number_short_1d(num):
"""
Convert number to abbreviated format:
1,200,000 -> 1.2M
1,500,000,000 -> 1.5B
2,000,000,000,000 -> 2T
"""
num = float(num)
if abs(num) >= 1_000_000_000_000: # Trillion
return f"{num / 1_000_000_000_000:,.1f}T"
elif abs(num) >= 1_000_000_000: # Billion
return f"{num / 1_000_000_000:.1f}B"
elif abs(num) >= 1_000_000: # Million
return f"{num / 1_000_000:.1f}M"
else:
return f"{num:,.0f}"
def format_number_short_2d(num):
"""
Convert number to abbreviated format:
1,200,000 -> 1.2M
1,500,000,000 -> 1.5B
2,000,000,000,000 -> 2T
"""
num = float(num)
if abs(num) >= 1_000_000_000_000: # Trillion
return f"{num / 1_000_000_000_000:,.2f}T"
elif abs(num) >= 1_000_000_000: # Billion
return f"{num / 1_000_000_000:.2f}B"
elif abs(num) >= 1_000_000: # Million
return f"{num / 1_000_000:.2f}M"
else:
return f"{num:,.0f}"
def top_3comp_bysec_process(df):
TARGET = 3
# Count rows per sub_sector
counts = df['sub_sector'].value_counts()
# If all groups already have >= 3 rows → return unchanged
if (counts >= TARGET).all():
result = df.copy()
else:
result_rows = []
for sector, group in df.groupby('sub_sector', sort=False):
# Append original group rows in *existing order*
result_rows.append(group)
# How many missing rows?
missing = TARGET - len(group)
if missing > 0:
# Create missing rows for this sub_sector
padding = pd.DataFrame({
'symbol': [np.nan]*missing,
'sub_sector': [sector]*missing,
'close': [np.nan]*missing,
'mcap_change_value': [np.nan]*missing,
'pe_ttm': [np.nan]*missing,
'total_market_cap': [np.nan]*missing
})
# Append padding rows right after this group
result_rows.append(padding)
result = pd.concat(result_rows, ignore_index=True)
return result
def create_weekly_report(hist_mcap, mcap_changes,top_gainers_losers,indices_changes,sectors_changes,top_3_comp_sectors,top_volume,top_value,df_ipo,stock_split,df_div,ca_comp):
# Register Inter font
pdfmetrics.registerFont(TTFont('Inter', 'asset/font/Inter-Regular.ttf'))
pdfmetrics.registerFont(TTFont('Inter-Bold', 'asset/font/Inter-Bold.ttf'))
pdfmetrics.registerFont(TTFont('Inter-Semi-Bold', 'asset/font/Inter-SemiBold.ttf'))
# Setup Canvas
width, height = 1200, 1500
pdf = canvas.Canvas(f"pdf_output/idx_highlights - {date_generator('cover')}.pdf", pagesize=(width, height))
# Cover
num_week = round(datetime.today().day/7)
if num_week <= 4 and num_week>0:
pdf.drawImage(f'asset/page/cover-{num_week}.png', 0, 0, width, height)
elif num_week == 0:
pdf.drawImage('asset/page/cover-1.png', 0, 0, width, height)
else:
pdf.drawImage('asset/page/cover-1.png', 0, 0, width, height)
pdf.setFillColor(colors.white)
pdf.setFont("Inter", 45)
pdf.drawString(149, 765, date_generator("cover"))
plot = mcap_chart(hist_mcap)
# Page 1
pdf.showPage()
pdf.drawImage('asset/page/page_1.png', 0, 0, width, height)
# Chart
pdf.drawImage("asset/plot/my_plot.png", 98, 900, 962, 962/3, mask="auto")
# Weekly Performance
pdf.setFillColor(colors.black)
pdf.setFont("Inter-Bold", 28)
pdf.drawString(154, 772, "Weekly Performance")
mcap_change = float(mcap_changes.loc[0,"mcap_percentage_change"])
if mcap_change > 0:
r, g, b = hex_to_rgb("#568475") #green
pdf.setFillColorRGB(r, g, b)
pdf.drawString(670, 772, f'+{mcap_change}%')
if mcap_change < 0:
r, g, b = hex_to_rgb("#D53E50") #Orangey-red
pdf.setFillColorRGB(r, g, b)
pdf.drawString(670, 772, f'{mcap_change}%')
if mcap_change == 0:
pdf.setFillColor(colors.black)
pdf.drawString(670, 772, f'{mcap_change}%')
pdf.setFillColor(colors.black)
pdf.drawString(835, 772, f"IDR {format_number_short_2d(mcap_changes['mcap_start'])}")
# Top Gainers
for i in range(0,5):
image = ImageReader(BytesIO(requests.get(f"https://storage.googleapis.com/sectorsapp-sea/logo/{top_gainers_losers['symbol'][i][0:4]}.webp").content))
pdf.drawImage(image, 180, height - 990 - (88*i), 50, 50,mask="auto")
for i in range (0,5):
# Title
pdf.setFillColor(colors.black)
pdf.setFont("Inter-Bold", 32)
pdf.drawString(260, height - 980 - (88*i), top_gainers_losers["symbol"][i][0:4])
for i in range (0,5):
# Title
r, g, b = hex_to_rgb("#568475") #green
pdf.setFillColorRGB(r, g, b)
pdf.setFont("Inter-Bold", 28)
text = f"{top_gainers_losers['mcap_change_pct'][i]}%"
text_width = pdf.stringWidth(text, 'Inter-Bold', 28)
pdf.drawString(1200-text_width-600, height - 962 - (88*i), text)
for i in range (0,5):
# Title
pdf.setFillColor(colors.black)
pdf.setFont("Inter", 20)
text = f"IDR {format_number_short_1d(top_gainers_losers['mcap_end'][i])}"
text_width = pdf.stringWidth(text, 'Inter', 20)
pdf.drawString(1200-text_width-600, height - 990 - (88*i), text)
# Top Losers
for i in range(0,5):
image = ImageReader(BytesIO(requests.get(f"https://storage.googleapis.com/sectorsapp-sea/logo/{top_gainers_losers['symbol'][i+5][0:4]}.webp").content))
pdf.drawImage(image, 705, height - 990 - (88*i), 50, 50, mask="auto")
for i in range (0,5):
# Title
pdf.setFillColor(colors.white)
pdf.setFont("Inter-Bold", 32)
pdf.drawString(770, height - 980 - (88*i), top_gainers_losers["symbol"][i+5][0:4])
for i in range (0,5):
# Title
r, g, b = hex_to_rgb("#D53E50") #Orangey-red
pdf.setFillColorRGB(r, g, b)
pdf.setFont("Inter-Bold", 28)
text = f"{top_gainers_losers['mcap_change_pct'][i+5]}%"
text_width = pdf.stringWidth(text, 'Inter-Bold', 28)
pdf.drawString(1200-text_width-150, height - 962 - (88*i), text)
for i in range (0,5):
# Title
pdf.setFillColor(colors.white)
pdf.setFont("Inter", 20)
text = f"IDR {format_number_short_1d(top_gainers_losers['mcap_end'][i+5])}"
text_width = pdf.stringWidth(text, 'Inter', 20)
pdf.drawString(1200-text_width-150, height - 990 - (88*i), text)
# Page 2
pdf.showPage()
pdf.drawImage('asset/page/page_2.png', 0, 0, width, height)
# Indices Performance
for i in range(0, 3):
# Calculate column center first
center = 270 + (335 * i)
y_percentage = height - 345
y_price = height - 397
# Retrieve values
percentage = indices_changes.loc[i, 'price_change_pct']
price = f"IDR {indices_changes.loc[i, 'end_price']}"
# Format percentage text
percentage_text = f"+{percentage}%" if percentage > 0 else f"{percentage}%"
# Calculate width for centering
percentage_width = pdf.stringWidth(percentage_text, "Inter-Bold", 55)
price_width = pdf.stringWidth(price, "Inter", 36)
percentage_x = center - (percentage_width / 2)
price_x = center - (price_width / 2)
# Set color and draw percentage first
if percentage > 0:
r, g, b = hex_to_rgb("#568475") # green
pdf.setFillColorRGB(r, g, b)
elif percentage < 0:
r, g, b = hex_to_rgb("#D53E50") # orange-red
pdf.setFillColorRGB(r, g, b)
else:
pdf.setFillColor(colors.black)
pdf.setFont("Inter-Bold", 55)
pdf.drawString(percentage_x, y_percentage, percentage_text)
# Reset color for price
pdf.setFillColor(colors.black)
pdf.setFont("Inter", 36)
pdf.drawString(price_x, y_price, price)
# Top 3 Sectors
for i in range(0,3):
pdf.drawImage(f'asset/sectors/{sectors_changes.loc[i,"sector"]}.png', 139 + (i*330), 900, 45,45, mask="auto")
pdf.setFillColor(colors.white)
pdf.setFont("Inter-Bold", 24)
draw_shrinking_text(pdf, sectors_changes.loc[i,'sub_sector'], 206, 203 + (i*330), 925, font_name='Inter-Bold', initial_font_size=24, min_font_size=8, color=colors.white)
# pdf.drawString(203+ (i*330), 925, sectors_changes.loc[i,'sub_sector'])
pdf.setFont("Inter", 20)
pdf.drawString(203+ (i*330), 900, f"IDR {format_number_short_2d(sectors_changes.loc[i,'total_market_cap'])}")
for i in range(0,3):
#1w
pdf.setFont("Inter", 18)
pdf.setFillColor(colors.white)
onew_x = 155 + (i * 330)
onew_y = 850
pdf.drawString(onew_x, onew_y, "1 Week")
# Calculate the width of the YTD label
onew_width = pdf.stringWidth("1 Week", "Inter", 18)
# Center point for YTD
onew_center = 155 + (i * 330) + (onew_width / 2)
# now compute the width of the percentage text
percentage = sectors_changes.loc[i,'mcap_change_1w']
if percentage > 0:
r, g, b = hex_to_rgb("#ABDDA4") # green
pdf.setFillColorRGB(r, g, b)
text = f"+{percentage}%"
elif percentage < 0:
r, g, b = hex_to_rgb("#D53E50") # orange-red
pdf.setFillColorRGB(r, g, b)
text = f"{percentage}%"
else:
pdf.setFillColor(colors.white)
text = "0.00%"
# Measure text width for centering
text_width = pdf.stringWidth(text, "Inter-Bold", 18)
centered_x = onew_center - (text_width/2)
# Now draw the percentage text centered under YTD
percentage_y = 825
pdf.setFont("Inter-Bold", 18)
pdf.drawString(centered_x, percentage_y, text)
#ytd
pdf.setFont("Inter", 14)
pdf.setFillColor(colors.white)
ytd_x = 273 + (i * 330)
ytd_y = 850
pdf.drawString(ytd_x, ytd_y, "YTD")
# Calculate the width of the YTD label
ytd_width = pdf.stringWidth("YTD", "Inter", 14)
# Center point for YTD
ytd_center = 273 + (i * 330) + (ytd_width / 2)
# now compute the width of the percentage text
percentage = sectors_changes.loc[i,'mcap_change_ytd']
if percentage > 0:
r, g, b = hex_to_rgb("#ABDDA4") # green
pdf.setFillColorRGB(r, g, b)
text = f"+{percentage}%"
elif percentage < 0:
r, g, b = hex_to_rgb("#D53E50") # orange-red
pdf.setFillColorRGB(r, g, b)
text = f"{percentage}%"
else:
pdf.setFillColor(colors.white)
text = "0.00%"
# Measure text width for centering
text_width = pdf.stringWidth(text, "Inter-Bold", 14)
centered_x = ytd_center - (text_width/2)
# Now draw the percentage text centered under YTD
percentage_y = 830
pdf.setFont("Inter-Bold", 14)
pdf.drawString(centered_x, percentage_y, text)
#1y
pdf.setFont("Inter", 14)
pdf.setFillColor(colors.white)
oney_x = 345 + (i * 330)
oney_y = 850
pdf.drawString(oney_x, oney_y, "1 Year")
# Calculate the width of the YTD label
oney_width = pdf.stringWidth("1 Year", "Inter", 14)
# Center point for 1y
oney_center = 345 + (i * 330) + (oney_width / 2)
# now compute the width of the percentage text
percentage = sectors_changes.loc[i,'mcap_change_1y']
if percentage > 0:
r, g, b = hex_to_rgb("#ABDDA4") # green
pdf.setFillColorRGB(r, g, b)
text = f"+{percentage}%"
elif percentage < 0:
r, g, b = hex_to_rgb("#D53E50") # orange-red
pdf.setFillColorRGB(r, g, b)
text = f"{percentage}%"
else:
pdf.setFillColor(colors.white)
text = "0.00%"
# Measure text width for centering
text_width = pdf.stringWidth(text, "Inter-Bold", 14)
centered_x = oney_center - (text_width/2)
# Now draw the percentage text centered under YTD
percentage_y = 830
pdf.setFont("Inter-Bold", 14)
pdf.drawString(centered_x, percentage_y, text)
for j in range (0,3):
for i in range (0,3):
image = ImageReader(BytesIO(requests.get(f"https://storage.googleapis.com/sectorsapp-sea/logo/{top_3_comp_sectors.loc[i + (j*3),'symbol'][0:4]}.webp").content))
pdf.drawImage(image, 162 + (j*330), 756 - (i*75), 26,26, mask="auto")
pdf.setFont("Inter", 18)
pdf.setFillColor(colors.white)
pdf.drawString(154 + (j*330) ,734 - (i*75), top_3_comp_sectors.loc[i + (j*3),"symbol"][0:4])
center = 260 + (j * 330)
y_percentage = 764 - (i * 75)
y_idr = 734 - (i * 75)
# Retrieve values
percentage = top_3_comp_sectors.loc[i + (j*3), "mcap_change_value"]
# Set color for percentage first
if percentage > 0:
r, g, b = hex_to_rgb("#ABDDA4") # green
pdf.setFillColorRGB(r, g, b)
percentage_text = f'↑ IDR {format_number_short_1d(abs(percentage))}'
elif percentage < 0:
r, g, b = hex_to_rgb("#D53E50") # orange-red
pdf.setFillColorRGB(r, g, b)
percentage_text = f'↓ IDR {format_number_short_1d(abs(percentage))}'
else:
pdf.setFillColor(colors.white)
percentage_text = f'↑ IDR {format_number_short_1d(abs(percentage))}'
text = f"IDR {format_number_short_1d(top_3_comp_sectors.loc[i + (j*3), 'close'])}"
# Calculate width for centering
percentage_width = pdf.stringWidth(percentage_text, "Inter-Bold", 18)
text_width = pdf.stringWidth(text, "Inter", 16)
percentage_x = center - (percentage_width/2)
text_x = center - (text_width/2)
# Draw percentage
pdf.setFont("Inter-Bold", 18)
pdf.drawString(percentage_x, y_percentage, percentage_text)
# Reset color for the secondary text
pdf.setFillColor(colors.white)
pdf.setFont("Inter", 16)
pdf.drawString(text_x, y_idr, text)
# Inside your for loop:
center = 358 + (j * 330)
y_label = 760 - (i * 75)
y_number = 740 - (i * 75)
# Texts to draw
label = "P/E"
value = top_3_comp_sectors.loc[i + (j * 3), 'pe_ttm']
if pd.isna(value):
number = "-"
elif value > 100:
number = "> 100"
elif value < 0:
number = "< 0"
else:
number = f"{value}"
# Calculate their widths
label_width = pdf.stringWidth(label, "Inter", 18)
number_width = pdf.stringWidth(number, "Inter-Bold", 16)
# Center them
label_x = center - (label_width/2)
number_x = center - (number_width/2)
# Set color and font
pdf.setFillColor(colors.white)
pdf.setFont("Inter", 18)
# Draw
pdf.drawString(label_x, y_label, label)
pdf.setFillColor(colors.white)
pdf.setFont("Inter-Bold", 16)
pdf.drawString(number_x, y_number, number)
# Top volume Traded
image = ImageReader(BytesIO(requests.get(f"https://storage.googleapis.com/sectorsapp-sea/logo/{top_volume.loc[0,'symbol'][0:4]}.webp").content))
pdf.drawImage(image, 158, 429-110, 63,63, mask="auto")
pdf.setFont("Inter", 40)
pdf.setFillColor(colors.white)
pdf.drawString(244, 337, top_volume.loc[0,"symbol"][0:4])
pdf.setFont("Inter-Semi-Bold", 40)
pdf.drawString(430, 337, format_number_short_2d(top_volume.loc[0,"total_volume"]))
for i in range(0,4):
# Center base
center = 193 + (i * 105) # 193 = 168 + 25 (half logo width)
# Draw logo first, centered
image = ImageReader(BytesIO(requests.get(f"https://storage.googleapis.com/sectorsapp-sea/logo/{top_volume.loc[i+1,'symbol'][0:4]}.webp").content))
pdf.drawImage(image, center - 25, 240, 50, 50, mask='auto')
# Draw symbol, centered
symbol = top_volume.loc[i+1,"symbol"][0:4]
symbol_width = pdf.stringWidth(symbol, "Inter", 26)
symbol_x = center - (symbol_width/2)
symbol_y = 205
pdf.setFont("Inter", 26)
pdf.setFillColor(colors.white)
pdf.drawString(symbol_x, symbol_y, symbol)
# Now draw number, centered
number = format_number_short_2d(top_volume.loc[i+1,"total_volume"])
number_width = pdf.stringWidth(number, "Inter-Semi-Bold", 26)
number_x = center - (number_width/2)
number_y = 170
pdf.setFont("Inter-Semi-Bold", 26)
pdf.drawString(number_x, number_y, number)
# Top value Traded
image = ImageReader(BytesIO(requests.get(f"https://storage.googleapis.com/sectorsapp-sea/logo/{top_value.loc[0,'symbol'][0:4]}.webp").content))
pdf.drawImage(image, 658, 429-110, 63,63, mask="auto")
pdf.setFont("Inter", 40)
pdf.setFillColor(colors.white)
pdf.drawString(744, 337, top_value.loc[0,"symbol"][0:4])
pdf.setFont("Inter-Semi-Bold", 40)
pdf.drawString(930, 337, format_number_short_2d(top_value.loc[0,"total_value"]))
for i in range(0,4):
# Center base
center = 668 + (i * 105) + 25 # 668 + (i*105) is the left corner, 25 is half of logo width (50/2)
# Draw logo first, centered
image = ImageReader(BytesIO(requests.get(f"https://storage.googleapis.com/sectorsapp-sea/logo/{top_value.loc[i+1,'symbol'][0:4]}.webp").content))
pdf.drawImage(image, center - 25, 240, 50, 50, mask='auto')
# Draw symbol, centered
symbol = top_value.loc[i+1,"symbol"][0:4]
symbol_width = pdf.stringWidth(symbol, "Inter", 26)
symbol_x = center - (symbol_width/2)
symbol_y = 205
pdf.setFont("Inter", 26)
pdf.setFillColor(colors.white)
pdf.drawString(symbol_x, symbol_y, symbol)
# Now draw number, centered
number = format_number_short_2d(top_value.loc[i+1,"total_value"])
number_width = pdf.stringWidth(number, "Inter-Semi-Bold", 26)
number_x = center - (number_width/2)
number_y = 170
pdf.setFont("Inter-Semi-Bold", 26)
pdf.drawString(number_x, number_y, number)
# Page 3
pdf.showPage()
## Calendar
unfill_cal_box = "asset/calendar_asset/unfill_cal.png"
fill_cal_box = "asset/calendar_asset/fill_cal.png"
ipo_num = "asset/calendar_asset/ipo_cal.png"
div_num = "asset/calendar_asset/div_cal.png"
split_num = "asset/calendar_asset/split_cal.png"
pdf.drawImage('asset/page/page_3.png', 0, 0, width, height)
pdf.setFont("Inter-Bold", 36)
pdf.setFillColor(colors.white)
pdf.drawString(109, 1240, date_generator("calendar"))
for i in range (0,5):
if ca_comp.iloc[i]["total"] == 0: