↓Skip to main content

Data Munging With Guile

·6 mins

I’ve been on holiday for the last couple of weeks and took advantage of one of the rainy days to complete my tax return. I track my income and expenditure in GnuCash which I then use to generate an income and expenditure report for the accounts relevant to my tax return. This means I need to keep GnuCash up to date with my bank accounts, and I was a few months behind with the data entry.

Last year I spent a lot of time downloading statements in PDF format and using Tabula to extract the relevant data which I could then import into GnuCash. I was describing this process to one of my colleagues who made me feel quite silly by pointing out that Nationwide also provides a CSV export for your statements…

Unfortunately these files cannot be imported directly into GnuCash because they have some unwanted header lines, use an unsupported date format, and prefix the currency amounts with a non-ASCII character (code 243), so a little bit of data munging is needed. This could probably be done with a Perl one-liner, but as a learning experience I decided to tackle the problem with Guile.

Working with CSV files #

There’s a great module for working with delimiter-separated values in Guile, guile-dsv. With this in hand, reading and writing CSV files is straightforward:

(use-modules (dsv))

;; Read a CSV from the given path.
(define (read-statement path)
  (call-with-input-file path
    (lambda (port)
      (dsv->scm port #:format 'rfc4180))))

;; Write data to the given path in CSV format.
(define (write-statement data path)
  (call-with-output-file path
    (lambda (port)
      (scm->dsv data port #:format 'rfc4180))))

Parsing and Formatting Dates #

The dates in the downloaded CSV are of the form “10 Jan 2024”, which we want to convert to a format understood by GnuCash. I chose to use ISO8601 format, “2024-01-10”. Guile uses C’s strftime for parsing and formatting dates, so we begin by defining the input and output formats in this way:

(define date-input-format "%d %b %Y")
(define date-output-format "%Y-%m-%d")

We can now define a function to reformat the date string:

(define (format-date d)
  (strftime date-output-format
            (car (strptime date-input-format d))))

Removing Unwanted Characters from Currency #

There are a lot of ways we could have stripped the leading character from the currency columns, for example by extracting the substring after the first character, but I went for what I think is a more robust solution of defining the set of allowed characters and using string-filter to remove everything else:

(define currency-charset (string->char-set "0123456789.-"))

(define (format-amount s)
  (string-filter currency-charset s))

Handling Multiple Statement Formats #

My immediate need is to reformat my current account and credit card statements, which have different columns. In order to use the same script for both, I devised a specification that defines the number of leading rows to skip, whether or not the first non-skipped row is a header, and the lists of columns containing dates and amounts. These are defined as simple association lists:

(define profiles
  '(("credit-card" . ((skip . 4)
                      (header . #t)
                      (date-cols . (0))
                      (amount-cols . (3 4))))
    ("current-account" . ((skip . 4)
                          (header . #t)
                          (date-cols . (0))
                          (amount-cols . (3 4 5))))))

Next a helper function to apply a function to update the specified columns of a list:

(define (update-list lst cols f)
  (for-each (lambda (k)
              (let ((v (list-ref lst k)))
                (list-set! lst k (f v))))
            cols))

Another helper function to apply the format-date and format-amount functions to the relevant columns according to the specification:

(define (process-row spec)
  (let ((date-cols (assq-ref spec 'date-cols))
        (amount-cols (assq-ref spec 'amount-cols)))
    (lambda (row)
      (when date-cols
        (update-list row date-cols format-date))
      (when amount-cols
        (update-list row amount-cols format-amount)))))

Finally a function to handle the skip and header parameters. We simply discard the number of rows we’re told to skip and, if header is true we preserve (but do not update) the header row:

(use-modules ((srfi srfi-1) #:select (drop)))

(define (update-data spec data)
  (let* ((skip (assq-ref spec 'skip))
         (data (if skip (drop data skip) data)))
    (for-each (process-row spec) (if (assq-ref spec 'header) (cdr data) data))
    data))

To facilitate testing at the REPL, all the functions so far are operating on data, the file I/O is limited to just one function:

(define (process-statement spec input-path output-path)
  (let ((data (read-statement input-path)))
    (write-statement (update-data spec data) output-path)))

Processing Command-Line Options #

Guile has a nice DSL for parsing command-line options. It has all the functionality of the familiar getopt_long but a much nicer grammar for defining the options, see getopt-long for the details. Our main function defines the option specification, parses the command-line arguments, validates the resulting options (displaying a usage message if requested) and finally calls the process-statement function. The --overwrite option will cause the program to re-write the CSV file in-place, which we achieve by passing in the same input and output filenames.

(use-modules (ice-9 getopt-long))

(define (main args)
  (let* ((option-spec `((help      (single-char #\h) (value #f))
                        (input     (single-char #\i) (value #t) (required? #t))
                        (output    (single-char #\o) (value #t))
                        (overwrite (single-char #\w) (value #f))
                        (profile   (single-char #\p) (value #t) (predicate ,valid-profile?) (required? #t))))
         (options (getopt-long args option-spec))
         (help-wanted (option-ref options 'help #f))
         (profile (option-ref options 'profile #f))
         (input (option-ref options 'input #f))
         (output (option-ref options 'output #f))
         (overwrite (option-ref options 'overwrite #f)))
    (cond
     (help-wanted (usage))
     ((and overwrite output) (usage "output filename cannot be given with --overwrite"))
     ((not (or overwrite output)) (usage "output filename is required without --overwrite")))
    (process-statement (assoc-ref profiles profile) input (or output input))))

Note we have to use quasiquote for the option specification in order to reference the predicate function valid-profile?.

Shebang #

Shell scripts and the like have a “shebang” line at the top telling the system which interpreter to use to run them. Unfortunately, the execve system call that is used to execute them only supports a single argument to the interpreter:

#!interpreter [optional-arg]

The Guile manual suggests a work-around for Guile scripts, but this assumes you know the path to the guile executable. Instead, I’ve used the env command with the -S option to split the argument list:

#!/usr/bin/env -S guile -e main -s

This will search $PATH to find the guile command.

Guix #

The topic of Guix is a whole other book, but it’s a great way to install Guile and its modules. In particular, we can use guix shell to give us a temporary environment in which to run the script:

guix shell guile-dsv -- ~/scripts/guile/fix-nationwide-statement.scm -p current-account -i statement.csv -w

Conclusion #

The complete script is available here.

Guile is a fun language to work with, it’s very expressive and has a comprehensive standard library. It has good documentation and an active IRC channel, and is seeing a lot of activity through its use in the Guix project.