I'm building an app that tells you a stock's percentage change in price between two dates by using Yahoo's API. Given a stock ticker and two dates, it currently outputs the percentage return to the console.
I would like to later expand this app to give it a list of stock tickers and dates. For each, it would return the performance relative to another stock between the dates.
I want the app to try to pull stock data from the Yahoo API, but to then try another API if the data for that stock is not available from Yahoo.
Here's what I have so far. I believe I'm using the revealing module pattern (although maybe not correctly). Any advice on how I can structure this code to maintain simplicity and comprehensibility as I add functionality would be appreciated. I'm open to input on whether that should be another design pattern or programming style altogether.
$(function () {
// This object provides the stock ticker,
// as well as the dates to compute the percentage
// change of the stock's price between.
var stock = {
ticker: 'fb',
startDate: '2015-08-06',
endDate: '2016-04-12'
};
yahooFinance.getStockData(stock);
});
var utility = {};
(function () {
var removeLeadingZero = function removeLeadingZero (strNumber) {
if (strNumber.charAt(0) === '0') {
return strNumber.substr(1);
}else{
return strNumber;
}
};
var formatForConsole = function formatForConsole (dateString) {
var dateStringArray = dateString.split('-');
var month = removeLeadingZero(dateStringArray[1]);
var day = removeLeadingZero(dateStringArray[2]);
var year = dateStringArray[0];
return month + '/' + day + '/' + 'year';
};
var getPercentChange = function getPercentChange (startingPrice, endingPrice) {
return ((endingPrice - startingPrice) / startingPrice) * 100;
};
$.extend(utility, {
formatForConsole: formatForConsole,
getPercentChange: getPercentChange
});
}());
var yahooFinance = {};
(function () {
// Returns the URI to request daily price data for the stock in JSON format.
var getUri = function getUri (stockObj) {
return 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo'
+ '.finance.historicaldata%20where%20symbol%20%3D%20%22'
+ stockObj.ticker
+ '%22%20and%20startDate%20%3D%20%22'
+ stockObj.startDate
+ '%22%20and%20endDate%20%3D%20%22'
+ stockObj.endDate
+ '%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
};
var getStockData = function getStockData (stockObj) {
$.getJSON(getUri(stockObj), function (priceData) {
var startDate = utility.formatForConsole(stockObj.startDate);
var endDate = utility.formatForConsole(stockObj.endDate);
console.log(startDate + ' to ' + endDate);
var pricesArray = priceData.query.results.quote;
var startingPrice = pricesArray[pricesArray.length - 1].Adj_Close;
var endingPrice = pricesArray[0].Adj_Close;
var percentChange = utility.getPercentChange(startingPrice, endingPrice);
console.log(percentChange);
});
};
$.extend(yahooFinance, {
getStockData: getStockData
});
}());