How to Build a Factor Model in Python

Ever wonder what drives stock returns beyond just market moves? That’s where factor models come in. They break down an asset’s return into common drivers—like market risk, size, value, or momentum—so we can better understand, predict, and optimize our portfolios.

Today, we’ll learn how to build a simple multi-factor model in Python and interpret the results. If you love quant finance, regression, and nerding out over data—this is for you!


💡 What Is a Factor Model?

A factor model explains an asset’s return using a linear combination of common risk factors. The most famous example is the Capital Asset Pricing Model (CAPM):

R_i = α + β * R_m + ε

Where:

  • R_i is the return of asset i
  • R_m is the market return
  • β is sensitivity to the market (market beta)
  • α is the intercept or alpha (abnormal return)
  • ε is the residual error

But one factor isn’t always enough. Enter multi-factor models like Fama-French 3-factor or 5-factor models, which add factors like:

  • SMB: Small minus Big (size effect)
  • HML: High minus Low (value effect)
  • MOM: Momentum

Modern quant investors use even more: low volatility, quality, ESG, etc.


🔧 Step-by-Step: Build a Factor Model in Python

1️⃣ Install Required Libraries

pip install pandas numpy yfinance statsmodels matplotlib

2️⃣ Load Asset and Factor Data

We’ll get daily returns for Apple (AAPL) and the Fama-French 3 factors from Kenneth French’s website via a simplified CSV or preloaded dataset.


import pandas as pd
import yfinance as yf
import statsmodels.api as sm

# Get Apple stock price
aapl = yf.download("AAPL", start="2020-01-01", end="2023-01-01")['Adj Close']
aapl_returns = aapl.pct_change().dropna()

# Load Fama-French factors (example: already downloaded CSV)
factors = pd.read_csv("F-F_Research_Data_Factors_daily.csv", skiprows=3)
factors = factors.rename(columns={"Mkt-RF": "MKT"})
factors['Date'] = pd.to_datetime(factors['Date'], format='%Y%m%d')
factors = factors.set_index('Date') / 100  # Convert % to decimal
factors = factors.loc[aapl_returns.index]

# Merge data
data = pd.concat([aapl_returns, factors], axis=1).dropna()
data.columns = ['AAPL', 'MKT', 'SMB', 'HML', 'RF']

# Excess return
data['AAPL_EX'] = data['AAPL'] - data['RF']

3️⃣ Regress Returns on Factors


# Set up X (factors) and Y (excess returns)
X = data[['MKT', 'SMB', 'HML']]
Y = data['AAPL_EX']
X = sm.add_constant(X)

# Run regression
model = sm.OLS(Y, X).fit()
print(model.summary())

📈 Example Output

Here’s what the regression results might show:


                            OLS Regression Results                            
==============================================================================
Dep. Variable:              AAPL_EX   R-squared:                       0.425
==============================================================================
coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const     0.0003      0.000      2.101      0.037     2e-05     0.0006
MKT       1.0256      0.045     22.851      0.000     0.937     1.114
SMB       0.3221      0.067      4.791      0.000     0.190     0.454
HML      -0.1953      0.054     -3.620      0.000    -0.301    -0.089

This means:

  • β_market ≈ 1.03 → AAPL is highly sensitive to the market
  • β_SMB ≈ 0.32 → Slight tilt toward small-cap behavior
  • β_HML ≈ -0.19 → AAPL behaves like a growth stock (not value)
  • R² ≈ 0.42 → 42% of AAPL’s return is explained by these 3 factors

📌 Interpretation and Use

Factor models give you:

  • 🎯 Insights into what drives returns (e.g., is a stock momentum-driven?)
  • 🛡️ Better risk management (e.g., controlling factor exposures)
  • 📦 Portfolio construction tools (e.g., build a long/short value portfolio)

You can also use them for:

  • Attribution analysis
  • Hedging strategies
  • Smart beta or factor investing strategies

📊 Visualizing Factor Exposure


import matplotlib.pyplot as plt

coefs = model.params[1:]
coefs.plot(kind='bar')
plt.title("Factor Exposures for AAPL")
plt.ylabel("Beta")
plt.grid(True)
plt.show()

This bar chart shows AAPL’s beta to each factor. A high market beta, moderate size tilt, and negative value tilt give you a fingerprint of Apple’s factor personality.


🧠 Final Thoughts

Factor models are the backbone of modern portfolio theory. Whether you’re backtesting strategies, managing risk, or analyzing performance, understanding how to build and interpret them is an essential skill.

In this guide, you learned how to:

  • Load and clean financial and factor data
  • Build and interpret a multi-factor regression model
  • Visualize exposures to better understand asset behavior

Now it’s your turn—run this on your favorite stocks, add new factors, and get to know your portfolio better than ever. Happy modeling!


Want more finance nerd tutorials? Follow me at The Finance Nerd for more Python-powered investment insights!

5 Popular Stocks in Japan that Offer Yutai Gifts (June 2020 Update)

A year ago I posted Top 5 Popular Stocks in Japan that Offer Yutai Gifts where I shared a popular list of yutai stocks. Given the interest received for that post, I created an updated list for 2020 that I would like to share with you. Some of my picks remain unchanged and it wouldn’t be interesting simply just re-introducing the same stocks so I will be doing something slightly different. Rather than ranking the “Top” stocks, I will introduce to you 5 stocks that pay out interesting yutai gifts.

There is a lot of material in Japanese, very often promoted by online brokers or other blogs and newsletters, but I couldn’t find a lot of content in English which is what led me to start this series of of posts.

Continue reading

Trying out a Robo-advisor in Japan

cute-807306_1920

Robo-advisors have increased in popularity in the past years but are they worth it? I was interested in seeing what they had to offer so I decided to try one out myself to see if these products are viable solutions for people looking to invest for their retirement. For those of you who are new to Robo-advisors, Wikipedia defines them in the following manner:

 

Robo-advisors or robo-advisers are a class of financial adviser that provide financial advice or investment management online with moderate to minimal human intervention. They provide digital financial advice based on mathematical rules or algorithms. These algorithms are executed by software and thus financial advice does not require a human advisor. The software utilizes its algorithms to automatically allocate, manage and optimize clients’ assets.

 

Below I have listed a number of popular Robo-advisors in Japan (the list is based on Robo-advisors that I looked up on 7th May 2020 and is not an exhaustive list).

 

  1. WealthNavi
  2. Theo
  3. On Compass
  4. Folio
  5. SMBC Robo Advisor

 

After reading about a number of Robo-advisors, I ended up choosing WealthNavi which seemed to be one of the most popular brands in Japan. The services that all the above brands offer seem to be all comparable where they charge around 1% for an account that invests in a diversified portfolio and performs rebalancing and optimisation.

 

How it works?

Once you set up the account and login you will be asked to start a questionnaire for the Robo Advisor to assess your risk/return objectives. For WealthNavi there are a total of 5 categories, with 1 being the most conservative and 5 being the most aggressive. The investment universe is limited to the below ETFs, however based on your risk appetite you will see a greater/smaller allocation to stocks. Here are the ETFs that your account balance will be allocated to:

 

VTI: Vanguard Total Stock Market ETF

https://investor.vanguard.com/etf/profile/VTI

 

VEA: Vanguard FTSE Developed Markets ETF

https://investor.vanguard.com/etf/profile/portfolio/vea

 

VWO: Vanguard FTSE Emerging Market ETF

https://investor.vanguard.com/etf/profile/VWO

 

AGG: IShares Core US Aggregate Bond ETF

https://www.ishares.com/us/products/239458/ishares-core-total-us-bond-market-etf

 

GLD: SPDR Gold Trust

https://www.spdrgoldshares.com/

 

IYR: IShares US Real Estate ETF

https://www.ishares.com/us/products/239520/ishares-us-real-estate-etf

 

TIP: IShares Tips Bond ETF

https://www.ishares.com/us/products/239467/ishares-tips-bond-etf

 

All ETFs are well known, provide good exposure to the market/asset class that they are looking to track with a very low expense ratio. I have added above the links to the fund profiles for those interested in looking at price/performance, fees, distributions, etc.

 

A Sample Allocation with a risk tolerance of 5.

 

(Allocation for 26th July 2019, initial investment 1,000,000, weights rounded at 2 decimal places)

Name Ticker   Weight
US Stocks VTI 358,896 34.28%
EU Stocks VEA 346,262 33.07%
Emerging Market Stocks VWO 148,698 14.20%
US Bonds AGG 50,297 4.80%
Gold GLD 87,136 8.32%
Real Estate IYR 50,750 4.85%
Cash   4,969 0.47%

 

Fees: 1% annual fee on your invested balance (excludes your cash weight), for investments over 30MM JPY 0.5% (SOURCE: https://www.wealthnavi.com/).

 

Rebalancing Frequency

WealthNavi’s algorithm is set to perform rebalancing every 6 months. However, if any asset class deviates from its optimal allocation weight by more than 5%, rebalancing takes place ahead of schedule to bring the portfolio back to the optimal allocations. For rebalancing to take place ahead of schedule please note that you need a minimum balance of 500,000 JPY invested in the account, if your deposit is lower than this amount you will need to wait until the next rebalancing date for the portfolio to be rebalanced back to its optimal allocation.

(SOURCE)

After trying the service, I was able to come up with the following advantages and disadvantages from using Robo Advisors.

 

Advantages

  1. Automatically generates an allocation based on your risk tolerance

Arguably, one of the main reasons why people choose Robot-advisors is because allocations and rebalancing decisions are done automatically based on pre-defined rules and algorithms with some form of portfolio optimisation taken into account.  This is a great advantage if you want to avoid the hassle of having to review your portfolio and having to regularly update the allocations yourself.

 

  1. No Transaction costs when rebalancing portfolios

Buy/Sell orders in your brokerage account will usually result in transaction costs, however rebalancing done by your Robot-advisor will not result in you incurring these fees. You will be charged a flat fee as a % of your account balance.

 

  1. Tax-efficient rebalancing

The optimisation algorithm (at least for WealthNavi) is able to factor in taxes when realising gains/losses and offsets them to ensure steady returns whilst minimising tax liabilities.

 

Disadvantages

 

  1. High Fees

Arguably, the fees that Robo-advisors charge is one of the biggest drawbacks from this service. Especially if you are paying 1% to hold a balanced portfolio of ETFs this is something that you might want to consider doing yourself if you are able to sit down, measure your risk appetite and do some analysis based on your risk return objectives. There are a lot free softwares out there that perform portfolio optimisation. There is a limit to the transparency that each Robo Advisor will provide in terms of rebalancing rules (especially if this will end up revealing trade secrets) but from what I can gather is that a lot are based on Modern Portfolio Theory and will place your portfolio somewhere on the efficient frontier based on your risk/return constraints.

 

  1. Value lost from automation/not too much customisation

Some of the value that financial advisors can offer is the tailored financial advice they can give to individuals based on their financial situation and objectives. The bucketing and categorisation that current Robo-advisors perform is still limited in my opinion and is not able to capture the cognitive aspects and intricacies of the investor’s mind.

 

 

Conclusion

I believe that the value of Robo-advisors depends a lot on how much time you want to spend in looking at your portfolio. If you are just happy to have your money invested automatically in a diversified portfolio and want to spend minimum time and effort in working out portfolio weights, buy/sell timings I do see a value in this service. If instead you are happy spending some time reviewing your allocations and making your own investment decisions, I believe that spending additional fees on a Robo-advisor just ends up hurting your returns and you have much cheaper ways for obtaining comparable results. There are also a lot of ETFs out there which already provide a very good level of diversification at extremely competitive management fees.

Opening a Brokerage Account in Japan

Before you continue reading I assume that you are a resident in Japan as you will have to submit proof of residency when opening up a brokerage account with a Japanese broker. When I was looking to open up an account a few years ago, I was surprised by the lack of online information in English so I hope some people find this content useful. You will still need to have some level of understanding of Japanese in order to navigate the registration forms; unfortunately a lot of the information is still in Japanese.

This may sound like a slight digression but if you are based in Japan as an expat it’s very likely that you will have been contacted by private advisers soliciting you to open up a retirement account with them. While I could see why certain people might benefit from their services, if your aim is to invest whilst minimising costs and you intend to stay in Japan for a while I would personally stay away.

Selecting a Broker

Firstly, you will need to choose from one of the many Japanese online brokerage firms, the so called ネット証券 (Netto Shoken) which are widely used by retail investors as their fees are very competitive. Their offerings are all quite similar based on what I’ve seen. Their products range from individual stocks, FX, options and futures, bonds and commodities. Below is a list of some of the most popular firms:

SBI Securities

Matsui Securities

Rakuten Securities

Kabu.com

Monex Securities

I also came across the below website that ranks these companies based on different metrics (please note that the website is in Japanese):

https://s.minkabu.jp/hikaku/

Having done my own research I opted for SBI Securities which has a good balance between low fees and positive client feedback. Although this is a very rough overview, these are the steps involved in opening up an account.

1) Fill out the online application form. You will need to provide your personal details such as your “My Number” info for tax purposes, personal address and documents (Passport, Residence Card, Insurance Card). You will also need to go through the terms and conditions and provide some details regarding your current occupation and investment experience. Filling out the form can take from 5-30 minutes. If you are employed, I assume that you have done your own research to ensure that you are not in breach of company policy. If you are not sure I would strongly recommend checking with your internal compliance team.

2) If you filled out your form correctly and your application was successful, you will get confirmation via post and a request to provide paper scans of documents such as your passport and My Number Card. Once you post the required information your account should be active within 3-4 business days.

3) Now that your account is active you need to transfer money in and this can be done in several ways. Many of the online brokers also offer banking services so you could open a bank account with them and transfer funds between your bank account and brokerage account. You can even ask them to issue a cash card (see below picture) that will allow you to deposit and withdraw money via ATM machines at convenience stores.

SBI card

Opening a NISA (Nippon Individual Savings Account)

If you have gone through the above steps you should definitely also open up a NISA. This is the Japanese equivalent of a stock ISA in the UK. The account allows you to invest up to 1,200,000 JPY tax free in a single tax year. The amount that you invest will be tax free for 5 years meaning that if you keep investing the maximum amount for 5 years you will end up with 6,000,000 (5*1,200,000) in a tax sheltered account. This is what they call a 一般(General) NISA. The second type of NISA is a 積立 (Periodic Investment) NISA, which allows you to invest 400,000 JPY per year but extends your tax exemption period to 20 years.

SOURCE: Japanese FSA

Taxes

Investments that are not part of your NISA will be subject to taxes and your broker will give you two options: the first option is to keep your investments in a “Special Account” (特定口座). I strongly recommend this as you will not have to go through the hassle of filing out a tax return (確定申告). Instead your taxes will be automatically deducted from your trading platform. Dividends paid into this account will therefore be paid net of tax. The other option instead is to use a “General Account 一般口座” where any gains and dividend/interest payments will be paid pretax, however you will need to declare this source of income in your yearly tax return form.

Disclaimer:

I am not affiliated with any of the companies that I mentioned in this article. Please invest responsibly. Investment returns can fluctuate and I cannot be held responsible for any losses.