(in-package #:chatikbot) (defparameter +yahoo-url+ "https://query.yahooapis.com/v1/public/yql" "Yahoo Finance API endpoint") (defparameter +yahoo-query+ "select Name,Rate from yahoo.finance.xchange where pair in (~{\"~A\"~^,~})") (defparameter +brent-url+ "http://www.cmegroup.com/CmeWS/mvc/Quotes/Future/424/G") (defvar *rate-pairs* '("USDRUB" "EURRUB" "GBPRUB")) (defun get-rates (&optional (pairs *rate-pairs*)) (let ((response (json-request +yahoo-url+ :parameters (append '(("format" . "json") ("env" . "store://datatables.org/alltableswithkeys")) (list (cons "q" (format nil +yahoo-query+ pairs))))))) (when (aget "error" response) (error "Error in rates request")) (loop for rate in (aget "rate" (aget "results" (aget "query" response))) collect (cons (aget "Name" rate) (read-from-string (aget "Rate" rate)))))) (defun get-brent () (handler-case (let ((last (read-from-string (aget "last" (first (aget "quotes" (json-request +brent-url+))))))) (when (numberp last) last)) (error (e) (log:error e)))) (defun get-serie (series name) (sort (loop for (time . rates) in series when (numberp (aget name rates)) collect (list time (aget name rates))) #'> :key #'car)) (defun make-chart (series &key (usd t) (eur t) (gbp t) (brent t)) (let ((flat (remove-if #'null (if (alexandria:circular-list-p series) (flat-circular series) series)))) (adw-charting:with-line-chart (1200 900) (when usd (adw-charting:add-series "USD/RUB" (get-serie flat "USD/RUB"))) (when eur (adw-charting:add-series "EUR/RUB" (get-serie flat "EUR/RUB"))) (when gbp (adw-charting:add-series "GBP/RUB" (get-serie flat "GBP/RUB"))) (when brent (adw-charting:add-series "Brent last day futures" (get-serie flat "Brent"))) (adw-charting:set-axis :x "Time" :draw-gridlines-p t :label-formatter #'(lambda (v) (local-time:format-timestring nil (local-time:unix-to-timestamp v) :format '((:hour 2) ":" (:min 2))))) (adw-charting:set-axis :y "RUB" :draw-gridlines-p t :label-formatter "~,2F") (adw-charting:save-file "chart.png"))))