finance.lisp 2.7 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 (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 range (seq &key (key 'identity))
  29. (loop
  30. for item in seq
  31. for value = (funcall key item)
  32. minimizing value into min
  33. maximizing value into max
  34. finally (return (values min max))))
  35. (defun make-chart (series &key (usd t) (eur t) (gbp t) (brent t))
  36. (let* ((r (multiple-value-list (range series :key #'car)))
  37. (fmt (if (<= (- (second r) (first r))
  38. (* 60 60 36))
  39. '((:hour 2) ":" (:min 2))
  40. '((:day 2) "." (:month 2) " " (:hour 2) ":" (:min 2)))))
  41. (adw-charting:with-line-chart (890 600)
  42. (when usd (adw-charting:add-series "USD/RUB" (get-serie series "USD/RUB")))
  43. (when eur (adw-charting:add-series "EUR/RUB" (get-serie series "EUR/RUB")))
  44. (when gbp (adw-charting:add-series "GBP/RUB" (get-serie series "GBP/RUB")))
  45. (when brent (adw-charting:add-series "Brent last day futures"
  46. (get-serie series "Brent")))
  47. (adw-charting:set-axis
  48. :x "Time" :draw-gridlines-p t
  49. :label-formatter #'(lambda (v)
  50. (local-time:format-timestring
  51. nil
  52. (local-time:unix-to-timestamp v)
  53. :format fmt)))
  54. (adw-charting:set-axis :y "RUB" :draw-gridlines-p t :label-formatter "~,2F")
  55. (adw-charting:save-file "chart.png"))))