【源码】使用MATLAB从Alpha Vantage API传递数据的函数Alpha Vantage API wrapper

Alpha Vantage以简单的JSON或CSV格式为实时财务数据和大多数使用的财务指标提供免费API函数。

Alpha Vantage delivers a free API for real-time financial data and most used finance indicators in a simple JSON or CSV format.

该模块实现了一个与Alpha Vantage提供的免费API的Matlab接口。

This module implements a Matlab interface to the free API provided by Alpha Vantage.

该工具包能够从股票、物理货币、加密货币以及相关元数据的历史数据中向它们中的每一个发出请求。

This wrapper is capable to make requests from historical data of Stocks, Physical currencies, Cryptocurrencies and the associated metadata to each one of them.

为了使用API工具,您必须从Alpha Vantage请求一个API密钥。

In order to use the API wrapper, you must request an API key from Alpha Vantage.

function [cryptoData] = getCrypto(apikey, symbol, market, type)

%This function returns the daily historical time series for a digital

%currency (e.g., BTC) traded on a specific market (e.g., CNY/Chinese Yuan)

%, refreshed daily at midnight (UTC). Prices and volumes are quoted in

%both the market-specific currency and USD.

%

%INPUT:

% apikey - Is your api key (request it in alphavantage.com), e.g. ‘demo’

% symbol - The digital/crypto currency of your choice. e.g. ‘BTC’

% market - The exchange market of your choice. e.g. ‘CNY’

% type - Time resolution of the data (‘daily’, ‘weekly’ and’monthly’).

%

% Examples:

% %request daily Prices and Volumes for Bitcoin in the chinese market.

%crypto = getCrypto(‘demo’, ‘BTC’, ‘CNY’);

%

% %request monthly Prices and Volumes for Bitcoin in the chinese market.

%crypto = getCrypto(‘demo’, ‘BTC’, ‘CNY’, ‘monthly’);

%

%for more details check:

%Mathworks File Exchange: https://la.mathworks.com/matlabcentral/fileexchange/72025-alpha-vantage-api-wrapper

%Alpha Vantage API: https://www.alphavantage.co/documentation/#digital-currency

%

%Author: Lautaro Parada Opazo

if nargin < 3

error('Not supported parameters. Try help getCrypto for examples and documentation of the function.');

elseif nargin == 3

    api_path = 'https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_DAILY&symbol=%s&market=%s&apikey=%s';

    % inserting the parameters into the path

    json_query = char(compose(api_path, symbol, market, apikey));

    dataDaily = webread(json_query);  

    % decompose the response

    cryptoData = decomposeCrypto(dataDaily);

elseif nargin >3

if isequal(type, 'daily')

    api_path = 'https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_DAILY&symbol=%s&market=%s&apikey=%s';

    % inserting the parameters into the path

    json_query = char(compose(api_path, symbol, market, apikey));

    dataDaily = webread(json_query);  

    % decompose the response

    cryptoData = decomposeCrypto(dataDaily);

    

elseif isequal(type, 'weekly')

    api_path = 'https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_WEEKLY&symbol=%s&market=%s&apikey=%s';

    % inserting the parameters into the path

    json_query = char(compose(api_path, symbol, market, apikey));

    dataDaily = webread(json_query);  

    % decompose the response

    cryptoData = decomposeCrypto(dataDaily);

    

elseif isequal(type, 'monthly')

    api_path = 'https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_MONTHLY&symbol=%s&market=%s&apikey=%s';

    % inserting the parameters into the path

    json_query = char(compose(api_path, symbol, market, apikey));

    dataDaily = webread(json_query);  

    % decompose the response

    cryptoData = decomposeCrypto(dataDaily);



else

    error('Not supported parameters. Try help getCrypto for examples and documentation of the function.')

end

end

end

%Daily, Weekly and Monthly descomposition of the data

function [T] = decomposeCrypto(data)

% decompose the response

fields_pre = fieldnames(data);

fields = fieldnames(data.(fields_pre{2}));

ticker_data = zeros(1,10);

spot_data = zeros(numel(fields), 10);

time_data = NaT(numel(fields), 1);

for idx = 1:numel(fields)

% this loop extract the date and the values asociated with the spot

% values of the range of the data

ticker_time = strjoin(regexp(fields{idx}, '\d+', 'match'));

ticker_time = datetime(ticker_time, 'InputFormat', 'yyyy MM dd');

ticker_data = struct2cell(data.(fields_pre{2}).(fields{idx}));

ticker_data = cellfun(@(x)str2double(x), ticker_data);

for j = 1:numel(ticker_data)

    spot_data(idx, j) = ticker_data(j);

end

time_data(idx,1) = ticker_time;

end

% proccesing

%extracting the names

namesCrypto = fieldnames(data.(fields_pre{2}).(fields{1}));

namesRaw = repmat({char(0)}, length(namesCrypto), 1);

namesPure = repmat({char(0)}, length(namesCrypto), 1);

for name = 1:numel(namesCrypto)

namesRaw{name} = string(regexp(namesCrypto{name}, '_.*', 'match'));

namesPure{name} = string(regexprep(namesRaw{name}, '\_', '', 'all'));

end

% adding the date name to the variable names

namesPure = cellstr(namesPure);

% changing the format of the cell elements. This is from each element as an

% array, to each element as a string.

T = table(spot_data(:,1), spot_data(:,2), spot_data(:,3), …

spot_data(:,4), spot_data(:,5), spot_data(:,6), spot_data(:,7), ...

spot_data(:,8), spot_data(:,9), spot_data(:,10), ...

'VariableNames', namesPure);

T = addvars(T, time_data, ‘Before’, namesPure{1}, ‘NewVariableNames’, ‘Date’);

T = flipud(T);

end

上一篇:第二十四篇 -- 学习第二十九天打卡20190720


下一篇:第二十篇 -- 学习第十九天打卡20190709