Plot closing values of the three popular stock indices Dax, TecDax and Nikkei 225 over the last 15 years. The historical data is available at Yahoo Finance can be downloaded using the pre-defined helper function get_data_from_yahoo
.
Plot all three indices into one figure
Add a legend, a title and axis labels to the figure (Tip: You can use the pre-defined index_map dictionary to map Yahoo Names into human-readable format)
How do the three indices differ, what do they have in common
Try to use matplotlib finance instead of the predefined helper function (Additional exercise)
#Pre-defined environment, please do not change
from datetime import datetime, date
from matplotlib import pyplot as plt
import numpy as np
import csv
import contextlib
import urllib2
%matplotlib inline
#index map to map Yahoo Names into human-readble format
index_map = {'%5EGDAXI': 'DAX',
'%5ETECDAX': 'TECDAX',
'^N225': 'Nikkei 225'}
def get_data_from_yahoo(index):
"""Helper function to download quotes from Yahoo:
returns a dictionary {'index_name': [{'{'Volume': ...,
'Adj Close': ...,
'High': ...,
'Low': ...,
'Date': ...,
'Close': ...,
'Open': ...}, ...]}
"""
url = 'http://ichart.yahoo.com/table.csv?s=%s&a=0&b=1&c=2000&d=11&e=31&f=2015&g=d&ignore=.csv' % (index)
with contextlib.closing(urllib2.urlopen(url)) as f:
fieldnames = f.readline().strip().split(',')
my_csv_reader = csv.DictReader(f, fieldnames=fieldnames, delimiter=',')
quotes = {index:[row for row in my_csv_reader]}
return quotes
for index in index_map:
quotes = get_data_from_yahoo(index)
"""
Write your code here, please!
"""
dates = np.array([datetime.strptime(entry['Date'], '%Y-%m-%d') for entry in quotes[index]])
close_values = np.array([entry['Close'] for entry in quotes[index]])
plt.plot_date(dates, close_values, '-', label=index_map[index])
plt.legend()
plt.title('Three popular stock indices over last 15 years')
plt.xlabel('Year')
plt.ylabel('Index Value')
<matplotlib.text.Text at 0x1074d1450>