Skip to content

Instantly share code, notes, and snippets.

@sundbp
Created October 30, 2018 09:53
Show Gist options
  • Select an option

  • Save sundbp/f1d978083dbe54919def9db621baf8da to your computer and use it in GitHub Desktop.

Select an option

Save sundbp/f1d978083dbe54919def9db621baf8da to your computer and use it in GitHub Desktop.
(ns tiingo-client
"Fns to request data from the tiingo API."
(:require [java-time :as jt]
[org.httpkit.client :as http]
[cemerick.url :as url]
[clojure.data.json :as json]
[manifold.deferred :as d]))
(def ^:private base-url "https://api.tiingo.com/tiingo/")
(def ^:dynamic *api-key* nil)
(defmacro with-api-key
"Run body with the api-key for tiingo set to the supplied value"
[key & body]
`(binding [*api-key* ~key]
~@body))
(defn- format-date-time
[d]
(cond
(jt/local-date? d)
(jt/format "yyyy-MM-dd" (jt/local-date-time d (jt/local-time 0 0 0 0)))
(jt/local-date-time? d)
(jt/format "yyyy-MM-dd" d)
:else
(throw (ex-info "Unknown type of time!" {:unknown d}))))
(defn- produce-history-options
[options]
(let [result (merge {:resampleFreq "daily"
:token *api-key*}
options)]
(assert (:startDate result) "No start date given!")
(assert (:token result) "Must set *api-key* (or provide it under :token in options)!")
(-> result
(update :startDate format-date-time)
(update :endDate format-date-time))))
(defn get-history
"Perform historical data request using the /daily API endpoing.
The argument options is a map supporting passing the info provided in the API docs:
https://api.tiingo.com/docs/tiingo/daily
In addition it supports passing the api-key under :token.
Dates/times given as inputs can be given as java.time.LocalDate or java.time.LocalDateTime
Returns a deferred with the raw result from tiingo (described in the API doc above)."
[ticker options]
(let [request-url (-> (url/url base-url "daily" ticker "prices")
(assoc :query (produce-history-options options))
str)]
(d/chain (http/get request-url {:headers {"Content-Type" "application/json"}})
(fn [r]
(json/read-json (:body r) true)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment