/
quandl.go
242 lines (207 loc) · 6.1 KB
/
quandl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package quandl
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// APIKey is used to set your api key before you make any call
var APIKey = ""
// LastURL will hold the last requested URL after each call
var LastURL = ""
// CacheHandler is a reference to a struct that implements the Cacher interface.
// If set, it will use it to get documents from the cache or set to it.
var CacheHandler Cacher
var urlTemplates = map[string]string{
"symbol": "https://www.quandl.com/api/v3/datasets/%s.%s?%s",
"search": "https://www.quandl.com/api/v3/datasets.%s?%s",
"list": "https://www.quandl.com/api/v3/datasets.%s?%s",
}
// Options is used to send additional parameters in the Quandl request
type Options url.Values
// Set registers a key=value pair to be sent in the Quandl request
func (o Options) Set(key, value string) {
o[key] = []string{value}
}
// Cacher defines the interface for a custom cache handler
type Cacher interface {
Get(key string) []byte
Set(key string, data []byte) error
}
// NewOptions accepts any even number of arguments and returns an
// Options object. The odd arguments are the keys, the even arguments
// are the values.
func NewOptions(s ...string) Options {
o := Options{}
for i := 0; i < len(s); i += 2 {
o.Set(s[i], s[i+1])
}
return o
}
// GetSymbol returns data for a given symbol
func GetSymbol(symbol string, params Options) (*SymbolResponse, error) {
raw, err := GetSymbolRaw(symbol, "json", params)
var response struct {
Dataset SymbolResponse
}
if err != nil {
return &response.Dataset, err
}
err = json.Unmarshal(raw, &response)
if err != nil {
return &response.Dataset, marshallerError(raw, err)
}
return &response.Dataset, nil
}
// GetList returns a list of symbols for a source
func GetList(source string, page int, perPage int) (*ListResponse, error) {
raw, err := GetListRaw(source, "json", page, perPage)
var response ListResponse
if err != nil {
return &response, err
}
err = json.Unmarshal(raw, &response)
if err != nil {
return &response, marshallerError(raw, err)
}
return &response, nil
}
// GetSearch returns search results
func GetSearch(query string, page int, perPage int) (*SearchResponse, error) {
raw, err := GetSearchRaw(query, "json", page, perPage)
var response SearchResponse
if err != nil {
return &response, err
}
err = json.Unmarshal(raw, &response)
if err != nil {
return &response, marshallerError(raw, err)
}
return &response, nil
}
// GetSymbolRaw returns CSV, JSON or XML data for a given symbol
func GetSymbolRaw(symbol string, format string, params Options) ([]byte, error) {
url := getURL("symbol", symbol, format, arrangeParams(params))
return getData(url)
}
// GetListRaw returns a list of symbols for a source as CSV, JSON or XML
func GetListRaw(source string, format string, page int, perPage int) ([]byte, error) {
params := Options{}
params.Set("query", "*")
params.Set("database_code", source)
params.Set("per_page", strconv.Itoa(perPage))
params.Set("page", strconv.Itoa(page))
url := getURL("list", format, arrangeParams(params))
return getData(url)
}
// GetSearchRaw returns search results as JSON or XML
func GetSearchRaw(query string, format string, page int, perPage int) ([]byte, error) {
params := Options{}
// TODO: Remove when Quandl fixes this bug
if format == "csv" {
format = "json"
}
params.Set("query", query)
params.Set("per_page", strconv.Itoa(perPage))
params.Set("page", strconv.Itoa(page))
url := getURL("search", format, arrangeParams(params))
return getData(url)
}
// ToColumns converts a rows array to a columns array
func ToColumns(src [][]interface{}) (out [][]interface{}) {
out = make([][]interface{}, len(src[0]))
for _, row := range src {
for j, cell := range row {
out[j] = append(out[j], cell)
}
}
return
}
// ToNamedColumns converts a rows array to a columns map
func ToNamedColumns(src [][]interface{}, keys []string) (out map[string][]interface{}) {
out = make(map[string][]interface{})
for _, row := range src {
for j, cell := range row {
out[keys[j]] = append(out[keys[j]], cell)
}
}
return
}
// FloatColumn converts a column of interface{} to a column of floats
func FloatColumn(s []interface{}) []float64 {
r := make([]float64, len(s))
for i := range s {
r[i] = s[i].(float64)
}
return r
}
// TimeColumn converts a column of interface{} to a column of time
func TimeColumn(s []interface{}) []time.Time {
r := make([]time.Time, len(s))
for i := range s {
r[i], _ = time.Parse("2006-01-02", s[i].(string))
}
return r
}
// StringColumn converts a column of interface{} to a column of string
func StringColumn(s []interface{}) []string {
r := make([]string, len(s))
for i := range s {
r[i] = s[i].(string)
}
return r
}
// getData requests a URL from Quandl and returns the raw response string
func getData(url string) ([]byte, error) {
if CacheHandler != nil {
if response := CacheHandler.Get(url); response != nil {
return response, nil
}
}
response, err := http.Get(url)
if err != nil {
return nil, err
}
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if CacheHandler != nil {
if err := CacheHandler.Set(url, contents); err != nil {
return nil, err
}
}
return contents, nil
}
// getURL receives a kind that points to a URL template and
// a variable number of strings, which will be replaced
// in the template.
func getURL(kind string, args ...interface{}) string {
template := urlTemplates[kind]
LastURL = strings.Trim(fmt.Sprintf(template, args...), "&?")
return LastURL
}
// arrangeParams takes an Options map and converts it to
// a query string. It will also append the api key as needed.
func arrangeParams(qs Options) string {
if qs == nil {
if APIKey == "" {
return ""
}
qs = Options{}
}
if APIKey != "" {
qs.Set("api_key", APIKey)
}
return url.Values(qs).Encode()
}
// marshallerError returns a formatted error that includes the response
func marshallerError(response []byte, err error) error {
return errors.New("JSON Marshaller Error:\nRESPONSE:\n" + string(response) + "\n\nERROR:\n" + err.Error())
}