Python for Investing
Learn Python from the beginning using financial examples. The lessons progress from storing prices and calculating returns to working with market data and testing investment strategies.
What is a variable?
Name a price, a ticker and a share count, then value a position and a three-stock portfolio.
How do I do maths and print a result?
Do arithmetic in Python and print the result with an f-string.
What is True and False?
Compare two numbers, store the answer, and build a buy rule out of it.
What is a list?
Hold many values under one name, count them, pick them out by position, and add new ones.
How do I slice a list?
Slice a list with x[start:stop], and turn the last few closes into a moving average.
What is a for loop?
Run the same lines once for every item in a list, and add the results up as you go.
What are if, elif and else?
Pick one outcome with if, elif and else, and see how the order of the tests decides which one you get.
How do I turn prices into returns?
Build a list of returns in a loop, then compound them into the return for the whole stretch.
What is a function?
Give a calculation a name with def, feed it inputs, and get an answer back.
What is a dictionary?
Map a key to a value, look it up by name, and use two dictionaries keyed by ticker to value a portfolio.
What is a class?
Write your own class, build two objects from it, and read what self means on every line.
What is a numpy array?
Hold many numbers in one array and do maths on all of them at once, without writing a loop.
How do I filter with a condition?
Turn a comparison into an array of True and False, use it to select elements, count them, and switch it into a position of 1 or 0.
What is a pandas Series?
Build a Series of closes, select by label and by position, and see arithmetic line up two price series on their dates.
What is a DataFrame?
Build a table from a dictionary of lists, select columns from it, add a computed column, sort it, and filter its rows.
How do I load a CSV file?
Read a CSV into a DataFrame with pd.read_csv, parse the dates, and index the rows by date.
How do I compute returns in pandas?
Turn a column of prices into a column of returns with pct_change, and handle the NaN it leaves in the first row.
Why is an array operation faster than a loop?
Time a Python loop against the same calculation written as one array operation, and see where the gap comes from.
What is a moving average?
Take the mean of the last n values at every row with .rolling(n).mean(), and put a 5-day and a 10-day average on a price column.
How do I use yesterday's value?
Move a column down one row with .shift(1) so every row can read the row above it.
How do I build an equity curve?
Turn a column of returns into the growth of one unit of money with (1 + r).cumprod().
How do I do the same thing per ticker?
Split a stacked table into one group per ticker, run a calculation inside each group, and get the answers back.
How do I stack two tables?
Glue DataFrames together with pd.concat, top to bottom by default and side by side with axis=1.
How do I join two tables on a key?
Line two tables up on a shared column with pd.merge, and choose which rows survive with inner, left, right and outer.
What is a panel?
Put a date and a ticker in the index, pull out one date or one ticker, and switch between the long and wide shapes.