Goal
We're trying to print stock market price of Google, Apple and Microsoft using Yahoo finance API
0. Yahoo Query Language
Yahoo have a powerful query language that give us reasonable API to fetch data from verity of data table that their environment has like Yahoo weather or Yahoo finance.
to get more info and create or use queries visit https://developer.yahoo.com/yql/console/
1. API call to get stock market price for Google, Apple and Microsoft
if you call this query should get following result except the numbers and price may be different, for better view we removed the diagnostics section as we're not working with it
{ query: { count: 3, created: "2017-09-28T12:02:57Z", lang: "en-US", diagnostics: {}, results: { quote: [ { symbol: "AAPL", AverageDailyVolume: "26531500", Change: "+1.09", DaysLow: "153.54", DaysHigh: "154.72", YearLow: "104.08", YearHigh: "164.94", MarketCapitalization: "796.63B", LastTradePriceOnly: "154.23", DaysRange: "153.54 - 154.72", Name: "Apple Inc.", Symbol: "AAPL", Volume: "25504227", StockExchange: "NMS" }, { symbol: "GOOG", AverageDailyVolume: "1521100", Change: "+19.63", DaysLow: "927.74", DaysHigh: "949.90", YearLow: "727.54", YearHigh: "988.25", MarketCapitalization: "654.42B", LastTradePriceOnly: "944.49", DaysRange: "927.74 - 949.90", Name: "Alphabet Inc.", Symbol: "GOOG", Volume: "2239441", StockExchange: "NMS" }, { symbol: "MSFT", AverageDailyVolume: "21253800", Change: "+0.59", DaysLow: "73.17", DaysHigh: "74.17", YearLow: "56.32", YearHigh: "75.97", MarketCapitalization: "568.81B", LastTradePriceOnly: "73.85", DaysRange: "73.17 - 74.17", Name: "Microsoft Corporation", Symbol: "MSFT", Volume: "19565135", StockExchange: "NMS" } ] } } }
2. Use JavaScript Runner to get the data
Type following script in the body of JavaScript Runner macro
var yahooFinanceQuery='https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22AAPL%22%2C%22GOOG%22%2C%22MSFT%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback='; var yahooFinanceData=JSON.parse(http.get(yahooFinanceQuery)); var apple=yahooFinanceData.query.results.quote[0]; var google=yahooFinanceData.query.results.quote[1]; var microsoft=yahooFinanceData.query.results.quote[2]; context.set("google",google); context.set("microsoft",microsoft); context.set("apple",apple);
LINE DESCRIPTIONS:
1: Created a variable to hold the url that calls the query
2: Call the url using http object get function and parse the result into a JSON object at the same time
3,4,5: Create variables to hold each symbol stock market data info
6,7,8: Use context object to attach those variable to this page context so other Javascript Runner macros in this page be able to access those