Sitemap
John Bilsel

John Bilsel

Factor Portfolio Construction — Python

5 min readJun 9, 2023

In quantitative finance, a typical technique used for testing the effectiveness of a signal or a “factor” is constructing long-short portfolios. This refers to going long a basket of securities that rank the highest based on signal “X”, and going short a basket which rank the lowest based on the same signal. Within this process, it’s also common to see the respective portfolios (highest ranked to lowest ranked) split into quintiles or deciles to compare how the securities in the middle (not super exposed/not exposed to signal “X”).

This week’s tutorial focuses on translating theoretical concepts like factor portfolio construction into practical implementation using Python. We’ll delve into a widely studied factor called “Momentum” and explore how to sort stocks based on their 12-month cumulative return. As this blog emphasizes the practical applications of common techniques in empirical finance, we’ll primarily focus on the implementation rather than delving into the detailed intuition behind Momentum’s effectiveness or the strategy’s limitations and intricacies. By the end of this tutorial, you’ll gain hands-on experience in applying Momentum to construct factor portfolios, enabling you to further explore and analyze this strategy’s potential in your investment endeavors.

In this example we look at the underlying companies on the ASX 200, and use the ‘pd.read_html’ function from pandas to extract the tickers of the companies:

import pandas as pd
import numpy as np
import yfinance as yf
import math
import hvplot.pandas
import holoviews as hv
hv.extension('bokeh')

# [1] is used to select the specific table needed from the Wikipedia website
asx_data = pd.read_html('https://en.wikipedia.org/wiki/S%26P/ASX_200')[1]

# Put tickers into a list
tickers = asx_data['Code'].to_list()

“tickers” is now a list of company tickers on the ASX 200, which we can put into the yahoo finance API call to extract their “Adjusted Close” prices.

# Only need the ['Adj Close']
prices = yf.download(tickers,start='2005-01-01', end='2023-05-31')['Adj Close']

# Change to datetime
prices.index = pd.to_datetime(prices.index)

# Convert from daily to monthly prices using 'M'
prices_monthly = prices.resample('M').last()

# Drop the columns with insufficient data
prices_monthly_clean = prices_monthly.dropna(axis=1)

Following this, you should have a data frame of prices that looks like this:

Press enter or click to view image in full size

Now that we have our prices, we need to:

(1) Create a data frame of the “Signal” — 12-month cumulative returns for each stock

(2) Calculate monthly returns of every stock, to later calculate portfolio returns (log return is also very common)

# Use "shift() to move the dataframe up and down relate to the index
momentum_12 = (prices_monthly_clean/prices_monthly_clean.shift(12))-1
monthly_returns = (prices_monthly_clean/prices_monthly_clean.shift(1))-1.

# Drop the 1 or 2 rows with NA's
momentum_12 = momentum_12.dropna(axis=0)
monthly_returns = monthly_returns.dropna(axis=0)

We can now begin to create “ranks” for the stocks each month. In this example, we will form 5 portfolios each month based on their ranking from highest to lowest of their 12-month cumulative return (momentum signal).

“pd.qcut” simply cuts the ranked values into however many groups you want e.g. q=5

# Establish a df for the ranks
quintile_ranks = pd.DataFrame(index=momentum_12.index, columns=momentum_12.columns)

# Place each stock in a "quintile" bucket, at each "date" (rows)
for date in momentum_12.index:
row_values = momentum_12.loc[date] # looping values each row
ranks = pd.Series(row_values).rank(method='max') # set rank at each row
quintiles = pd.qcut(ranks, q=5, labels=False) # divide into quintiles

# Create dataframe with ranks for each stock at each month(4=high, 0=low)
quintile_ranks.loc[date] = quintiles

At this point, the data frame “quintile_ranks” contains the a the quintile (0–4) of each stock at each point in time.

Get John Bilsel’s stories in your inbox

Join Medium for free to get updates from this writer.

The final step is to calculate the quintile portfolio returns and find out whether stocks that have a high 12-month cumulative return earn excess return over stocks with a low 12-month cumulative return.

We assume an ‘equal-weight’ approach within each quintile, and to do this we simply take df.mean(axis=1).

quintile_dfs = {} 
portfolio_returns = pd.DataFrame()

# Iterate for each quintile, and form portfolios accordingly
for quintile in range(5):

# Only take returns if they're in quintile associated with the current loop.
filtered_df = monthly_returns[quintile_ranks == quintile]

# shift to "t+1" return as rank at time "t" corresponds to return at time "t+1"
filtered_df_shifted = filtered_df.shift(-1).dropna(axis=0)

# Put those returns into dictionairy "quintile_dfs"
quintile_dfs[quintile] = filtered_df_shifted

#For Equal-Weight, simply take the average return across stocks within each quintile dataframe
portfolio_returns[quintile] = quintile_dfs[quintile].mean(axis=1).dropna()


# Plot the cumulative return
(1+portfolio_returns).cumprod().hvplot(title = 'Portfolios - Log Scale', height = 300, width= 500, grid=True, logy=True)
Log-Scaled Cumulative Returns

As seen above, the “4” portfolio, which contains the securities with the highest momentum at each month significantly outperforms the rest over approximately ~ 18 years. Though, a huge portion of a “long-short” between the highest and the lowest would actually be coming from the “low momentum” stocks given their very poor performance. Subtracting returns of the (4) and (0) would give you a market-neutral factor portfolio (no equity beta).

To tie this all together in a cleaner form, we can look at the risk-adjusted returns of these 5 portfolios using a simple Annualized Return / Annualized Volatility calculation:

# Calculate Ann Return
cumulative_return = (1 + portfolio_returns).prod() - 1
num_periods = len(monthly_returns)
annualized_return = (1 + cumulative_return) ** (12 / num_periods) - 1

# Calculate Ann Vol
ann_vol = portfolio_returns.std()*math.sqrt(12)

# Calculate Risk-adjusted-return
risk_adj_return = annualized_return/ann_vol
risk_adj_return.hvplot(kind='bar',title = 'Quintile Momentum portfolio - Risk Adjusted Return', height = 300, width= 500, grid=True, color = 'teal')
0 (Lowest Momentum) to 4 (Highest Momentum) stocks

It’s clear that as you start to get more exposure to “high momentum stocks” in our sample, you achieved a higher risk-adjusted return historically.

A very important note about this process is the inherent biases and errors that may be caused when constructing these to evaluate the validity of a particular “signal”.

Important Biases and Considerations

(i) We run into survivorship-bias in this example, as we dropped the “stocks” (columns) that did not have enough data back to 2005, and didn’t include stocks that may have been de-listed from the ASX 200.

(ii) The testing period perhaps was not long enough, and should be rigioursly assessed across many samples for true robustness.

(iii) Arguably the most important is “trading-costs”. Momentum is traditionally a “fast-moving signal”, which means the portfolio turns over quite a lot. This test above does not account for the transaction costs associated with turning a portfolio over each month, and hence the return is higher than it otherwise would be.

Overall, this task was more to demonstrate the practical application in Python of long-short portfolios and less about the nuances and weeds of the process / technique.

Feel free to reach out on LinkedIn for any questions or to discuss Python for Quantitative Finance:

https://www.linkedin.com/in/john-bilsel-444471163/

--

--