finance.lisp 3.2 KB

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