1
0

finance.lisp 2.5 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 idx)
  25. (loop for row in series
  26. collect (list (first row) (elt row idx))))
  27. (defun range (seq &key (key 'identity))
  28. (loop
  29. for item in seq
  30. for value = (funcall key item)
  31. minimizing value into min
  32. maximizing value into max
  33. finally (return (values min max))))
  34. (defvar *chart-points* 800 "Data points in chart")
  35. (defun make-chart (series names)
  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 ((+ 90 *chart-points*)
  42. (floor (* 3 *chart-points*) 4))
  43. (loop for serie in names
  44. for idx from 1
  45. do (adw-charting:add-series serie (get-serie series idx)))
  46. (adw-charting:set-axis
  47. :x "Time" :draw-gridlines-p t
  48. :label-formatter #'(lambda (v)
  49. (local-time:format-timestring
  50. nil
  51. (local-time:unix-to-timestamp v)
  52. :format fmt)))
  53. (adw-charting:set-axis :y "RUB" :draw-gridlines-p t :label-formatter "~,2F")
  54. (adw-charting:save-file "chart.png"))))