Ranking Universes by Factors

By Delaney Granizo-Mackenzie

Part of the Quantopian Lecture Series:

Notebook released under the Creative Commons Attribution 4.0 License. Please do not remove this attribution.

One common technique in quantitative finance is that of ranking stocks in some way. This ranking can be whatever you come up with, but will often be a combination of fundamental factors and price-based signals. One example could be the following

  1. Score stocks based on 0.5 x the PE Ratio of that stock + 0.5 x the 30 day price momentum
  2. Rank stocks based on that score

These ranking systems can be used to construct long-short equity strategies. The Long-Short Equity Lecture is recommended reading before this Lecture.

In order to develop a good ranking system, we need to first understand how to evaluate ranking systems. We will show a demo here.

WARNING:

This notebook does analysis over thousands of equities and hundreds of timepoints. The resulting memory usage can crash the research server if you are running other notebooks. Please shut down other notebooks in the main research menu before running this notebook. You can tell if other notebooks are running by checking the color of the notebook symbol. Green indicates running, grey indicates not.


In [1]:
import numpy as np
import statsmodels.api as sm
import scipy.stats as stats
import scipy
from statsmodels import regression
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

Getting Data

The first thing we're gonna do is get monthly values for the PE Ratio and Market Cap for every equity. This can take a while.


In [2]:
start_date = '2012-01-01'
end_date = '2015-01-01'

# Get market cap and book-to-price for all assets in universe
fundamentals = init_fundamentals()
# WARNING: The following line will take a while to run, as it is fetching a large amount of data.
pe_data = get_fundamentals(query(fundamentals.valuation_ratios.pe_ratio), end_date, range_specifier='36m')
pe_data = pe_data['pe_ratio'].T.dropna()

cap_data = get_fundamentals(query(fundamentals.valuation.market_cap), end_date, range_specifier='36m')
cap_data = cap_data['market_cap'].T.dropna()

Let's take a look at the data to get a quick sense of what we have.


In [3]:
pe_data.head(5)


Out[3]:
algo_date 2012-02-01 00:00:00+00:00 2012-03-01 00:00:00+00:00 2012-04-02 00:00:00+00:00 2012-05-01 00:00:00+00:00 2012-06-01 00:00:00+00:00 2012-07-02 00:00:00+00:00 2012-08-01 00:00:00+00:00 2012-09-04 00:00:00+00:00 2012-10-01 00:00:00+00:00 2012-11-01 00:00:00+00:00 ... 2014-04-01 00:00:00+00:00 2014-05-01 00:00:00+00:00 2014-06-02 00:00:00+00:00 2014-07-01 00:00:00+00:00 2014-08-01 00:00:00+00:00 2014-08-29 00:00:00+00:00 2014-10-01 00:00:00+00:00 2014-11-03 00:00:00+00:00 2014-11-26 00:00:00+00:00 2015-01-02 00:00:00+00:00
security
Equity(2 [AA]) 15.7233 18.4843 18.4843 29.2398 28.4091 24.9377 136.9863 133.3333 135.1351 135.1351 ... 35.2113 35.2113 35.2113 35.2113 35.2113 35.2113 35.2113 35.2113 35.2113 35.2113
Equity(21 [AAME]) 15.7729 16.2602 21.3675 15.9490 16.2866 15.3610 13.1234 13.1234 13.1234 14.9254 ... 8.5543 7.9554 7.6511 8.6133 8.9445 16.3666 15.9206 15.7573 19.7281 20.2962
Equity(24 [AAPL]) 11.5207 12.9870 15.4321 14.5985 14.2248 14.0845 13.7174 14.3472 15.6250 15.1057 ... 13.0719 12.8700 14.1443 15.4321 15.8479 16.4745 16.2554 16.5781 18.3827 17.4367
Equity(31 [ABAX]) 53.4759 52.3560 51.2821 50.0000 60.9756 56.1798 59.8802 57.8035 60.6061 34.1297 ... 50.0000 51.2821 53.4759 70.4225 75.7576 68.0272 73.2627 74.2863 73.2964 76.7407
Equity(52 [ABM]) 16.2338 16.2338 17.3611 18.5874 18.5874 17.0648 15.5521 15.5521 20.7900 19.4553 ... 21.9780 22.3714 21.0526 22.1239 20.7039 21.8341 20.7549 21.7123 21.6886 21.8808

5 rows × 36 columns

The next step is to figure out which equities we have data for. Data sources are never perfect, and stocks go in and out of existence with Mergers, Acquisitions, and Bankruptcies. We'll make a list of the stocks common to both our factor data sets and then filter down both to just those stocks.

We'll also get the daily pricing of all stocks over the same time period. Finally, we'll filter down one more time to just look at stocks which have data from all three sources.


In [4]:
# There will be some equities for which we had no data, so look at the set for which we have data
common_equities = cap_data.index.intersection(pe_data.index)

# Get the prices on only the common equities
# WARNING: The following line will take a while to run, as it is fetching a large amount of data.
prices = get_pricing(common_equities, start_date=start_date, end_date=end_date, frequency='daily')
prices = prices['price']

# Drop any that have no price data
prices = prices.T.dropna().T
common_equities = prices.T.index

# Filter the fundamental data down to only the equities that have price data
cap_data_filtered = cap_data.T[common_equities]
pe_data_filtered = pe_data.T[common_equities]

Now we want to compute the forward 30 day returns for each month. We do this by dividing the price on the last day of the month by the price on the first day of the month. Pandas has a nice function groupby, which can accomplish this for us fairly elegantly.


In [5]:
monthly_prices = prices.groupby((prices.index.year, prices.index.month))
month_forward_returns = monthly_prices.last() / monthly_prices.first() - 1

Let's take a look to see what we have.


In [6]:
month_forward_returns.T.head(5)


Out[6]:
2012 ... 2014
1 2 3 4 5 6 7 8 9 10 ... 3 4 5 6 7 8 9 10 11 12
Equity(2 [AA]) 0.101842 -0.003918 -0.024366 -0.043756 -0.142570 0.054282 -0.019699 0.014218 0.051008 -0.037037 ... 0.107666 0.033768 -0.002933 0.075145 0.108181 0.009726 -0.033593 0.066879 0.020661 -0.078180
Equity(24 [AAPL]) 0.110387 0.188934 0.101422 -0.055982 -0.007912 0.040884 0.030446 0.096202 -0.011206 -0.097761 ... 0.017044 0.089155 0.070431 0.035328 0.022027 0.066192 -0.024685 0.088517 0.087310 -0.040671
Equity(31 [ABAX]) -0.040397 -0.038085 0.100529 0.208347 -0.073550 0.169085 -0.083205 0.047486 -0.061438 -0.029303 ... 0.028359 0.026050 0.008293 0.059034 0.029974 0.016592 0.044284 0.024319 0.083223 0.011752
Equity(52 [ABM]) 0.039770 0.013845 0.057441 -0.041581 -0.057507 -0.045876 -0.034286 0.112211 -0.056801 0.002641 ... 0.018059 -0.059681 0.015642 -0.014609 -0.094555 0.083096 -0.039626 0.096467 -0.006965 0.061921
Equity(62 [ABT]) -0.045294 0.043286 0.068730 0.013380 -0.007386 0.064472 0.026174 -0.008474 0.047356 -0.051909 ... -0.020844 0.007540 0.034394 0.027136 0.022702 0.004638 -0.014918 0.057795 0.028182 0.015792

5 rows × 36 columns

Let's take a look at the market cap data.


In [7]:
cap_data_filtered.head(5)


Out[7]:
security Equity(2 [AA]) Equity(24 [AAPL]) Equity(31 [ABAX]) Equity(52 [ABM]) Equity(62 [ABT]) Equity(64 [ABX]) Equity(66 [AB]) Equity(67 [ADSK]) Equity(69 [ACAT]) Equity(76 [TAP]) ... Equity(42165 [INVN]) Equity(42173 [DLPH]) Equity(42230 [TRIP]) Equity(42247 [MEMP]) Equity(42262 [GZT]) Equity(42263 [LPI]) Equity(42264 [SN]) Equity(42270 [KORS]) Equity(42272 [BCEI]) Equity(42275 [MCEP])
algo_date
2012-02-01 00:00:00+00:00 9207164370 3.775467e+11 600106960 1100149396 42250355869 45269107265 1375667313 6878844000 279042990 7837200000 ... 790053962 7070386745 3364572154 398161484 1557559489 2845867819 569580000 5206111083 493469800 323694000
2012-03-01 00:00:00+00:00 10814426590 4.256083e+11 587311040 1100149396 40738725316 49280800527 1600738265 8132400000 369252454 7720200000 ... 1321399023 8806800203 4392228068 405208590 1643266466 2828001384 592020000 5912995890 644274170 368676000
2012-04-02 00:00:00+00:00 10842315003 5.057548e+11 576086400 1219701803 42589460095 47750298996 1472426788 8603305000 465130546 7932257602 ... 1257292339 10503824320 4301474039 409172587 1611950455 3237653209 789690000 8262910251 734283062 428652000
2012-05-01 00:00:00+00:00 10682398853 5.605685e+11 632091870 1305671975 46140710166 43503783560 1641755868 9619336000 559314199 8176675000 ... 1450413725 10372526516 4786762152 413865541 1702602066 3003606944 776033640 8979355460 862585210 415422000
2012-06-01 00:00:00+00:00 10379020647 5.460575e+11 772918380 1305671975 46720386918 40452104576 1481892388 9097073577 577592440 7513506000 ... 1300711200 10073824011 5034045491 404762276 1758053652 3385464823 837908928 8802042581 867322520 415245600

5 rows × 2970 columns

Because we're dealing with ranking systems, at several points we're going to want to rank our data. Let's check how our data looks when ranked to get a sense for this.


In [8]:
cap_data_filtered.rank().head(5)


Out[8]:
security Equity(2 [AA]) Equity(24 [AAPL]) Equity(31 [ABAX]) Equity(52 [ABM]) Equity(62 [ABT]) Equity(64 [ABX]) Equity(66 [AB]) Equity(67 [ADSK]) Equity(69 [ACAT]) Equity(76 [TAP]) ... Equity(42165 [INVN]) Equity(42173 [DLPH]) Equity(42230 [TRIP]) Equity(42247 [MEMP]) Equity(42262 [GZT]) Equity(42263 [LPI]) Equity(42264 [SN]) Equity(42270 [KORS]) Equity(42272 [BCEI]) Equity(42275 [MCEP])
algo_date
2012-02-01 00:00:00+00:00 14 2 3 9.5 2 34 4 1 1 9 ... 1 1 1 5 2 19 3 1 1 2
2012-03-01 00:00:00+00:00 23 8 2 9.5 1 36 8 12 2 7 ... 17 3 4 7 7 17 4 2 2 7
2012-04-02 00:00:00+00:00 24 19 1 14.0 3 35 5 16 9 10 ... 15 11 2 8 4 23 17 6 6 18
2012-05-01 00:00:00+00:00 22 27 4 16.5 4 33 10 23 20 14 ... 21 10 7 9 8 21 16 8 8 15
2012-06-01 00:00:00+00:00 21 22 6 16.5 6 30 6 20 25 4 ... 16 9 8 6 9 25 21 7 9 14

5 rows × 2970 columns

Looking at Correlations Over Time

Now that we have the data, let's do something with it. Our first analysis will be to measure the monthly Spearman rank correlation coefficient between Market Cap and month-forward returns. In other words, how predictive of 30-day returns is ranking your universe by market cap.


In [9]:
scores = np.zeros(36)
pvalues = np.zeros(36)
for i in range(36):
    score, pvalue = stats.spearmanr(cap_data_filtered.iloc[i], month_forward_returns.iloc[i])
    pvalues[i] = pvalue
    scores[i] = score
    
plt.bar(range(1,37),scores)
plt.hlines(np.mean(scores), 1, 37, colors='r', linestyles='dashed')
plt.xlabel('Month')
plt.xlim((1, 37))
plt.legend(['Mean Correlation over All Months', 'Monthly Rank Correlation'])
plt.ylabel('Rank correlation between Market Cap and 30-day forward returns');


We can see that the average correlation is positive, but varies a lot from month to month.

Let's look at the same analysis, but with PE Ratio.


In [10]:
scores = np.zeros(36)
pvalues = np.zeros(36)
for i in range(36):
    score, pvalue = stats.spearmanr(pe_data_filtered.iloc[i], month_forward_returns.iloc[i])
    pvalues[i] = pvalue
    scores[i] = score
    
plt.bar(range(1,37),scores)
plt.hlines(np.mean(scores), 1, 37, colors='r', linestyles='dashed')
plt.xlabel('Month')
plt.xlim((1, 37))
plt.legend(['Mean Correlation over All Months', 'Monthly Rank Correlation'])
plt.ylabel('Rank correlation between PE Ratio and 30-day forward returns');


The correlation of PE Ratio and 30-day returns seems to be near 0 on average. It's important to note that this monthly and between 2012 and 2015. Different factors are predictive on differen timeframes and frequencies, so the fact that PE Ratio doesn't appear predictive here is not necessary throwing it out as a useful factor. Beyond it's usefulness in predicting returns, it can be used for risk exposure analysis as discussed in the Factor Risk Exposure Lecture.

Basket Returns

The next step is to compute the returns of baskets taken out of our ranking. If we rank all equities and then split them into $n$ groups, what would the mean return be of each group? We can answer this question in the following way. The first step is to create a function that will give us the mean return in each basket in a given the month and a ranking factor.


In [11]:
def compute_basket_returns(factor_data, forward_returns, number_of_baskets, month):
    data = pd.DataFrame(factor_data.iloc[month-1]).join(forward_returns.iloc[month-1])
    # Rank the equities on the factor values
    data.columns = ['Factor Value', 'Month Forward Returns']
    data.sort('Factor Value', inplace=True)
    
    # How many equities per basket
    equities_per_basket = np.floor(len(data.index) / number_of_baskets)

    basket_returns = np.zeros(number_of_baskets)

    # Compute the returns of each basket
    for i in range(number_of_baskets):
        start = i * equities_per_basket
        if i == number_of_baskets - 1:
            # Handle having a few extra in the last basket when our number of equities doesn't divide well
            end = len(data.index) - 1
        else:
            end = i * equities_per_basket + equities_per_basket
        # Actually compute the mean returns for each basket
        basket_returns[i] = data.iloc[start:end]['Month Forward Returns'].mean()
        
    return basket_returns

The first thing we'll do with this function is compute this for each month and then average. This should give us a sense of the relationship over a long timeframe. We can see that there appears to be a spread induced by ranking on Market Cap. Specifically that smaller cap stocks tend to have higher returns. This is a well known phenomenon in quantitative finance.


In [12]:
number_of_baskets = 10
mean_basket_returns = np.zeros(number_of_baskets)
for m in range(1, 37):
    basket_returns = compute_basket_returns(cap_data_filtered, month_forward_returns, number_of_baskets, m)
    mean_basket_returns += basket_returns

mean_basket_returns /= 36    

# Plot the returns of each basket
plt.bar(range(number_of_baskets), mean_basket_returns)
plt.ylabel('Returns')
plt.xlabel('Basket')
plt.legend(['Returns of Each Basket']);


Spread Consistency

Of course, that's just the average relationship. To get a sense of how consistent this is, and whether or not we would want to trade on it, we should look at it over time. Here we'll look at the monthly spreads for the first year. We can see a lot of variation, and further analysis should be done to determine whether Market Cap is tradeable.


In [13]:
f, axarr = plt.subplots(3, 4)
for month in range(1, 13):
    basket_returns = compute_basket_returns(cap_data_filtered, month_forward_returns, 10, month)

    r = np.floor((month-1) / 4)
    c = (month-1) % 4
    axarr[r, c].bar(range(number_of_baskets), basket_returns)
    axarr[r, c].xaxis.set_visible(False) # Hide the axis lables so the plots aren't super messy
    axarr[r, c].set_title('Month ' + str(month))


We'll repeat the same analysis for PE Ratio.


In [14]:
number_of_baskets = 10
mean_basket_returns = np.zeros(number_of_baskets)
for m in range(1, 37):
    basket_returns = compute_basket_returns(pe_data_filtered, month_forward_returns, number_of_baskets, m)
    mean_basket_returns += basket_returns

mean_basket_returns /= 36    

# Plot the returns of each basket
plt.bar(range(number_of_baskets), mean_basket_returns)
plt.ylabel('Returns')
plt.xlabel('Basket')
plt.legend(['Returns of Each Basket']);



In [19]:
f, axarr = plt.subplots(3, 4)
for month in range(1, 13):
    basket_returns = compute_basket_returns(pe_data_filtered, month_forward_returns, 10, month)

    r = np.floor((month-1) / 4)
    c = (month-1) % 4
    axarr[r, c].bar(range(10), basket_returns)
    axarr[r, c].xaxis.set_visible(False) # Hide the axis lables so the plots aren't super messy
    axarr[r, c].set_title('Month ' + str(month))


Sometimes Factors are Just Other Factors

Often times a new factor will be discovered that seems to induce spread, but it turns out that it is just a new and potentially more complicated way to compute a well known factor. Consider for instance the case in which you have poured tons of resources into developing a new factor, it looks great, but how do you know it's not just another factor in disguise?

To check for this, there are many analyses that can be done.

Correlation Analysis

One of the most intuitive ways is to check what the correlation of the factors is over time. We'll plot that here.


In [16]:
scores = np.zeros(36)
pvalues = np.zeros(36)
for i in range(36):
    score, pvalue = stats.spearmanr(cap_data_filtered.iloc[i], pe_data_filtered.iloc[i])
    pvalues[i] = pvalue
    scores[i] = score
    
plt.bar(range(1,37),scores)
plt.hlines(np.mean(scores), 1, 37, colors='r', linestyles='dashed')
plt.xlabel('Month')
plt.xlim((1, 37))
plt.legend(['Mean Correlation over All Months', 'Monthly Rank Correlation'])
plt.ylabel('Rank correlation between Market Cap and PE Ratio');


And also the p-values because the correlations may not be that meaningful by themselves.


In [17]:
scores = np.zeros(36)
pvalues = np.zeros(36)
for i in range(36):
    score, pvalue = stats.spearmanr(cap_data_filtered.iloc[i], pe_data_filtered.iloc[i])
    pvalues[i] = pvalue
    scores[i] = score
    
plt.bar(range(1,37),pvalues)
plt.xlabel('Month')
plt.xlim((1, 37))
plt.legend(['Mean Correlation over All Months', 'Monthly Rank Correlation'])
plt.ylabel('Rank correlation between Market Cap and PE Ratio');


There is interesting behavior, and further analysis would be needed to determine whether a relationship existed.


In [18]:
pe_dataframe = pd.DataFrame(pe_data_filtered.iloc[0])
pe_dataframe.columns = ['F1']
cap_dataframe = pd.DataFrame(cap_data_filtered.iloc[0])
cap_dataframe.columns = ['F2']
returns_dataframe = pd.DataFrame(month_forward_returns.iloc[0])
returns_dataframe.columns = ['Returns']

data = pe_dataframe.join(cap_dataframe).join(returns_dataframe)

data = data.rank(method='first')

heat = np.zeros((len(data), len(data)))

for e in data.index:
    F1 = data.loc[e]['F1']
    F2 = data.loc[e]['F2']
    R = data.loc[e]['Returns']
    heat[F1-1, F2-1] += R
    
heat = scipy.signal.decimate(heat, 40)
heat = scipy.signal.decimate(heat.T, 40).T

p = sns.heatmap(heat, xticklabels=[], yticklabels=[])
# p.xaxis.set_ticks([])
# p.yaxis.set_ticks([])
p.xaxis.set_label_text('F1 Rank')
p.yaxis.set_label_text('F2 Rank')
p.set_title('Sum Rank of Returns vs Factor Ranking');


How to Choose Ranking System

The ranking system is the secret sauce of many strategies. Choosing a good ranking system, or factor, is not easy and the subject of much research. We'll discuss a few starting points here.

Clone and Tweak

Choose one that is commonly discussed and see if you can modify it slightly to gain back an edge. Often times factors that are public will have no signal left as they have been completely arbitraged out of the market. However, sometimes they lead you in the right direction of where to go.

Pricing Models

Any model that predicts future returns can be a factor. The future return predicted is now that factor, and can be used to rank your universe. You can take any complicated pricing model and transform it into a ranking.

Price Based Factors (Technical Indicators)

Price based factors take information about the historical price of each equity and use it to generate the factor value. Examples could be 30-day momentum, or volatility measures.

Reversion vs. Momentum

It's important to note that some factors bet that prices, once moving in a direction, will continue to do so. Some factors bet the opposite. Both are valid models on different time horizons and assets, and it's important to investigate whether the underlying behavior is momentum or reversion based.

Fundamental Factors (Value Based)

This is using combinations of fundamental values as we discussed today. Fundamental values contain information that is tied to real world facts about a company, so in many ways can be more robust than prices.

The Arms Race

Ultimately, developing predictive factors is an arms race in which you are trying to stay one step ahead. Factors get arbitraged out of markets and have a lifespan, so it's important that you are constantly doing work to determine how much decay your factors are experiencing, and what new factors might be used to take their place.