processCASpdf 0.3.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
processCASpdf.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
"""
|
|
2
|
+
#
|
|
3
|
+
# This script is an extension of camspdf.py, originally written by Suhas Bharadwaj:
|
|
4
|
+
# https://github.com/srbharadwaj/CAMSPdfExtractor
|
|
5
|
+
#
|
|
6
|
+
# Modified to extract fund name and ISIN from CAS statements that span multiple lines.
|
|
7
|
+
#
|
|
8
|
+
# Version: 0.3.1
|
|
9
|
+
# Date: 2025-04-05
|
|
10
|
+
# Copyright (c) 2025, Neeraj <@ukkit>
|
|
11
|
+
#
|
|
12
|
+
# Licensed under the MIT License. See the LICENSE file in the project root
|
|
13
|
+
# for the full license text.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import csv
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
from dataclasses import asdict, dataclass
|
|
22
|
+
from datetime import datetime
|
|
23
|
+
|
|
24
|
+
import pandas as pd
|
|
25
|
+
import pdfplumber
|
|
26
|
+
import requests
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
# Defining RegEx patterns
|
|
31
|
+
REGULAR_BUY_TXN = r"(?P<date>\d+\-\S+\-\d+)\s+(?P<txn>.*)\s+(?P<amount>[0-9]+\.[0-9]*)\s+(?P<units>[0-9]+\.[0-9]*)\s+(?P<nav>[0-9]+\.[0-9]*)\s+(?P<unitbalance>[0-9]+\.[0-9]*).*"
|
|
32
|
+
REGULAR_SELL_TXN = r"(?P<date>\d+\-\S+\-\d+)\s+(?P<txn>.*)\s+(?P<amount>\([0-9]+\.[0-9]*\))\s+(?P<units>\([0-9]+\.[0-9]*\))\s+(?P<nav>[0-9]+\.[0-9]*)\s+(?P<unitbalance>[0-9]+\.[0-9]*).*"
|
|
33
|
+
SEGR_BUY_TXN = r"(?P<date>\d+\-\S+\-\d+)\s+(?P<txn>.*)\s+(?P<units>[0-9]+\.[0-9]*)\s+(?P<unitbalance>[0-9]+\.[0-9]*).*"
|
|
34
|
+
FOLIO_PAN = r"^Folio No:\s+(?P<folio_num>.*)\s+PAN:\s+(?P<pan>[A-Z,0-9]{10})"
|
|
35
|
+
|
|
36
|
+
# Fund name indicator patterns used to identify lines containing mutual fund names
|
|
37
|
+
_FUND_NAME_PATTERNS = (
|
|
38
|
+
"PAMP-",
|
|
39
|
+
"-Growth",
|
|
40
|
+
"-Direct",
|
|
41
|
+
"-Regular",
|
|
42
|
+
"-Plan",
|
|
43
|
+
"-Fund",
|
|
44
|
+
"-HDFC",
|
|
45
|
+
"-ICICI",
|
|
46
|
+
"-SBI",
|
|
47
|
+
"-Axis",
|
|
48
|
+
"-Kotak",
|
|
49
|
+
"-Nippon",
|
|
50
|
+
"-Tata",
|
|
51
|
+
"-UTI",
|
|
52
|
+
"-Aditya",
|
|
53
|
+
"-Mirae",
|
|
54
|
+
"-Parag",
|
|
55
|
+
"-Edelweiss",
|
|
56
|
+
"-DSP",
|
|
57
|
+
"-Invesco",
|
|
58
|
+
"-PGIM",
|
|
59
|
+
"-HSBC",
|
|
60
|
+
"-BNP",
|
|
61
|
+
"-Franklin",
|
|
62
|
+
"-IDFC",
|
|
63
|
+
"-Reliance",
|
|
64
|
+
"-L&T",
|
|
65
|
+
"-Mahindra",
|
|
66
|
+
"-Canara",
|
|
67
|
+
"-Indiabulls",
|
|
68
|
+
"-Motilal",
|
|
69
|
+
"-Quantum",
|
|
70
|
+
"-Sundaram",
|
|
71
|
+
"-Taurus",
|
|
72
|
+
"-JM",
|
|
73
|
+
"-Principal",
|
|
74
|
+
"-Baroda",
|
|
75
|
+
"-LIC",
|
|
76
|
+
"-BOI",
|
|
77
|
+
"-Union",
|
|
78
|
+
"-IDBI",
|
|
79
|
+
"-IIFL",
|
|
80
|
+
"-PPFAS",
|
|
81
|
+
"-WhiteOak",
|
|
82
|
+
"-Samco",
|
|
83
|
+
"-Groww",
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
_REGISTRAR_SUFFIXES = ("Registrar : CAMS", "Registrar : KFintech", "Registrar : Karvy")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _strip_registrar(name: str) -> str:
|
|
91
|
+
for suffix in _REGISTRAR_SUFFIXES:
|
|
92
|
+
name = name.replace(suffix, "")
|
|
93
|
+
return name.strip()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _has_fund_name_pattern(line):
|
|
97
|
+
"""Check if a line contains a known mutual fund name indicator pattern."""
|
|
98
|
+
return any(pattern in line for pattern in _FUND_NAME_PATTERNS)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _clean_fund_name(raw_name):
|
|
102
|
+
"""Extract and clean fund name from raw text.
|
|
103
|
+
|
|
104
|
+
Splits on the first hyphen and takes the right side,
|
|
105
|
+
strips trailing hyphens/spaces, and removes registrar suffixes.
|
|
106
|
+
"""
|
|
107
|
+
name = raw_name.strip()
|
|
108
|
+
if "-" in name:
|
|
109
|
+
name = name.split("-", 1)[1].strip()
|
|
110
|
+
name = name.rstrip("- ").strip()
|
|
111
|
+
return _strip_registrar(name)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _clean_fund_name_smart(raw_name):
|
|
115
|
+
"""Extract fund name using last-hyphen strategy with fallback.
|
|
116
|
+
|
|
117
|
+
Tries splitting on the last hyphen first. If the result is too short
|
|
118
|
+
or starts with '(', falls back to splitting on the first hyphen.
|
|
119
|
+
"""
|
|
120
|
+
name = raw_name.strip()
|
|
121
|
+
if "-" in name:
|
|
122
|
+
last_part = name.split("-")[-1].strip()
|
|
123
|
+
if len(last_part) < 5 or last_part.startswith("("):
|
|
124
|
+
parts = name.split("-", 1)
|
|
125
|
+
name = parts[1].strip() if len(parts) > 1 else last_part
|
|
126
|
+
else:
|
|
127
|
+
name = last_part
|
|
128
|
+
return _strip_registrar(name)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _extract_isin(text):
|
|
132
|
+
"""Extract an ISIN (INF + 9 alphanumeric chars) from text. Returns match or empty string."""
|
|
133
|
+
match = re.search(r"INF[A-Z0-9]{9}", text)
|
|
134
|
+
return match.group(0) if match else ""
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass
|
|
138
|
+
class _EachLine:
|
|
139
|
+
scheme_code: str
|
|
140
|
+
isin_growth: str
|
|
141
|
+
isin_div_reinv: str
|
|
142
|
+
scheme_name: str
|
|
143
|
+
nav: str
|
|
144
|
+
date: str
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class _LatestNav:
|
|
148
|
+
def __init__(self) -> None:
|
|
149
|
+
self.alldata: list[_EachLine] = []
|
|
150
|
+
url = "https://portal.amfiindia.com/spages/NAVopen.txt"
|
|
151
|
+
response = requests.get(url, timeout=60)
|
|
152
|
+
if response.status_code == 200:
|
|
153
|
+
html_content = response.text
|
|
154
|
+
alllines = html_content.splitlines()
|
|
155
|
+
self.process(alllines)
|
|
156
|
+
else:
|
|
157
|
+
logger.warning("Failed to retrieve the latest nav page. Status code: %s", response.status_code)
|
|
158
|
+
|
|
159
|
+
def process(self, alllines):
|
|
160
|
+
for eachline in alllines:
|
|
161
|
+
if ";" in eachline and "Scheme Code" not in eachline:
|
|
162
|
+
alltokens = eachline.split(";")
|
|
163
|
+
a = _EachLine(
|
|
164
|
+
scheme_code=alltokens[0],
|
|
165
|
+
isin_growth=alltokens[1],
|
|
166
|
+
isin_div_reinv=alltokens[2],
|
|
167
|
+
scheme_name=alltokens[3],
|
|
168
|
+
nav=alltokens[4],
|
|
169
|
+
date=alltokens[5],
|
|
170
|
+
)
|
|
171
|
+
self.alldata.append(a)
|
|
172
|
+
|
|
173
|
+
def get_sch_code(self, isin):
|
|
174
|
+
for a in self.alldata:
|
|
175
|
+
if a.isin_growth == isin or a.isin_div_reinv == isin:
|
|
176
|
+
return a.scheme_code
|
|
177
|
+
return ""
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@dataclass
|
|
181
|
+
class _FundDetails:
|
|
182
|
+
fund_name: str
|
|
183
|
+
isin: str
|
|
184
|
+
scheme_code: str
|
|
185
|
+
folio_num: str
|
|
186
|
+
date: str
|
|
187
|
+
txn: str
|
|
188
|
+
amount: float
|
|
189
|
+
units: float
|
|
190
|
+
nav: float
|
|
191
|
+
balance_units: float
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class _ProcessTextFile:
|
|
195
|
+
def __init__(self, alllines: list[str]) -> None:
|
|
196
|
+
self.alldata: list[_FundDetails] = []
|
|
197
|
+
self.lnav = _LatestNav()
|
|
198
|
+
self.alllines = alllines
|
|
199
|
+
self.process()
|
|
200
|
+
|
|
201
|
+
def extract_fund_and_isin(self, lines, start_idx):
|
|
202
|
+
"""Extract fund name and ISIN from potentially multi-line text"""
|
|
203
|
+
fund_name = ""
|
|
204
|
+
isin = ""
|
|
205
|
+
|
|
206
|
+
current_line = lines[start_idx].strip()
|
|
207
|
+
logger.debug("Checking line for ISIN: %s", current_line)
|
|
208
|
+
|
|
209
|
+
# Check if the current line ends with a hyphen, indicating ISIN might be on the next line
|
|
210
|
+
if current_line.endswith("-") and start_idx + 1 < len(lines):
|
|
211
|
+
next_line = lines[start_idx + 1].strip()
|
|
212
|
+
logger.debug("Line ends with hyphen, checking next line: %s", next_line)
|
|
213
|
+
|
|
214
|
+
if next_line.startswith("ISIN:"):
|
|
215
|
+
potential_fund_name = current_line.rstrip("-").strip()
|
|
216
|
+
fund_name = _clean_fund_name(potential_fund_name)
|
|
217
|
+
logger.debug("Extracted fund_name from hyphen-ended line: %s", fund_name)
|
|
218
|
+
|
|
219
|
+
isin_part = next_line.replace("ISIN:", "").strip()
|
|
220
|
+
isin = _extract_isin(isin_part)
|
|
221
|
+
if isin:
|
|
222
|
+
return fund_name, isin, start_idx + 1
|
|
223
|
+
|
|
224
|
+
# Try to find ISIN in the current line
|
|
225
|
+
if "ISIN:" in current_line:
|
|
226
|
+
parts = current_line.split("ISIN:")
|
|
227
|
+
if len(parts) > 1:
|
|
228
|
+
fund_name = _clean_fund_name(parts[0])
|
|
229
|
+
logger.debug("Extracted fund_name: %s", fund_name)
|
|
230
|
+
|
|
231
|
+
# Look for ISIN in the same line
|
|
232
|
+
isin_part = parts[1].strip()
|
|
233
|
+
isin = _extract_isin(isin_part)
|
|
234
|
+
if isin:
|
|
235
|
+
return fund_name, isin, start_idx
|
|
236
|
+
|
|
237
|
+
# Check if ISIN is split across lines
|
|
238
|
+
if (isin_part.endswith("INF") or "INF" in isin_part) and start_idx + 1 < len(lines):
|
|
239
|
+
next_line = lines[start_idx + 1].strip()
|
|
240
|
+
logger.debug("Found 'INF' in current line, checking next line: %s", next_line)
|
|
241
|
+
|
|
242
|
+
isin_rest_match = re.search(r"([A-Z0-9]{9})", next_line)
|
|
243
|
+
if isin_rest_match:
|
|
244
|
+
isin = f"INF{isin_rest_match.group(1)}"
|
|
245
|
+
logger.debug("Found split ISIN: %s", isin)
|
|
246
|
+
return fund_name, isin, start_idx + 1
|
|
247
|
+
|
|
248
|
+
# If ISIN not found in current line, check next line
|
|
249
|
+
if start_idx + 1 < len(lines):
|
|
250
|
+
next_line = lines[start_idx + 1].strip()
|
|
251
|
+
logger.debug("Checking next line for ISIN: %s", next_line)
|
|
252
|
+
|
|
253
|
+
if "ISIN:" in next_line:
|
|
254
|
+
if _has_fund_name_pattern(current_line):
|
|
255
|
+
fund_name = _clean_fund_name(current_line)
|
|
256
|
+
logger.debug("Extracted fund_name from current line (ISIN on next line): %s", fund_name)
|
|
257
|
+
|
|
258
|
+
isin_part = next_line.replace("ISIN:", "").strip()
|
|
259
|
+
isin = _extract_isin(isin_part)
|
|
260
|
+
if isin:
|
|
261
|
+
return fund_name, isin, start_idx + 1
|
|
262
|
+
elif (
|
|
263
|
+
next_line.startswith("(Non-Demat)")
|
|
264
|
+
or next_line.startswith("(Demat)")
|
|
265
|
+
or next_line.startswith("(Physical)")
|
|
266
|
+
):
|
|
267
|
+
fund_name = _clean_fund_name(current_line)
|
|
268
|
+
logger.debug("Extracted fund_name from current line (Non-Demat on next line): %s", fund_name)
|
|
269
|
+
|
|
270
|
+
isin_part = next_line.replace("ISIN:", "").strip()
|
|
271
|
+
isin = _extract_isin(isin_part)
|
|
272
|
+
if isin:
|
|
273
|
+
return fund_name, isin, start_idx + 1
|
|
274
|
+
else:
|
|
275
|
+
# Try to extract from the next line
|
|
276
|
+
isin_parts = next_line.split("ISIN:")
|
|
277
|
+
if len(isin_parts) > 1:
|
|
278
|
+
fund_name = _clean_fund_name(isin_parts[0])
|
|
279
|
+
logger.debug("Extracted fund_name from next line: %s", fund_name)
|
|
280
|
+
|
|
281
|
+
isin = _extract_isin(isin_parts[1])
|
|
282
|
+
if isin:
|
|
283
|
+
return fund_name, isin, start_idx + 1
|
|
284
|
+
|
|
285
|
+
# Check if the next line contains the rest of a split ISIN
|
|
286
|
+
isin_rest_match = re.search(r"([A-Z0-9]{9})", next_line)
|
|
287
|
+
if isin_rest_match and "INF" in current_line:
|
|
288
|
+
isin = f"INF{isin_rest_match.group(1)}"
|
|
289
|
+
logger.debug("Found split ISIN across lines: %s", isin)
|
|
290
|
+
return fund_name, isin, start_idx + 1
|
|
291
|
+
|
|
292
|
+
# Aggressive approach: look ahead up to 3 lines for any ISIN
|
|
293
|
+
for i in range(start_idx, min(start_idx + 3, len(lines))):
|
|
294
|
+
line = lines[i].strip()
|
|
295
|
+
if "ISIN:" in line:
|
|
296
|
+
isin_parts = line.split("ISIN:")
|
|
297
|
+
if len(isin_parts) > 1:
|
|
298
|
+
fund_name = _clean_fund_name(isin_parts[0])
|
|
299
|
+
logger.debug("Extracted fund_name from aggressive search: %s", fund_name)
|
|
300
|
+
|
|
301
|
+
isin = _extract_isin(isin_parts[1])
|
|
302
|
+
if isin:
|
|
303
|
+
return fund_name, isin, i
|
|
304
|
+
|
|
305
|
+
return fund_name, isin, start_idx
|
|
306
|
+
|
|
307
|
+
def write_to_csv(self, csv_file_name=None):
|
|
308
|
+
if csv_file_name is None:
|
|
309
|
+
csv_file_name = f"CAS_data_{datetime.now().strftime('%d_%m_%Y_%H_%M')}.csv"
|
|
310
|
+
fieldnames = [field.name for field in _FundDetails.__dataclass_fields__.values()]
|
|
311
|
+
|
|
312
|
+
with open(csv_file_name, mode="w", newline="") as csv_file:
|
|
313
|
+
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
|
|
314
|
+
writer.writeheader()
|
|
315
|
+
for item in self.alldata:
|
|
316
|
+
writer.writerow(asdict(item))
|
|
317
|
+
|
|
318
|
+
logger.info('CSV file "%s" created successfully.', csv_file_name)
|
|
319
|
+
|
|
320
|
+
def process(self):
|
|
321
|
+
if not self.alllines:
|
|
322
|
+
return
|
|
323
|
+
folio_num = ""
|
|
324
|
+
fund_name = ""
|
|
325
|
+
isin = ""
|
|
326
|
+
|
|
327
|
+
logger.debug("First 20 lines of the PDF text:")
|
|
328
|
+
for idx, line in enumerate(self.alllines[:20]):
|
|
329
|
+
logger.debug("Line %d: %s", idx, line.strip())
|
|
330
|
+
|
|
331
|
+
i = 0
|
|
332
|
+
while i < len(self.alllines):
|
|
333
|
+
eachline = self.alllines[i]
|
|
334
|
+
|
|
335
|
+
m = re.match(FOLIO_PAN, eachline)
|
|
336
|
+
if m:
|
|
337
|
+
folio_num = m.groupdict().get("folio_num", "")
|
|
338
|
+
logger.debug("Found folio_num: %s", folio_num)
|
|
339
|
+
i += 1
|
|
340
|
+
continue
|
|
341
|
+
|
|
342
|
+
if "ISIN:" in eachline or (i + 1 < len(self.alllines) and "ISIN:" in self.alllines[i + 1]):
|
|
343
|
+
logger.debug("Attempting fund/ISIN extraction starting at line %d", i)
|
|
344
|
+
extracted_fund_name, extracted_isin, new_idx = self.extract_fund_and_isin(self.alllines, i)
|
|
345
|
+
if extracted_fund_name and extracted_isin:
|
|
346
|
+
fund_name = extracted_fund_name
|
|
347
|
+
isin = extracted_isin
|
|
348
|
+
logger.debug("Found fund_name: %s", fund_name)
|
|
349
|
+
logger.debug("Found isin: %s", isin)
|
|
350
|
+
i = new_idx + 1
|
|
351
|
+
continue
|
|
352
|
+
|
|
353
|
+
# Process transaction lines
|
|
354
|
+
m = re.match(REGULAR_BUY_TXN, eachline)
|
|
355
|
+
if m:
|
|
356
|
+
date = m.groupdict().get("date", "")
|
|
357
|
+
txn = "Buy"
|
|
358
|
+
amount = float(m.groupdict().get("amount", 0))
|
|
359
|
+
units = float(m.groupdict().get("units", 0))
|
|
360
|
+
nav = float(m.groupdict().get("nav", 0))
|
|
361
|
+
balance_units = float(m.groupdict().get("unitbalance", 0))
|
|
362
|
+
|
|
363
|
+
t = _FundDetails(
|
|
364
|
+
folio_num=folio_num,
|
|
365
|
+
fund_name=fund_name,
|
|
366
|
+
isin=isin,
|
|
367
|
+
scheme_code=self.lnav.get_sch_code(isin),
|
|
368
|
+
date=date,
|
|
369
|
+
txn=txn,
|
|
370
|
+
amount=amount,
|
|
371
|
+
units=units,
|
|
372
|
+
nav=nav,
|
|
373
|
+
balance_units=balance_units,
|
|
374
|
+
)
|
|
375
|
+
self.alldata.append(t)
|
|
376
|
+
i += 1
|
|
377
|
+
continue
|
|
378
|
+
|
|
379
|
+
m = re.match(REGULAR_SELL_TXN, eachline)
|
|
380
|
+
if m:
|
|
381
|
+
date = m.groupdict().get("date", "")
|
|
382
|
+
txn = "Sell"
|
|
383
|
+
amount_str = m.groupdict().get("amount", "0")
|
|
384
|
+
amount = float(re.sub(r"\(|\)", "", amount_str))
|
|
385
|
+
units_str = m.groupdict().get("units", "0")
|
|
386
|
+
units = float(re.sub(r"\(|\)", "", units_str))
|
|
387
|
+
nav = float(m.groupdict().get("nav", 0))
|
|
388
|
+
balance_units = float(m.groupdict().get("unitbalance", 0))
|
|
389
|
+
|
|
390
|
+
t = _FundDetails(
|
|
391
|
+
folio_num=folio_num,
|
|
392
|
+
fund_name=fund_name,
|
|
393
|
+
isin=isin,
|
|
394
|
+
scheme_code=self.lnav.get_sch_code(isin),
|
|
395
|
+
date=date,
|
|
396
|
+
txn=txn,
|
|
397
|
+
amount=amount,
|
|
398
|
+
units=units,
|
|
399
|
+
nav=nav,
|
|
400
|
+
balance_units=balance_units,
|
|
401
|
+
)
|
|
402
|
+
self.alldata.append(t)
|
|
403
|
+
i += 1
|
|
404
|
+
continue
|
|
405
|
+
|
|
406
|
+
m = re.match(SEGR_BUY_TXN, eachline)
|
|
407
|
+
if m:
|
|
408
|
+
date = m.groupdict().get("date", "")
|
|
409
|
+
txn = "Buy"
|
|
410
|
+
amount = 0.0
|
|
411
|
+
units = float(m.groupdict().get("units", 0))
|
|
412
|
+
nav = 0.0
|
|
413
|
+
balance_units = float(m.groupdict().get("unitbalance", 0))
|
|
414
|
+
|
|
415
|
+
t = _FundDetails(
|
|
416
|
+
folio_num=folio_num,
|
|
417
|
+
fund_name=fund_name,
|
|
418
|
+
isin=isin,
|
|
419
|
+
scheme_code=self.lnav.get_sch_code(isin),
|
|
420
|
+
date=date,
|
|
421
|
+
txn=txn,
|
|
422
|
+
amount=amount,
|
|
423
|
+
units=units,
|
|
424
|
+
nav=nav,
|
|
425
|
+
balance_units=balance_units,
|
|
426
|
+
)
|
|
427
|
+
self.alldata.append(t)
|
|
428
|
+
i += 1
|
|
429
|
+
continue
|
|
430
|
+
|
|
431
|
+
# If we get here, we didn't match any pattern
|
|
432
|
+
i += 1
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
class ProcessPDF:
|
|
436
|
+
def __init__(self, filename, password=None) -> None:
|
|
437
|
+
if not filename:
|
|
438
|
+
raise ValueError("filename cannot be empty")
|
|
439
|
+
if not os.path.isfile(filename):
|
|
440
|
+
raise FileNotFoundError(f"PDF file not found: {filename}")
|
|
441
|
+
self.filename = filename
|
|
442
|
+
self.password = password
|
|
443
|
+
self.alldata: list[_FundDetails] = []
|
|
444
|
+
|
|
445
|
+
def get_pdf_data(self, output_format="csv"):
|
|
446
|
+
format_specifiers = ["dicts", "csv", "json", "df"]
|
|
447
|
+
if output_format not in format_specifiers:
|
|
448
|
+
raise ValueError(f"Output format must be one of {', '.join(format_specifiers)}")
|
|
449
|
+
|
|
450
|
+
file_path = self.filename
|
|
451
|
+
doc_pwd = self.password
|
|
452
|
+
final_text = ""
|
|
453
|
+
logger.info("Processing PDF. Please wait...")
|
|
454
|
+
with pdfplumber.open(file_path, password=doc_pwd) as pdf:
|
|
455
|
+
for page in pdf.pages:
|
|
456
|
+
txt = page.extract_text()
|
|
457
|
+
if txt:
|
|
458
|
+
final_text = final_text + "\n" + txt
|
|
459
|
+
|
|
460
|
+
# Replace all occurrences of ',' with an empty string
|
|
461
|
+
final_text = final_text.replace(",", "")
|
|
462
|
+
pt = _ProcessTextFile(alllines=final_text.splitlines())
|
|
463
|
+
|
|
464
|
+
if output_format == "csv":
|
|
465
|
+
pt.write_to_csv()
|
|
466
|
+
return None
|
|
467
|
+
item_dicts = [asdict(item) for item in pt.alldata]
|
|
468
|
+
if output_format == "df":
|
|
469
|
+
return pd.DataFrame(item_dicts)
|
|
470
|
+
elif output_format == "json":
|
|
471
|
+
return json.dumps(item_dicts)
|
|
472
|
+
else:
|
|
473
|
+
return item_dicts
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: processCASpdf
|
|
3
|
+
Version: 0.3.1
|
|
4
|
+
Summary: Extract data from CAMS Mutual Fund PDF statements
|
|
5
|
+
Project-URL: Homepage, https://github.com/ukkit/processCASpdf
|
|
6
|
+
Project-URL: Repository, https://github.com/ukkit/processCASpdf
|
|
7
|
+
Project-URL: Issues, https://github.com/ukkit/processCASpdf/issues
|
|
8
|
+
Author-email: Neeraj Tikku <neeraj.tikku@gmail.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Requires-Dist: pandas>=1.3.0
|
|
22
|
+
Requires-Dist: pdfplumber>=0.7.0
|
|
23
|
+
Requires-Dist: requests>=2.25.0
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# Mutual Fund CAS PDF Statement Parser
|
|
27
|
+
|
|
28
|
+
A Python tool/library that extracts data from Consolidated Account Statement (CAS) PDFs (https://github.com/ukkit/processCASpdf) — tested with KFintech — into CSV, DataFrame, JSON, or a list of dictionaries.
|
|
29
|
+
|
|
30
|
+
## Requirements
|
|
31
|
+
|
|
32
|
+
- Python >= 3.9
|
|
33
|
+
- [uv](https://github.com/astral-sh/uv) package manager
|
|
34
|
+
- Internet connection (fetches AMFI scheme data on each run)
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
git clone https://github.com/ukkit/processCASpdf.git
|
|
40
|
+
cd processCASpdf
|
|
41
|
+
curl -LsSf https://astral.sh/uv/install.sh | sh
|
|
42
|
+
uv sync
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Usage
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from processCASpdf import ProcessPDF
|
|
49
|
+
|
|
50
|
+
pdf = ProcessPDF("CAS_statement.pdf", password="your_pdf_password")
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
- `filename` (required) - Path to the CAS PDF file.
|
|
54
|
+
- `password` (optional) - PDF password (usually your PAN in uppercase).
|
|
55
|
+
|
|
56
|
+
### Output Formats
|
|
57
|
+
|
|
58
|
+
Call `get_pdf_data(format)` with one of: `"csv"` (default), `"df"`, `"json"`, `"dicts"`.
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
pdf.get_pdf_data("csv") # writes CAS_data_<timestamp>.csv to current directory
|
|
62
|
+
df = pdf.get_pdf_data("df") # returns pandas DataFrame
|
|
63
|
+
js = pdf.get_pdf_data("json") # returns JSON string
|
|
64
|
+
rec = pdf.get_pdf_data("dicts") # returns list of dicts
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Output Fields
|
|
68
|
+
|
|
69
|
+
| Field | Type | Description |
|
|
70
|
+
|---|---|---|
|
|
71
|
+
| `fund_name` | str | Mutual fund scheme name |
|
|
72
|
+
| `isin` | str | ISIN code (e.g. `INF...`) |
|
|
73
|
+
| `scheme_code` | str | AMFI scheme code; empty if lookup fails |
|
|
74
|
+
| `folio_num` | str | Folio number |
|
|
75
|
+
| `date` | str | Transaction date (e.g. `01-Jan-2025`) |
|
|
76
|
+
| `txn` | str | `Buy` or `Sell` |
|
|
77
|
+
| `amount` | float | Transaction amount (INR) |
|
|
78
|
+
| `units` | float | Units transacted |
|
|
79
|
+
| `nav` | float | NAV at time of transaction |
|
|
80
|
+
| `balance_units` | float | Unit balance after transaction |
|
|
81
|
+
|
|
82
|
+
### Example
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
import logging
|
|
86
|
+
from processCASpdf import ProcessPDF
|
|
87
|
+
|
|
88
|
+
logging.basicConfig(level=logging.DEBUG) # optional
|
|
89
|
+
|
|
90
|
+
pdf = ProcessPDF("MyCAS.pdf", password="ABCDE1234F")
|
|
91
|
+
df = pdf.get_pdf_data("df")
|
|
92
|
+
|
|
93
|
+
df[df["fund_name"].str.contains("HDFC", case=False)]
|
|
94
|
+
df.to_excel("cas_transactions.xlsx", index=False)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Troubleshooting
|
|
98
|
+
|
|
99
|
+
| Problem | Likely cause / fix |
|
|
100
|
+
|---|---|
|
|
101
|
+
| `PDFPasswordIncorrect` | Wrong or missing password. Try your PAN in uppercase. |
|
|
102
|
+
| No transactions extracted | Enable debug logging to inspect raw PDF text. |
|
|
103
|
+
| `scheme_code` is empty | ISIN not found in current AMFI data (new or discontinued scheme). |
|
|
104
|
+
| Network error on startup | AMFI data fetch requires outbound HTTPS. |
|
|
105
|
+
|
|
106
|
+
## Development
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
uv sync --group dev
|
|
110
|
+
uv run ruff check .
|
|
111
|
+
uv run ruff format .
|
|
112
|
+
uv run mypy processCASpdf.py
|
|
113
|
+
uv run pre-commit install
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Credits
|
|
117
|
+
|
|
118
|
+
Based on [`camspdf.py`](https://github.com/srbharadwaj/CAMSPdfExtractor) originally written by Suhas Bharadwaj.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
processCASpdf.py,sha256=j-Uy9UevxBLG7lWpfxvlwtbi6LrPTBqAj92NLnrGinY,16787
|
|
2
|
+
processcaspdf-0.3.1.dist-info/METADATA,sha256=Zd7md8YMBI56mUyvlSrUjiLCtjoW3S0A-qxcxZfGTqE,3755
|
|
3
|
+
processcaspdf-0.3.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
4
|
+
processcaspdf-0.3.1.dist-info/licenses/LICENSE,sha256=aGqvHifb49OHzcVL0wAGuviSA3BqnyuEYBQS-YO3ICs,1069
|
|
5
|
+
processcaspdf-0.3.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Neeraj Tikku
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|