Using Apache Spark to Find Stock High
Suppose you have stock market data from Yahoo! for AAPL from http://finance.yahoo.com/q/hp?s=AAPL+Historical+Prices. The data is in CSV format and has these values.
Date Open High Low Close Volume Adj Close ---- ---- ---- --- ----- ------ --------- 11-18-2014 113.94 115.69 113.89 115.47 44,200,300 115.47 11-17-2014 114.27 117.28 113.30 113.99 46,746,700 113.99
Here is what the CSV looks like:
csv = [ "#Date,Open,High,Low,Close,Volume,Adj Close\n", "2014-11-18,113.94,115.69,113.89,115.47,44200300,115.47\n", "2014-11-17,114.27,117.28,113.30,113.99,46746700,113.99\n", ]
Lets find the date on which the price was the highest.
Question: What two fields would you need to extract?
We want to use Adj Close instead of High so our calculation is not affected by stock splits.
Question: What field would need to be the key?
Question: What are the sequence of operations that you would need to perform.
Use textFile to read the file.
Use filter to remove the header line.
Use map to split each row into fields.
Use map to extract Adj Close and Date.
Use sortByKey(false) to sort descending on Adj Close.
Use take(1) to get the highest value.
csv = [ "#Date,Open,High,Low,Close,Volume,Adj Close\n", "2014-11-18,113.94,115.69,113.89,115.47,44200300,115.47\n", "2014-11-17,114.27,117.28,113.30,113.99,46746700,113.99\n", ] sc.parallelize(csv) \ .filter(lambda line: not line.startswith("#")) \ .map(lambda line: line.split(",")) \ .map(lambda fields: (float(fields[-1]),fields[0])) \ .sortByKey(False) \ .take(1)
Here is the program for finding the high of any stock.
import urllib2 import re def get_stock_high(symbol): url = 'http://real-chart.finance.yahoo.com' + \ '/table.csv?s='+symbol+'&g=d&ignore=.csv' csv = urllib2.urlopen(url).read() csv_lines = csv.split('\n') stock_rdd = sc.parallelize(csv_lines) \ .filter(lambda line: re.match(r'\d', line)) \ .map(lambda line: line.split(",")) \ .map(lambda fields: (float(fields[-1]),fields[0])) \ .sortByKey(False) return stock_rdd.take(1) get_stock_high('AAPL')