In [2]:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pandas_datareader.data as web
from datetime import datetime
%matplotlib inline

In [179]:
# set dates
end = datetime.now()
start = datetime(end.year-2, end.month, end.day)

1. Import Stock Data from Yahoo Finance


In [160]:
CMT = web.DataReader("C38U.SI", 'yahoo', start, end)
CMT.head(2)


Out[160]:
Open High Low Close Volume Adj Close
Date
2015-02-12 2.15 2.16 2.10 2.11 9178700 1.894
2015-02-13 2.10 2.12 2.08 2.11 6409100 1.894

2. Plot the Daily Closing Price of a Stock


In [180]:
CMT['Adj Close'].plot(legend=True, figsize=(10, 5), \
                      title='CapitaMall Trust', \
                      label='Adjusted Closing Price')


Out[180]:
<matplotlib.axes._subplots.AxesSubplot at 0x14ae50c10>

3. Plot the Daily Closing Price and Volume of a Stock


In [182]:
plt.figure(figsize=(10,5))
top = plt.subplot2grid((4,4), (0, 0), rowspan=3, colspan=4)
bottom = plt.subplot2grid((4,4), (3,0), rowspan=1, colspan=4)
top.plot(CMT.index, CMT['Adj Close'])
bottom.bar(CMT.index, CMT['Volume'])

# set the labels
top.axes.get_xaxis().set_visible(False)
top.set_title('CapitalMall Trust')
top.set_ylabel('Adj Closing Price')
bottom.set_ylabel('Volume')


Out[182]:
<matplotlib.text.Text at 0x14cf5e250>

4. Plot a Histogram of the Daily Closing Price


In [165]:
# plot a histogram with closing price
plt.figure(figsize=(10,5))
sns.distplot(CMT['Adj Close'].dropna(), bins=20, color='purple')


Out[165]:
<matplotlib.axes._subplots.AxesSubplot at 0x14856ab90>

In [231]:
# plot a boxplot to see the interquantile range.
q25 = round(CMT['Adj Close'].quantile(0.25),2)
q75 = round(CMT['Adj Close'].quantile(0.75),2)

sns.boxplot(CMT['Adj Close'].dropna(), orient='v')
plt.text(0.04,2.1,'Interquantile Range: {}-{}'.format(q25,q75))


Out[231]:
<matplotlib.text.Text at 0x14c1db590>

5. Chart using Simple Moving Average


In [152]:
# simple moving averages
sma10 = CMT['Close'].rolling(10).mean() #10 days
sma20 = CMT['Close'].rolling(20).mean() #20 days
sma50 = CMT['Close'].rolling(50).mean() #50 days

CMTsma = pd.DataFrame({'CMT': CMT['Close'], 'SMA 10': sma10, 'SMA 20': sma20, 'SMA 50': sma50})
CMTsma.plot(figsize=(10, 5), legend=True, title='CapitaMall Trust')

# add vertical lines with annotations
plt.axvline(x = '2015-11-3', color = "black", lw=0.5)
plt.text('2015-10-23', 2.25, 'SMA 10-20',rotation=90)
plt.axvline(x = '2015-11-20', color = "black", lw=0.5)
plt.text('2015-11-24', 2.25, 'SMA 10-50',rotation=90)


Out[152]:
<matplotlib.text.Text at 0x1474cd050>