LSESU Applicable Maths Give It A Go Python Demo

This is some slightly more advanced Python to what we will do in the first 2 weeks.

By the end of the course you will be able to do all of this and more!

Demo 1: Plotting the closing price and volatility of a stock in 5 lines

First we have to import some "libraries", which is a fancy way of saying using something someone else already wrote


In [ ]:
# -*- coding: utf-8 -*-
%matplotlib inline
import numpy as np
import pandas as pd
from pandas_datareader import data as web
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.finance as mpf

In [ ]:
# Choose a stock
ticker = 'GOOG'

# Choose a start date in US format MM/DD/YYYY
stock_start = '10/2/2014'
# Choose an end date in US format MM/DD/YYYY
stock_end = '10/2/2016'

# Retrieve the Data from Google's Finance Database
stock = web.DataReader(ticker,data_source='google',
                       start = stock_start,end=stock_end)

# Print a table of the Data to see what we have just fetched
stock.tail()

In [ ]:
# Generate the logarithm of the ratio between each days closing price
stock['Log_Ret'] = np.log(stock['Close']/stock['Close'].shift(1))

# Generate the rolling standard deviation across the time series data
stock['Volatility'] = pd.rolling_std(stock['Log_Ret'],window=100)*np.sqrt(100)

In [ ]:
# Create a plot of changing Closing Price and Volatility
stock[['Close','Volatility']].plot(subplots=True,color='b',figsize=(8,6))

Demo 2: Plotting a candlestick chart for any stock in 11 lines of code


In [ ]:
# Choose a start and end date in a slightly different format to before (YYYY/MM/DD)
start = (2015, 10, 2)
end = (2016, 4,2)
company = "S&P 500"
ticker = "^GSPC"
quotes = mpf.quotes_historical_yahoo_ohlc(ticker, start, end)
print(quotes[:2])

In [ ]:
# We use Matplotlib to generate plots

fig, ax = plt.subplots(figsize=(8, 5))
fig.subplots_adjust(bottom=0.2)
mpf.candlestick_ohlc(ax, quotes, width=0.6, colorup='b', colordown='r')
# Running this block produces an ugly output

In [ ]:
# We can try again with some fancier formatting tricks

fig, ax = plt.subplots(figsize=(8, 5))
fig.subplots_adjust(bottom=0.2)

mpf.candlestick_ohlc(ax, quotes, width=0.6, colorup='b', colordown='r')

# Adding some formatting sugar
plt.title("Candlestick Chart for "+company+" ("+ticker+")"+" "+str(start)+" to "+str(end))
plt.grid(True) # Set a title
ax.xaxis_date() # dates on the x-axis
ax.autoscale_view() #Scale the image
plt.setp(plt.gca().get_xticklabels(), rotation=30) # Format labels

Complete Code for Demo 1


In [ ]:
# -*- coding: utf-8 -*-
%matplotlib inline
import numpy as np
import pandas as pd
from pandas_datareader import data as web

# Choose a stock
ticker = 'GOOG'

# Choose a start date in US format MM/DD/YYYY
stock_start = '10/2/2015'
# Choose an end date in US format MM/DD/YYYY
stock_end = '10/2/2016'

# Retrieve the Data from Google's Finance Database
stock = web.DataReader(ticker,data_source='google',
                       start = stock_start,end=stock_end)

# Generate the logarithm of the ratio between each days closing price
stock['Log_Ret'] = np.log(stock['Close']/stock['Close'].shift(1))

# Generate the rolling standard deviation across the time series data
stock['Volatility'] = pd.rolling_std(stock['Log_Ret'],window=252)*np.sqrt(252)

google[['Close','Volatility']].plot(subplots=True,color='b',figsize=(8,6))

Complete Code for Demo 2


In [ ]:
# -*- coding: utf-8 -*-
%matplotlib inline
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.finance as mpf

start = (2015, 10, 2)
end = (2016, 4,2)
company = "S&P 500"
ticker = "^GSPC"
quotes = mpf.quotes_historical_yahoo_ohlc(ticker, start, end)
print(quotes[:2])

fig, ax = plt.subplots(figsize=(8, 5))
fig.subplots_adjust(bottom=0.2)

mpf.candlestick_ohlc(ax, quotes, width=0.6, colorup='b', colordown='r')

plt.title("Candlestick Chart for "+company+" ("+ticker+")"+" "+str(start)+" to "+str(end))
plt.grid(True) # Set a title
ax.xaxis_date() # dates on the x-axis
ax.autoscale_view() #Scale the image
plt.setp(plt.gca().get_xticklabels(), rotation=30) # Format labels

Demos from Python In Finance


In [ ]: