Skip to content

Instantly share code, notes, and snippets.

@rberaldo
Created September 14, 2022 03:39
Show Gist options
  • Save rberaldo/82b3f9c463f603665eb16d16dc7b4f32 to your computer and use it in GitHub Desktop.
Save rberaldo/82b3f9c463f603665eb16d16dc7b4f32 to your computer and use it in GitHub Desktop.
Automatically fetch ledger entries of commodity prices.
;;
;; ledger helper functions
(defun my/ledger-copy-down-commodity-price ()
"Adds a new, updated ledger commodity price entry based on the
current line, which should follow the structure \"P DATE TIME
COMMODITY PRICE CURRENCY\". Automatically updates date, time and
fetches current prices."
(interactive)
(let (line commodity price)
;; Read current line and split it.
;; Idea: add error checking, such as an empty line.
(setq line (split-string
(buffer-substring-no-properties
(line-beginning-position) (line-end-position))))
;; Gets the commodity. Code isn’t going to work if Yahoo does not
;; recognize it.
(setq commodity (string-trim (nth 3 line) "\"" "\""))
;; Fetches price. If the commodity is BTC, convert it to Brazilian
;; Reais.
(setq price (format "%0.2f"
(if (equal commodity "BTC")
(my/fetch-BTC-BRL)
;; If it isn’t BTC, it is probably a commodity.
(my/fetch-yahoo-finance-commodity-price commodity))))
;; Insert the price entry.
(move-end-of-line 1)
(newline)
(my/ledger-insert-commodity-price commodity price)))
(defun my/ledger-insert-commodity-price (c p)
"Inserts a ledger commodity entry with commodity C and price P."
(interactive
(list
(read-string "Commodity: ")
(read-string "Price: ")))
(insert (concat
"P "
(format-time-string "%Y/%m/%d %T ")
"\"" c "\""
" "
p
" BRL")))
(defun my/fetch-yahoo-finance-commodity-price (c)
"Fetches commodity C prices from Yahoo Finance."
(let (yahoo-base-url price-json)
(setq yahoo-base-url "https://query1.finance.yahoo.com/v8/finance/chart/")
(setq price-json
(with-current-buffer (url-retrieve-synchronously
(concat yahoo-base-url c))
(goto-char (point-min))
(goto-char url-http-end-of-headers)
(prog1 (json-read)
(kill-buffer))))
;; Extract price from json-derived plist; not sure if this is the
;; correct way.
(cdr
(assoc 'regularMarketPrice
(assoc 'meta
(aref
(cdr
(assoc 'result
(assoc 'chart price-json)))
0))))))
(defun my/fetch-BTC-BRL ()
"Fetches BTC-BRL price from Yahoo Finances."
(let (btc-price brl-usd)
(setq btc-price (my/fetch-yahoo-finance-commodity-price "BTC-USD"))
(setq brl-usd (my/fetch-yahoo-finance-commodity-price "BRL=X"))
(* btc-price brl-usd)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment