Make sure to have installed locally a comprehensive Python installation like the Anaconda Python distribution (code Python 3.6 tested).
Alternatively, and more easily, register on the Quant Platform where you can execute this Jupyter Notebook file in the browser. After registration, you find all Jupyter Notebook files of this course in the folder pffcourse
.
Working with Python in general requires you to import certain modules/packages from the standard library or from the so-called scientific or PyData stack (i.e. from third parties).
import numpy as np # array operations
import pandas as pd # time series management
from pylab import plt
plt.style.use('ggplot')
# put all plots in the notebook itself
%matplotlib inline
We retrieve end-of-day (EOD) price data for certain instruments (data source: Thomson Reuters Eikon API).
data = pd.read_csv('https://hilpisch.com/tr_eikon_eod_data.csv',
index_col=0, parse_dates=True)
The AAPL
object is of type DataFrame
.
type(data)
DataFrame
objects provide a wealth of (convenience) methods.
data.info() # meta information
Let us inspect the final five rows of the data set.
data.tail() # final five rows
You can easily select single or multiple columns of a DataFrame
object.
data['AAPL.O'].head() # first five rows of single column
data[['AAPL.O', 'MSFT.O']].tail() # last five rows of 2 columns
Similarly, you can select single or multiple rows.
data.loc['2017-10-06'] # single row via index value
data.iloc[:2] # two rows via index numbers
There is also a powerful method for plotting.
data['AAPL.O'].plot(figsize=(10, 6));
Let us calculate the Apple stock price log returns.
# fully vectorized operation for log return calculation
rets = np.log(data['AAPL.O'] / data['AAPL.O'].shift(1))
The log returns can then be visualized via a histogram.
rets.hist(figsize=(10, 6), bins=35);
pandas provides, among others, convenience functions for the calculation of moving averages.
# fully vectorized calculation of 50 days moving average/trend
data['MA50'] = data['AAPL.O'].rolling(50).mean()
data[['AAPL.O', 'MA50']].plot(figsize=(10, 6));
This closes the first module of the Python for Finance email course. In this module, you have learned:
DataFrame
objectDataFrame
objectDataFrame
objectDataFrame
objects (log returns, moving average)What you have learned today builds the basis for many important use cases for Python in Finance.
In order to master the material of this module, do the following:
MSFT.O
or .SPX
.rolling(window=X).std()
or .rolling(window=X).max()
You find background information for the topics covered in this module in the following books:
http://tpq.io | @dyjh | team@tpq.io
Quant Platform | http://quant-platform.com
Python for Finance | Python for Finance @ O'Reilly
Derivatives Analytics with Python | Derivatives Analytics @ Wiley Finance
Listed Volatility and Variance Derivatives | Listed VV Derivatives @ Wiley Finance