finance.lisp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. when (elt row idx)
  27. collect (list (first row) (elt row idx))))
  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. (defvar *chart-points* 800 "Data points in chart")
  36. (defun make-chart (series names)
  37. (let* ((r (multiple-value-list (range series :key #'car)))
  38. (fmt (if (<= (- (second r) (first r))
  39. (* 60 60 36))
  40. '((:hour 2) ":" (:min 2))
  41. '((:day 2) "." (:month 2) " " (:hour 2) ":" (:min 2)))))
  42. (adw-charting:with-line-chart ((+ 90 *chart-points*)
  43. (floor (* 3 *chart-points*) 4))
  44. (loop for serie in names
  45. for idx from 1
  46. do (adw-charting:add-series serie (get-serie series idx)))
  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"))))