Мои познания в javascript ограничены. Тем не менее, много читая, я смог собрать описанные ниже функции. Цель состоит в том, чтобы определить общую функцию, с помощью которой я могу извлекать определенные данные из финансов Yahoo.
В приведенном ниже примере я извлекаю МНОГО данных JSON для любого тикера (пример ссылки внизу). Из возвращенного JSON я выбираю, какие значения меня интересуют (здесь только дивидендыRate и paypoutRatio. Если вызвать эту функцию в ячейке (я использую Google Sheets), она вернет 2 ячейки с запрошенной информацией:
=yFinance("KO")
+------+
| 1.76 |
+------+
| 0.75 |
+------+
Используемая ссылка: Yahoo Finance JSON для Coca Cola
Однако мне нужно, чтобы данные были отформатированы не в 2 ячейках НИЖЕ друг друга, а РЯДОМ друг с другом:
=yFinance("KO")
+------+------+
| 1.76 | 0.75 |
+------+------+
У меня есть два вопроса:
getMatchingValues()
?), чтобы это произошло?Любая помощь приветствуется, в том числе потому, что я чувствую, что подобная общая функция принесет пользу многим людям в будущем. Я видел много сообщений об извлечении одного значения из Yahoo Finance, в основном путем анализа HTML (таблиц) с использованием функции Google Sheets INDEX()
, но я считаю, что JSON быстрее и устойчивее к будущим изменениям внешнего интерфейса в Yahoo.
function yFinance(symbol) {
const url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/' + encodeURI(symbol)
+ '?modules=price,assetProfile,summaryDetail,incomeStatementHistory,'
+ 'balanceSheetHistory,defaultKeyStatistics,financialData,calendarEvents,'
+ 'recommendationTrend,upgradeDowngradeHistory,majorHoldersBreakdown'
;
const response = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
const responseCode = response.getResponseCode();
if (responseCode === 200) {
const quote = JSON.parse(response.getContentText());
const paths = [
'summaryDetail/dividendRate/raw',
'summaryDetail/payoutRatio/raw'
];
return getMatchingValues(getPath(quote, 'quoteSummary/result/0'), paths);
}
else
{
return -1;
}
}
function getPath( obj, path ) {
if (!path || !obj) {
return null;
}
const parts = path.split('/');
const currentPath = parts[0];
const nextPath = parts.slice(1).join('/');
const currentObj = obj[currentPath];
// final path, exit here
if (nextPath.length === 0) {
return currentObj;
}
if (Array.isArray( currentObj )) {
// does an element exit at the next level
if ( currentObj[parts[1]] ) {
// will continue reading for 1 element
return getPath( currentObj, nextPath );
}
// return all the subpaths, skip the ones that are falsy
return currentObj.map( item => getPath( item, nextPath ) ).filter( v => v );
}
// get the next part of the object
return getPath( currentObj, nextPath );
}
function getMatchingValues( obj, paths ) {
return paths.flatMap( path => getPath( obj, path ));
}
Если вы хотите получить бок о бок значения, измените, добавив скобки следующим образом
return [getMatchingValues(getPath(quote, 'quoteSummary/result/0'), paths)];
Вы можете упростить код следующим образом
function yFinance_new(symbol) {
const url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/' + encodeURI(symbol)
+ '?modules=price,assetProfile,summaryDetail,incomeStatementHistory,'
+ 'balanceSheetHistory,defaultKeyStatistics,financialData,calendarEvents,'
+ 'recommendationTrend,upgradeDowngradeHistory,majorHoldersBreakdown'
;
const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
const responseCode = response.getResponseCode();
if (responseCode === 200) {
const quote = JSON.parse(response.getContentText());
return [[
quote.quoteSummary.result[0].summaryDetail.dividendRate.raw,
quote.quoteSummary.result[0].summaryDetail.payoutRatio.raw
]];
}
else {
return -1;
}
}