1
0

finance.lisp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 (yason:parse
  8. (flexi-streams:octets-to-string
  9. (drakma:http-request +yahoo-url+
  10. :parameters (append '(("format" . "json")
  11. ("env" . "store://datatables.org/alltableswithkeys"))
  12. (list (cons "q" (format nil +yahoo-query+ pairs)))))
  13. :external-format :utf-8)
  14. :object-as :alist)))
  15. (when (aget "error" response)
  16. (error "Error in rates request"))
  17. (loop for rate in (aget "rate" (aget "results" (aget "query" response)))
  18. collect (cons (aget "Name" rate)
  19. (read-from-string (aget "Rate" rate))))))
  20. (defun get-brent ()
  21. (handler-case
  22. (read-from-string
  23. (aget "last" (first (aget "quotes"
  24. (yason:parse
  25. (flexi-streams:octets-to-string
  26. (drakma:http-request +brent-url+
  27. :force-binary t
  28. :decode-content t)
  29. :external-format :utf-8)
  30. :object-as :alist)))))
  31. (error (e) (log:error e))))
  32. (defun get-serie (series name)
  33. (loop for (time . rates) in series
  34. when (aget name rates)
  35. collect (list time (aget name rates))))
  36. (defun make-chart (series &key (usd t) (eur t) (gbp t) (brent t))
  37. (let ((flat (remove-if #'null (if (alexandria:circular-list-p series)
  38. (flat-circular series)
  39. series))))
  40. (adw-charting:with-line-chart (1200 900)
  41. (when usd (adw-charting:add-series "USD/RUB" (get-serie flat "USD/RUB")))
  42. (when eur (adw-charting:add-series "EUR/RUB" (get-serie flat "EUR/RUB")))
  43. (when gbp (adw-charting:add-series "GBP/RUB" (get-serie flat "GBP/RUB")))
  44. (when brent (adw-charting:add-series "Brent last day futures"
  45. (get-serie flat "Brent")))
  46. (adw-charting:set-axis
  47. :x "Time" :draw-gridlines-p t
  48. :label-formatter #'(lambda (v) (local-time:format-timestring nil (local-time:unix-to-timestamp v)
  49. :format '((:hour 2) ":" (:min 2)))))
  50. (adw-charting:set-axis :y "RUB" :draw-gridlines-p t :label-formatter "~,2F")
  51. (adw-charting:save-file "chart.png"))))