yahoo-stock-client
Version:
Module to fetch stock information via yahoo's stock api. Returns data in csv format.
96 lines (83 loc) • 2.91 kB
text/coffeescript
Promise = require('bluebird')
request = Promise.promisifyAll(require('request'))
formats = require('./formats.js')
querystring = require('querystring')
stream = require 'stream'
util = require 'util'
class ArrayStream
constructor: () ->
stream.Readable.call(@, {objectMode:true})
= false
util.inherits(ArrayStream, stream.Readable)
init : (arr) ->
= true
= arr if arr?
_read : () ->
if not
return
if .length > 0
this.push(.shift())
else
this.push(null)
class StockClient
constructor: (formatOpts, config = {})->
= formatOpts if formatOpts instanceof Array
= formats.Categories[formatOpts] if typeof(formatOpts) is 'string'
throw Error('FormatOpts must be Array or Category String. Got: ' + formatOpts) if not ?
= config
= ""
+= symbol for symbol in formats.formatsToFormatSymbols()
_yahooUrl : "http://finance.yahoo.com/d/quote.csv"
_historicalUrl: 'http://ichart.finance.yahoo.com/table.csv?'
getHistorical : (symbol, cb) ->
if typeof symbol is 'string'
symbolStr = symbol
queryObj =
s:symbol
if .Stream? and .Stream
arrStream = new ArrayStream([])
request.getAsync( + querystring.stringify(queryObj))
.then(
(() ->
arrS = arrStream
(data) ->
dat = data[1].replace(/\r/g, '').split('\n')
dat.pop()
arrS.init(dat)
)()
)
return arrStream
if .Async? and .Async
return request.getAsync( + querystring.stringify(queryObj))
request.get( + querystring.stringify(queryObj), cb)
getData : (symbol, cb) ->
if typeof symbol is 'string'
symbolStr = symbol
if symbol instanceof Array
symbolStr = ""
symbolStr += stock + '+' for stock in symbol
symbolStr = symbolStr.slice(0, -1)
if .Stream? and .Stream
arrStream = new ArrayStream([])
request.getAsync( + '?s=' + symbolStr + '&f=' + )
.then(
(() ->
arrS = arrStream
(data) ->
dat = data[1].replace(/\r/g, '').split('\n')
dat.pop()
arrS.init(dat)
)()
)
return arrStream
if .Async? and .Async
return request.getAsync( + '?s=' + symbolStr + '&f=' + )
request.get( + '?s=' + symbolStr + '&f=' + , cb)
###
formatOpts is either a string or array
if its a string it is taken to be a category
else its taken to be an array of format options
###
exports.createClient = (formatOpts, config) ->
new StockClient(formatOpts, config)