1
0

finance.lisp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. (in-package #:chatikbot)
  2. (defparameter +yahoo-url+ "https://query.yahooapis.com/v1/public/yql" "Yahoo Finance API endpoint")
  3. (defparameter +yahoo-query+ "select Name,Rate from yahoo.finance.xchange where pair in (~{\"~A\"~^,~})")
  4. (defparameter +brent-url+ "http://www.cmegroup.com/CmeWS/mvc/Quotes/Future/424/G")
  5. (defvar *rate-pairs* '("USDRUB" "EURRUB" "GBPRUB"))
  6. (defun get-rates (&optional (pairs *rate-pairs*))
  7. (let ((response (json-request
  8. +yahoo-url+
  9. :parameters (append '(("format" . "json")
  10. ("env" . "store://datatables.org/alltableswithkeys"))
  11. (list (cons "q" (format nil +yahoo-query+ pairs)))))))
  12. (when (aget "error" response)
  13. (error "Error in rates request"))
  14. (loop for rate in (aget "rate" (aget "results" (aget "query" response)))
  15. collect (cons (aget "Name" rate)
  16. (read-from-string (aget "Rate" rate))))))
  17. (defun get-brent ()
  18. (handler-case
  19. (let ((last (read-from-string
  20. (aget "last" (first (aget "quotes" (json-request +brent-url+)))))))
  21. (when (numberp last)
  22. last))
  23. (error (e) (log:error e))))
  24. (defun get-serie (series name)
  25. (loop for (time . rates) in series
  26. when (numberp (aget name rates))
  27. collect (list time (aget name rates))))
  28. (defun make-chart (series &key (usd t) (eur t) (gbp t) (brent t))
  29. (let ((flat (remove-if #'null (if (alexandria:circular-list-p series)
  30. (flat-circular series)
  31. series))))
  32. (adw-charting:with-line-chart (1200 900)
  33. (when usd (adw-charting:add-series "USD/RUB" (get-serie flat "USD/RUB")))
  34. (when eur (adw-charting:add-series "EUR/RUB" (get-serie flat "EUR/RUB")))
  35. (when gbp (adw-charting:add-series "GBP/RUB" (get-serie flat "GBP/RUB")))
  36. (when brent (adw-charting:add-series "Brent last day futures"
  37. (get-serie flat "Brent")))
  38. (adw-charting:set-axis
  39. :x "Time" :draw-gridlines-p t
  40. :label-formatter #'(lambda (v) (local-time:format-timestring nil (local-time:unix-to-timestamp v)
  41. :format '((:hour 2) ":" (:min 2)))))
  42. (adw-charting:set-axis :y "RUB" :draw-gridlines-p t :label-formatter "~,2F")
  43. (adw-charting:save-file "chart.png"))))