Skip to content

Instantly share code, notes, and snippets.

@aj0strow
Created May 25, 2015 21:03
Show Gist options
  • Save aj0strow/d06f1dc2a6adc49b8f0b to your computer and use it in GitHub Desktop.
Save aj0strow/d06f1dc2a6adc49b8f0b to your computer and use it in GitHub Desktop.
YQL finance data
YQL('yahoo.finance.quotes')
.where({ symbol: [ '^IXIC' ] })
.select([ 'Symbol', 'LastTradePriceOnly', 'Change', 'PercentChange' ])
.then(function (results) {
console.log(results)
})
YQL('yahoo.finance.historicaldata')
.where('symbol', '=', 'PRFC')
.where({ startDate: new Date(2015, 4, 1), endDate: new Date(2015, 4, 23) })
.then(function (results) {
console.log(results)
})
(function () {
function YQL (table) {
return new QueryBuilder(table)
}
var defaults = {
baseUrl: 'http://query.yahooapis.com/v1/public/yql',
env: 'store://datatables.org/alltableswithkeys',
}
function exec (options) {
if (is('string', options)) {
options = { q: options }
}
options = $.extend({}, defaults, options)
return $.getJSON(options.baseUrl, {
q: options.q,
env: options.env,
format: 'json'
}).then(function (response) {
return response.query.results.quote
})
}
YQL.exec = exec
YQL.defaults = defaults
function QueryBuilder (table) {
this.table = table
this.keys = []
this.clauses = []
}
QueryBuilder.prototype.then = function (a, b) {
return this.exec().then(a, b)
}
QueryBuilder.prototype.exec = function () {
return exec({ q: this.toString() })
}
QueryBuilder.prototype.select = function (keys) {
this.keys = this.keys.concat(keys)
return this
}
QueryBuilder.prototype.where = function (a, op, b) {
switch (arguments.length) {
case 3:
return this.where(a + ' ' + op + ' ' + param(b))
case 2:
return this.where(a, (is('array', op) ? 'in' : '='), op)
case 1:
if (is('string', a)) {
this.clauses.push(a)
} else {
Object.keys(a).forEach(function (key) {
this.where(key, a[key])
}, this)
}
return this
default:
throw new Error('expected 1 to 3 arguments')
}
}
QueryBuilder.prototype.toString = function () {
var q = []
var keys = this.keys.slice(0)
if (!keys.length) { keys.push('*') }
q.push('select', keys.join(','))
q.push('from', this.table)
if (this.clauses) {
q.push('where', this.clauses.join(' and '))
}
return q.join(' ')
}
function param (value) {
var type = $.type(value)
switch (type) {
case "string":
return '"' + value + '"'
case "number":
return param(String(value))
case "array":
return '(' + value.map(param).join(',') + ')'
case "date":
var parts = [
value.getFullYear(),
pad(value.getMonth() + 1, 2),
pad(value.getDate(), 2)
]
return param(parts.join('-'))
}
}
function pad (x, len) {
var str = String(x || 0)
while (str.length < (len || 0)) { str = '0' + str }
return str
}
function is (typ, val) {
return $.type(val) == typ
}
window.YQL = YQL
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment