Plot Stock Prices
14 Jul 2006
07 Apr 2010)
Retrieves and plots historical stock prices
%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:
% To specify the number of 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.
num_days = 30;
% This is how we would get the latest quote, if we wanted it. The
% output would be a structure.
% d = fetch(y,symbol);
% Get historical prices
n = now;
% 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');
% Tidy up
% 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);
title(sprintf('%s: last %d days',symbol,num_days));
ylabel('Price at Close');