Principal Component Analysis As A Factor Model

Photo by the author

Introduction

Principal component analysis (PCA) is a statistical technique which enjoys applications in image processing and quantitative finance. In this article, we focus on the later application in quantitative trading, in particular using PCA as a multi-factor model of portfolio returns. We use the multi-factor model to design a momentum trading strategy, backtest it under different investment universes, and present the performance results.

The project is shared on my online repository https://github.com/DinodC/pca-factor-model.

Import packages

import numpy as np
import pandas as pd
import pickle
import statsmodels.api as sm
import matplotlib.pyplot as plt

Magic

%matplotlib inline

Data Collection

In this section, we collect S&P consittuents’ historical data from a previous project https://quant-trading.blog/2019/06/24/backtesting-a-trading-strategy-part-2/.

Set S&P Index keys

keys = ['sp500',
        'sp400',
        'sp600']

Initialize S&P indices close data

close = {}

Pull S&P indices close data

for i in keys: 
    # Load OHLCV data
    with open(i + '_data.pickle', 'rb') as f:
        data = pickle.load(f)

    # Update close prices data
    close[i] = data.close.loc['2014-06-12':]

    # Close file
    f.close

Inspect S&P 500 index constituents data

close['sp500'].head()
SymbolsAAALAAPAAPLABBV
date
2014-06-1239.772638.2958123.225284.586044.6031
2014-06-1339.840738.4672123.740783.660345.0187
2014-06-1639.718139.1150124.008684.503544.8857
2014-06-1740.092739.8867124.941184.393545.1351
2014-06-1840.365140.6392128.680984.485245.3595

5 rows × 505 columns

close['sp500'].tail()
SymbolsAAALAAPAAPLABBV
date
2019-06-0366.9927.20153.17173.3075.70
2019-06-0467.9529.12154.61179.6476.75
2019-06-0568.3530.36154.61182.5477.06
2019-06-0669.1630.38154.90185.2277.07
2019-06-0769.5230.92155.35190.1577.43

5 rows × 505 columns

close['sp500'].describe()
SymbolsAAALAAPAAPLABBV
count1257.0000001257.0000001257.0000001257.0000001257.000000
mean52.02038441.208459145.434801135.13343666.670458
std13.8680356.36871624.13110638.11763317.717831
min32.25860024.53980079.16870082.74380042.066600
25%39.39150036.574400132.526400103.63750053.175300
50%46.12340040.847900150.479700119.47620058.475100
75%65.60380046.127100161.921100167.85770082.898700
max81.94000057.586600199.159900229.392000116.445400

8 rows × 505 columns

close['sp500'].shape
(1257, 505)

Fill NaNs with previous observation

close['sp500'].fillna(method='ffill', inplace=True)
close['sp400'].fillna(method='ffill', inplace=True)
close['sp600'].fillna(method='ffill', inplace=True)

Initialize daily returns

returns = {}

Calculate daily returns

for i in keys:
    returns[i] = close[i].pct_change()

Momentum Strategy Implementation

In this section, we present the model (factor model) and tool (principal compenent analysis) used in implementing the momentum trading strategy.

1. Factor Models

Factor models use economic (e.g. interest rates), fundamental (e.g. price per earnings), and statistical (e.g. principal component analysis) factors to explain asset prices (and returns). Fama and French initially designed the three-factor model which extends the capital asset pricing model (CAPM) to include size and value factors. The general framework is known as the arbitrage pricing theory (APT) developed by Stephen Ross and proposes multiple factors.

2. Principal Component Analysis (PCA)

Principal component analysis is a statistical procedure for finding patterns in high dimension data. PCA allows you to compress high dimension data by reducing the number of dimensions, without losing much information. Principal component analysis has the following applications in quantitative finance: interest-rate modeling and portfolio analysis.

PCA implementation has the following steps:

  1. Pull data
  2. Adjust data by subtracting the mean
  3. Calculate the covariance matrix of the adjusted data
  4. Calculate the eigenvectors and eigenvalues of the covariance matrix
  5. Choose the most significant components which explain around 95% of the data

Note that in this article we are only interested in applying principal component analysis, for a complete illustration you can start by checking out https://en.wikipedia.org/wiki/Principal_component_analysis#Applications.

3. Momentum Trading Strategy

Momentum trading strategies profit from current market trends continuation. The momentum trading strategy proposed below assumes that factor returns have momentum. The idea is to long the winning (losing) stocks which have the highest (lowest) expected returns according to factors.

Before implementation, we set the following parameters:

  1. Lookback period
  2. Number of significant factors
  3. Number of winning and losing stocks to pick
lookback = 250
number_of_factors = 5
top_n = 50

Initialize the trading positions

positions = {}

for i in keys:
    # Update positions
    positions[i] = pd.DataFrame(np.zeros((returns[i].shape[0], returns[i].shape[1])),
                                 index=returns[i].index,
                                 columns=returns[i].columns
                                )

Implementation

for i in keys:
    for j in range(lookback + 1, len(close[i])):
        # Calculate the daily returns
        R = returns[i].iloc[j - lookback + 1:j, :]

        # Avoid daily returns with NaNs
        has_data = (R.count() == max(R.count()))
        has_data_list = list(R.columns[has_data])
        R = R.loc[:, has_data_list]

        # Calculate the mean of the daily returns
        R_mean = R.mean()

        # Calculate the adjusted daily returns
        R_adj = R.sub(R_mean)

        # Calculate the covariance matrix
        cov = R_adj.cov()

        # Calculate the eigenvalues (B) and eigenvectors (X)
        eigen = np.linalg.eig(cov)
        B = eigen[0]
        X = eigen[1]

        # Retain only a number of factors
        X = X[:, :number_of_factors]

        # OLS
        model = sm.OLS(R_adj.iloc[-1], X)
        results = model.fit()
        b = results.params

        # Calculate the expected returns
        R_exp = R_mean.add(np.matmul(X, b))

        # Momentum strategy
        shorts = R_exp.sort_values()[:top_n].index
        positions[i].iloc[j][shorts] = -1
        longs = R_exp.sort_values()[-top_n:].index
        positions[i].iloc[j][longs] = 1

Remarks:

  1. Investment universes used in backtesting are the S&P 500, S&P 400 MidCap and S&P 600 SmallCap indices.
  2. Ordinary least squares (OLS) method is used to calculate stocks’ expected returns from significant factors.
  3. Only a single stock is bought for each of the winning (losing) stocks, this could be improved by adjusting the number by the rank.

Performance Analysis

In this section, we present the performance of the momentum trading strategy based on principal component analysis.

Adjust the positions because we consider close prices

for i in keys:
    positions[i] = positions[i].shift(periods=1)

Calculate the daily PnL of the momentum strategy

pnl_strat = {}
avg_pnl_strat = {}

for i in keys:
    # Daily pnl
    pnl_strat[i] = (positions[i].mul(returns[i])).sum(axis='columns')
    # Annualized average pnl of the momentum strategy
    avg_pnl_strat[i] = pnl_strat[i].mean() * 250

Average daily PnL of momentum strategy using different investment universes i.e. S&P 500, S&P 400 and S&P 600 indices

pd.DataFrame(avg_pnl_strat,
            index=['Average PnL'],
            )
sp500sp400sp600
Average PnL-0.033961-0.491665-1.941058

Remark: the average daily pnl of the momentum strategy is negative regardless of the investment universe used.

Plot the cumulative PnL of the momentum trading strategy

# Set size
plt.figure(figsize=(20, 10))

for i in range(len(keys)):
    plt.plot(pnl_strat[keys[i]].cumsum())

plt.xlim(pnl_strat['sp500'].index[0], pnl_strat['sp500'].index[-1])
# plt.ylim(-10, 5)

# Set title and legend
plt.title('Cumulative PnL Of Momentum Trading Strategy')
plt.legend(keys)

Remarks:

  1. From July 2015 to January 2017, the momentum trading strategy generated negative PnL.
  2. From July 2017 to January 2019, the momentum trading strategy turned it around and generated positive PnL.
  3. From January 2019, the momentum trading strategy continuted to generate positive PnL for S&P 500 and S&P 400 MidCap indices only.

Conclusion

In this article, we implemented a momentum trading strategy based on principal component analysis. The momentum trading strategy generated positive PnL from July 2017 to January 2019, and negative PnL from July 2015 to July 2017. A way to enhance the current momentum trading strategy is to include exit and entry points depending on the expected profitability of the trading system.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s