查找股票代码的MATLAB脚本 - 我从哪里开始?

时间:2013-07-16 20:48:57

标签: matlab

我需要查找7500多家公司的股票代码。我想让MATLAB为我做这件事。

如何在给定搜索字符串的情况下编写一个查找股票代码的脚本?例如自动查询这样的网站:http://www.nasdaq.com/quotes/symbol-lookup.aspx

进行模糊搜索或通配符的能力是一个优势。

任何洞察力都赞赏!

3 个答案:

答案 0 :(得分:1)

这是一种类似于我之前使用过的快速和肮脏的方式。

雅虎!有一个API:http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=facebook&callback=YAHOO.Finance.SymbolSuggest.ssCallback。 (尝试链接)您只需要将查询参数替换为每个公司 - 一个简单的for循环应该这样做。

在Matlab中,用

调用它
result = urlread(url);

如果您查看了API,看起来它会回来"YAHOO.Finance.SymbolSuggest.ssCallback("JSON")"包装JSON。由于urlread()只返回一个字符串,因此请替换这些字符,以便使用有效的JSON。

最后使用像this one这样的JSON库并读取结果:

stock = parse_json(result.ResultSet.Result(1).symbol); 

"模糊"查找,您可能只想查看第一个结果。

答案 1 :(得分:1)

感谢bbill让我走上正轨。我已经决定回答我自己的问题,因为它代表了一个完整的答案,希望对这个问题更有帮助。此外,此实现不需要JSON包。此功能更完整,并使用bbill建议的Yahoo Finance API。我还包括使用MarketWatch.com的第二个答案,但不太完整(见下文)。

% Get a stock ticker symbol from Yahoo Finance.
%
% get_stocksymbol('searchstring','default1') takes two arguments:
%   'searchstring' is the company name to be looked up.
%   'default1' is y/n -- set to 'y' to default to the first result if
%       the search return multiple results.
%
% stocksymbol = get_stocksymbol(searchstring,default1) returns a string
% with the result of the stock symbol lookup.
%
% [stocksymbol,choices] = get_stocksymbol(searchstring,default1) returns
% the optional cell array of company name and symbol choices.
%
% The function looks up the search string using the Yahoo Finance API (but
% without requiring the use of a JSON library) and returns all possible
% stock symbols provided by Yahoo. If more than one symbol is returned,
% the user is given the option to select the most appropriate.
%
% Trevor Zink 2013

function [stocksymbol,choices] = get_stocksymbol(searchstring,default1)

fsearchstring=strrep(searchstring,' ','%20');
url = strcat('http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=',fsearchstring,'&callback=YAHOO.Finance.SymbolSuggest.ssCallback');

try
jsonread = urlread(url);
catch errmsg
    stocksymbol = 'NA';
    fprintf('No company named %s exists in the database \n',searchstring)
    return
end
% search the JSON output for the desired term (in this case, ticker symbol)

% handle the case where either data not available or no symbol
no_data = strfind(jsonread, '"Result":[]}})');
if ~isempty(no_data),
    fprintf(1,'No symbol for %s.\n',searchstring);
    stocksymbol = 'NA';
    return;
end

% extract the symbol(s)
% find a term in the JSON output that preceeds the stock symbol(s) (in this
% case, "symbol"):
occ = strfind(jsonread, '"symbol"');
clear choices
for i=1:length(occ)
% the next four lines find characters at the beginning and the end of
% the actual stock symbol itself
sym_lt = strfind(jsonread(occ(i):end),':"');
sym_rt = strfind(jsonread(occ(i):end),'",');
nam_lt = strfind(jsonread(occ(i):end),'"nam');
nam_rt = strfind(jsonread(occ(i):end),'","ex');
jsonshort = jsonread(occ(i):end);
% then just grab the section of the JSON output inbetween the delimiters we
% established above
choices(i,1)= {i};
choices(i,2) = cellstr(jsonshort(sym_lt+2:sym_rt-1));
choices(i,3) = cellstr(jsonshort(nam_lt+9:nam_rt-1));
end

% choose from multiple options, if available
clear choice
if or(size(choices,1)==1,default1=='y')
    stocksymbol=choices{1,2};
else
    for i=1:size(choices,1)
        % this part is a bit over the top, but formats the choices in a
        % pretty table for the user to choose from
        if size(choices{i,2},1)>6
        fprintf('%i)\t\t%s\t\t%s \n',i,choices{i,2},choices{i,3})
        else
            if size(choices{i,2},1)>3 && length(choices{i,2})<=6
        fprintf('%i)\t\t%s\t\t\t%s \n',i,choices{i,2},choices{i,3})
            else
        fprintf('%i)\t\t%s\t\t\t\t%s \n',i,choices{i,2},choices{i,3})
            end
        end
    end
    fprintf('Company: %s\n',searchstring)
    choice = input('Choose an option number (default 1; choose 0 for ''NA''):');
    if isempty(choice)
        choice=1;
    end
    % account for incorrect entries
    if choice > length(choices)
        valid_response = 0;
        while ~valid_response
            choice = input('Invalid selection. Choose an option number: ');
            if choice <= length(choices)
                valid_response = 1;
            end
        end
    end
        if choice==0
            stocksymbol='NA';
        else
            stocksymbol=choices{choice,2};
        end
end

答案 2 :(得分:0)

这是一个稍微不完整的版本(无法从竞争选项中进行选择),但它使用MarketWatch.com的输出。这主要基于Luminous Logic blog的示例。

% Retrieve stock ticker symbols from MarketWatch.com
% Trevor Zink 2013
% Code based largely on example from
% http://www.luminouslogic.com/matlab_stock_scripts/get_trailing_pe.m


% Initialize Workspace
% function trailing_pe = get_symbol(searchstring)

fprintf(1,'Retrieving symbol for %s... \n', searchstring);
url_name = strcat('http://www.marketwatch.com/tools/quotes/lookup.asp?siteID=mktw&Lookup=',searchstring,'&Country=all&Type=All');
url     = java.net.URL(url_name);        % Construct a URL object
is      = openStream(url);              % Open a connection to the URL
isr     = java.io.InputStreamReader(is);
br      = java.io.BufferedReader(isr);

% Cycle through the source code until we find searchstring...
while 1
    line_buff = char(readLine(br));
    ptr       = strfind(line_buff, strcat('title="',searchstring));

    % ...And break when we find it
    if ~isempty(ptr),break; end

    % Handle the case where either data not available or no symbol
    no_data   = strfind(line_buff, 'There were no matches found');
    if ~isempty(no_data), 
        fprintf(1,'MarketWatch.com does not have a symbol for %s.\n',searchstring);
        symbol = NaN;
        return; 
    end
end

% Just to make it easier, strip off all the preceeding stuff we don't want
line_buff   = line_buff(ptr:end);

% Extract the symbol
ptr_gt      = strfind(line_buff,'>');
ptr_lt      = strfind(line_buff,'<');
symbol = line_buff(ptr_gt(1)+1:ptr_lt(1)-1);
if printsymbol=='y'
    if isempty(symbol)
        fprintf(1,'N/A\n');
    else
        fprintf(1,'%s\n',symbol);
    end
end