UNPKG

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
Promise = require('bluebird') request = Promise.promisifyAll(require('request')) formats = require('./formats.js') querystring = require('querystring') stream = require 'stream' util = require 'util' class ArrayStream constructor: (@arr) -> stream.Readable.call(@, {objectMode:true}) @_init = false util.inherits(ArrayStream, stream.Readable) init : (arr) -> @_init = true @arr = arr if arr? @_read() _read : () -> if not @_init return if @arr.length > 0 this.push(@arr.shift()) else this.push(null) class StockClient constructor: (formatOpts, config = {})-> @_formatOpts = formatOpts if formatOpts instanceof Array @_formatOpts = formats.Categories[formatOpts] if typeof(formatOpts) is 'string' throw Error('FormatOpts must be Array or Category String. Got: ' + formatOpts) if not @_formatOpts? @_config = config @_formatString = "" @_formatString += symbol for symbol in formats.formatsToFormatSymbols(@_formatOpts) _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 @_config.Stream? and @_config.Stream arrStream = new ArrayStream([]) request.getAsync(@_historicalUrl + querystring.stringify(queryObj)) .then( (() -> arrS = arrStream (data) -> dat = data[1].replace(/\r/g, '').split('\n') dat.pop() arrS.init(dat) )() ) return arrStream if @_config.Async? and @_config.Async return request.getAsync(@_historicalUrl + querystring.stringify(queryObj)) request.get(@_historicalUrl + 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 @_config.Stream? and @_config.Stream arrStream = new ArrayStream([]) request.getAsync(@_yahooUrl + '?s=' + symbolStr + '&f=' + @_formatString) .then( (() -> arrS = arrStream (data) -> dat = data[1].replace(/\r/g, '').split('\n') dat.pop() arrS.init(dat) )() ) return arrStream if @_config.Async? and @_config.Async return request.getAsync(@_yahooUrl + '?s=' + symbolStr + '&f=' + @_formatString) request.get(@_yahooUrl + '?s=' + symbolStr + '&f=' + @_formatString, 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)