function plot_prices(symbol,num_days)
%PLOT_PRICES - Plots a stock price over a specified number of days
%
% To plot the closing price for the specified stock symbol for the last 30 days:
% plot_prices(symbol)
%
% To specify the number of days:
% plot_prices(symbol,num_days)
%
% Uses the Yahoo service, since it doesn't require a subscription or any
% special software.
% Copyright 2006-2010 The MathWorks, Inc.
% Open a connection to the Yahoo service.
y = yahoo;
% Assign the default number of days if necessary.
if nargin<2
num_days = 30;
end
% This is how we would get the latest quote, if we wanted it. The
% output would be a structure.
% try
% d = fetch(y,symbol);
% catch
% close(y);
% rethrow(lasterror);
% end
% Get historical prices
n = now;
try
% Use the form of the "fetch" function which takes inputs:
% data = fetch(connection,symbol,from_date,to_date,period);
% We want daily prices, starting now and finishing the specified number of
% days ago. This might seem like it's going to give us our results in
% reverse order, but it's not. The dates can be in any format recognised
% by datenum. Use datestr to create something recognisable.
d = fetch(y,symbol,'Close',datestr(n),datestr(n-num_days),'d');
catch E
close(y);
rethrow(E);
end
% Tidy up
close(y);
% We only requested one output (the closing price), so the data has two columns:
% date, closing price.
% The date is in the same (numeric) format as returned by "now". Get the number of days
% ago by subtracting the current date and rounding up. If you do this after
% the market has closed, you'll get an entry for today (days_ago = 1). Otherwise,
% the most recent entry will be for yesterday (-1).
days_ago = ceil(d(:,1) - n);
close_price = d(:,2);
% Plot
plot(days_ago,close_price);
title(sprintf('%s: last %d days',symbol,num_days));
xlim([-num_days,0]);
xlabel('Days');
ylabel('Price at Close');