Greetings! You’ve arrived here most likely because you’ve just realized that you’ve been Wasting Your Talents at your job using Matlab to research new medicines, design fuel-efficient engines, or develop next-generation wireless communication technologies when – duh! – you could put those Matlab skills to much better, MUCH better use turning the stock market into your own ATM. From your boat!
Well here it is – the gateway drug – a few simple lines of code that will let you download Yahoo’s free historical stock price data right into Matlab. Then you’re on your own as to what to do with it, but I’ll bet you’ve learned quite a bit of signal processing mojo over the years that you’re salivating to put to good use: particle filters, neural networks, wavelet transforms, …maybe even Viterbi decoders!
Assuming you already speak Matlab well, there are really just a handful of new things to learn.
First, it might help to know exactly where to download from. Yahoo Finance provides a convenient historical data CSV file for each stock currently trading. Type in any ticker, click on Historical Prices, and scroll down to the bottom…
Tricky Move #1 is to crack the URL genome so that you can generate your own URL on the fly. The URLs looks like this:
With a little (VERY little) trial & error, you might come to discover that after s= goes the ticker symbol, after a= the start month (minus 1), after b= the start day, c= the start year and so on. The final g= parameter lets you choose between getting historical stock information on a daily, weekly, or monthly basis. Construct your desired URL as a Matlab character string (let’s call it url_string).
Tricky Move #2 is to tunnel your way directly to a webpage from within Matlab, no browser required! This is done via Matlab’s java interface and your URL string like so:
Tricky Move #3 is to use that connection to read in the individual lines of the webpage’s source code into a buffer.
It’s really no harder than that – just put that last tidbit in a while loop and parse the buffer each time around to grab the data and store it in a matrix. It’s especially easy here since we’re working with CSV. Parsing HTML from other websites is a little trickier, but I’ll bet you’ll graduate quickly (gateway drug, I tell you).
Still sound too hard? OK, just click below to download my source code for free. See you in St. Maarten!