This is my first notebook. My initial aims for this notebook is to import the last one years stock data for AAPL and plot the stock prices on a graph with 50d and 200d SMA. I will then add some EMA to the chart. This is all going to be practice for finding piviot points etc moving forward.
# Import our libraries
# This is for numerical processing
import numpy as np
import pandas as pd
# This is the library most commonly used for plotting in Python.
# Notice how we import it 'as' plt, this enables us to type plt
# rather than the full string every time.
import matplotlib.pyplot as plt
start = '2016-01-01'
end = '2016-10-12'
# set the dataframe to fetch APPL price from dates defined
#data = get_pricing(['AAPL'], start_date=start, end_date=end)
data = get_pricing('AAPL', start_date='2016-01-01', end_date='2016-10-12')
X = data['price']
X.tail()
So looks like we have some data in a dataframe. Now am going to try plot it on a line graph using matplotlib
plt.plot(X.index, X.values)
plt.ylabel('Price $')
plt.legend(['AAPL']);
Now I would like to define my moving averages and store them somewhere so I can try plot them also.
# LETS CHECK SOME VALUES OF X WHICH IS OUR PANDAS DATA FRAME OR TIME AND PRICE
np.mean(X)
np.std(X)
Now we need to define our moving averages and plot them on the same chart as the stock price.
# Take the average of the last 50 days at each timepoint.
SMA50D = pd.rolling_mean(X, window=50)
SMA100D = pd.rolling_mean(X, window=100)
# LETS CHECK OUTPUT
SMA50D.tail()
SMA100D
Now lets plot them on the same chart.
plt.plot(X.index, X.values)
plt.plot(SMA50D.index, SMA50D.values)
plt.plot(SMA100D.index, SMA100D.values)
plt.ylabel('Price')
plt.legend(['AAPL', '50d SMA', '100d SMA']);
Since we have SMA now it would be good to find out how to do EMA - so lets figure that out. From searching it seems we have to use the Ta-lib class to do this kind of stuff.
import talib
a = np.array([1.0,2,3,4,5])
talib.MA(a, 3)
# Seems Talib needs np array as input and outputs an array
# Output EMA in ARRAY FORMAT
EMA10_ARRAY = talib.EMA(X.values, 10)
EMA13_ARRAY = talib.EMA(X.values, 13)
EMA21_ARRAY = talib.EMA(X.values, 21)
# make 4D array
EMA_4D = {'Time' : X.index,
'EMA_10': EMA10_ARRAY,
'EMA_13': EMA13_ARRAY,
'EMA_21': EMA21_ARRAY}
# Make a pandas data frame to make plotting easier
df = pd.DataFrame(EMA_4D)
# Set index of df to be the timestamp
df.set_index('Time', inplace=True)
# Check outout
df.tail()
Now lets plot out EMA along with SP and SMA
plt.plot(X.index, X.values)
plt.plot(SMA50D.index, SMA50D.values)
plt.plot(SMA100D.index, SMA100D.values)
plt.plot(df.index, df.EMA_10)
plt.plot(df.index, df.EMA_13)
plt.plot(df.index, df.EMA_21)
plt.ylabel('Price')
plt.legend(['AAPL', '50d SMA', '100d SMA','10d EMA','13d EMA','21d EMA'], loc=2);