function out = getOptionPrices(symbolid)
%out = getOptionPrices(symbolid)
%find option prices: use average of bid and call
%
%out contains the following values:
%
%  out.sym         stock symbol
%  out.time        time when option prices were obtained (datetime type)
%  out.stockprice  stock price
%
%  out.opt         struct array with expirations, strikes, option prices
%
%N = length(out.val)                   % number of expiration dates
%For i=1,...,N:
%  out.opt(i).expir                    % expiration date (datetime type)
%  out.opt(i).pstrike, data(i).pprice  % strikes, prices for put options
%  out.opt(i).cstrike, data(i).cprice  % strikes, prices for call options
%
%EXAMPLE:
%  out = getOptionPrices('AAPL')       % get Apple option prices    
%  out.opt(end)                        % last expiration date available
%  plot(out.opt(end).pstrike, out.opt(end).pprice,'.-') 
%                   % for this expiration: plot put option prices vs. strike


% using getGoogleOptionsData by C. Lau
% www.mathworks.com/matlabcentral/fileexchange/50368

if nargin < 1
    disp('Please type "help getOptionPrices" for syntax.');
    return;
end

timenow = datetime('now');

try
    urlExpiry = urlread(['http://www.google.com/finance/option_chain?q=' symbolid '&output=json']);
catch ME
    disp(ME);
    sprintf('Error: Cannot retrieve option data using urlread for %s\n',symbolid);
    out = [];
    return;
end
    
% E.g. of data: 
  % expirations:[
  %    {y:2014,m:12,d:5},{y:2014,m:12,d:12},{y:2014,m:12,d:20},{y:2014,m:12,d:26},{y:2015,m:1,d:2},{y:2015,m:1,d:9},{y:2015,m:1,d:17},{y:2015,m:2,d:20},{y:2015,m:3,d:20},{y:2015,m:4,d:17},{y:2015,m:7,d:17},{y:2016,m:1,d:15},{y:2017,m:1,d:20}
  %    ]
tt = regexp(urlExpiry,'expirations:\[(.*)\],puts','tokens');
if isempty(tt)
   out = [];
   return; 
end
expiry = regexp(tt{1}{1},'{y:(?<yy>\d+),m:(?<mm>\d+),d:(?<dd>\d+)}','names');

tt2 = regexp(urlExpiry,'underlying_price:([0-9.]+)','tokens');
stockprice = str2num(tt2{1}{1});


for tempi = 1:size(expiry,2)

    
    try
        urlContract = urlread(['http://www.google.com/finance/option_chain?q=' symbolid '&output=json&expy=' expiry(tempi).yy '&expm=' expiry(tempi).mm '&expd=' expiry(tempi).dd]);
    catch ME
        disp(ME);
        sprintf('Error: Cannot retrieve option expiry data using urlread for %s\n',symbolid);
        continue;
    end

    
    tt = regexp(urlContract,'puts:\[(.*)\],calls','tokens');
        % Note the ",calls" to capture only the call data
    putsTT{tempi} = regexp(tt{1}{1},'{cid:"(?<cid>.*?)",name:"(?<name>.*?)",s:"(?<s>.*?)",e:"(?<e>.*?)",p:"(?<p>.*?)",c:"(?<c>.*?)",b:"(?<b>.*?)",a:"(?<a>.*?)",oi:"(?<oi>.*?)",vol:"(?<vol>.*?)",strike:"(?<strike>.*?)",expiry:"(?<expiry>.*?)"}','names');
		% E.g. of put data: 
        % {cid:"545233775057295",name:"",s:"INTC141205P00024000",e:"OPRA",p:"-",c:"-",b:"-",a:"0.02",oi:"0",vol:"-",strike:"24.00",expiry:"Dec 5, 2014"}
        % {cid:"92955275286566",name:"",s:"INTC141205P00025000",e:"OPRA",p:"-",c:"-",b:"-",a:"0.02",oi:"0",vol:"-",strike:"25.00",expiry:"Dec 5, 2014"}

    tt = regexp(urlContract,'calls:\[(.*)\],underlying','tokens');
        % Note the ",underlying" to capture only the call data
    callsTT{tempi} = regexp(tt{1}{1},'{cid:"(?<cid>.*?)",name:"(?<name>.*?)",s:"(?<s>.*?)",e:"(?<e>.*?)",p:"(?<p>.*?)",c:"(?<c>.*?)",b:"(?<b>.*?)",a:"(?<a>.*?)",oi:"(?<oi>.*?)",vol:"(?<vol>.*?)",strike:"(?<strike>.*?)",expiry:"(?<expiry>.*?)"}','names');
        % E.g. of call data: 
        % {cid:"259510024302043",name:"",s:"INTC141205C00024000",e:"OPRA",p:"-",c:"-",b:"11.75",a:"13.50",oi:"0",vol:"-",strike:"24.00",expiry:"Dec 5, 2014"},
        % {cid:"141592700369825",name:"",s:"INTC141205C00025000",e:"OPRA",p:"-",c:"-",b:"10.75",a:"12.50",oi:"0",vol:"-",strike:"25.00",expiry:"Dec 5, 2014"},
end

out = [];
out.sym = symbolid;
out.time = timenow;
out.stockprice = stockprice;

data = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for tempi = 1:size(expiry,2)   % for all expiration times
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    data(tempi).expir = datetime(callsTT{tempi}(1).expiry);   % expiration as Matlab datetime

%%%%% CALLS:
    
    for tempj = 1:size(callsTT{tempi},2)  % for all contracts
    
      %  tt = regexp(callsTT{tempi}(tempj).p,'([-\.\d]+)"','tokens');
      %  if isempty(tt)
      %      price = callsTT{tempi}(tempj).p;
      %  else
      %      price = tt{1}{1};
      %  end
      %  % more data cleanup
      %  if strcmp(price,'-')
      %      price = nan;
      %  else
      %      price = str2num(strrep(price,',',''));
      %  end
      %  data{tempi}.cprice(tempj) = price;

        bid = callsTT{tempi}(tempj).b;
        % more data cleanup
        if strcmp(bid,'-')
            bid = nan;
        else
            bid = str2num(strrep(bid,',',''));
        end

        ask = callsTT{tempi}(tempj).a;
        % more data cleanup
        if strcmp(ask,'-')
            ask = nan;
        else
            ask = str2num(strrep(ask,',',''));
        end

        data(tempi).cprice(tempj) = (bid + ask)/2;
               
        strike = callsTT{tempi}(tempj).strike;
        % more data cleanup
        if strcmp(strike,'-')
            strike = nan;
        else
            strike = str2num(strrep(strike,',',''));
        end
        data(tempi).cstrike(tempj) = strike;
  
    end
    ind = ~isnan(data(tempi).cprice);
    data(tempi).cstrike = data(tempi).cstrike(ind);
    data(tempi).cprice = data(tempi).cprice(ind);
    
%%%%% PUTS:

    for tempj = 1:size(putsTT{tempi},2)

     %   tt = regexp(putsTT{tempi}(tempj).p,'([-\.\d]+)"','tokens');
     %   if isempty(tt)
     %       price = putsTT{tempi}(tempj).p;
     %   else
     %       price = tt{1}{1};
     %   end
     %   % more data cleanup
     %   if strcmp(price,'-')
     %       price = nan;
     %  else
     %       price = str2num(strrep(price,',',''));
     %   end
     %   data{tempi}.pprice(tempj) = price;

        bid = putsTT{tempi}(tempj).b;
        % more data cleanup
        if strcmp(bid,'-')
            bid = nan;
        else
            bid = str2num(strrep(bid,',',''));
        end

        ask = putsTT{tempi}(tempj).a;
        % more data cleanup
        if strcmp(ask,'-')
            ask = nan;
        else
            ask = str2num(strrep(ask,',',''));
        end

        data(tempi).pprice(tempj) = (bid + ask)/2;
               
        strike = putsTT{tempi}(tempj).strike;
        % more data cleanup
        if strcmp(strike,'-')
            strike = nan;
        else
            strike = str2num(strrep(strike,',',''));
        end
        data(tempi).pstrike(tempj) = strike;
       
    end
    ind = ~isnan(data(tempi).pprice);
    data(tempi).pstrike = data(tempi).pstrike(ind);
    data(tempi).pprice = data(tempi).pprice(ind);
    
end
out.opt = data;


