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 (July & August 2020 Update)

In this post I will present to you my yutai stock picks for July and August 2020. It’s worth noting that July wasn’t a yutai heavy month, especially compared to August and September. Yutai investing might be fun but without wanting to sound too repetitive, I always like to add as a disclaimer that you shouldn’t just pick a stock solely because of its yutai. Rather yutai should just be considered as a perk in addition to the underlying return opportunities that the stock presents. Needless to say, given the uncertainty surrounding financial markets and COVID cases rising in Japan, I would be cautious before making any new purchases.

Continue reading

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.

Top 5 Popular Stocks in Japan that Offer Yutai Gifts

Yutai Gifts 株主優待 (Kabunushi Yutai) are perks that companies give to their shareholders as a form of gratitude for owning their stocks. These gifts are often tied to the product or service that the company provides. A lot of retail investors find Yutai investing appealing and there are numerous websites in Japanese that summarise and rank these Yutai offerings. I have done my own bit of research and I have come across quite a few companies that provide competitive rewards. Over the months I have created my own list of popular Yutai stocks that I would like to share with you.  

How do I receive my Yutai Gift? 

Before we get started with our top 5 list, you might be asking what is required to be eligible to receive these gifts. 

  • You will need a brokerage account in order to purchase the stocks. For guidance in opening up a brokerage account in Japan, please refer to this article
  • Purchase the stock and hold it until the relevant ex-right date (the date on which you are eligible for the gift if you are the shareholder).
  • You will receive your Yutai Gift via post (most companies have a detailed description on their website regarding the Yutai Gift timings so you will be able to check online the exact dates of when you can expect to receive your rewards.

Now, let’s get started. All share prices are based on closing prices of 16th May 2019.

(5) Skylark Holdings (3197)

skylark

Company Profile: Skylark Group runs numerous family restaurant chains in Japan. Gusto and Jonathan’s were the two restaurants that I was aware of but their brand portfolio seems quite extensive and includes a wide range of cuisines. You can find a list here.

Gift: Coupons that can be used across their restaurants. Every 6 months you will receive 3,000 JPY worth of coupons so that’s 6,000 JPY per year just in coupons which isn’t that bad (these coupons are relatively easy to sell online or at ticket shops like Daikokuya.

Minimum Shares Required: 100 shares

Investment Amount: 100 * 1868 = 186,800

(4) Japan McDonald’s Holdings (2702)

mcdonalds

Company Profile: McDonald’s needs no introduction; their burgers are widely consumed around the world and Japan is no exception. 

Gift: You get the below booklet which has 6 sheets. Each sheet has 3 coupons which can be exchanged for 1 burger, 1 side and 1 drink or dessert of your choice. I have seen people assigning different values to this coupon. Some people came up with their valuations by picking the most expensive items on the menu that they can order, which brings the monetary value of a booklet close to 7000 – 8000 JPY. I have seen more fair estimates which value this coupon at around 5000 JPY.

mcdonaldscoupons

Minimum Shares Required: 100 shares

Investment Amount: 4880 * 100 = 480,000 JPY

(3) ANA Holdings (9202) / JAL (9201) ( (I put both airline companies together as what they have to offer is pretty similar in my opinion).

jal

Ana

Company Profile: JAL and ANA are the two biggest domestic airlines in Japan and are with well established internationally.

Gift: 50% off domestic flights. Considering domestic flights can range from 20,000-50,000 JPY, you are looking to save 10,000 – 25,000 JPY on your travel fare. Similarly to other Yutai Gift tickets you will be able to easily sell them online. 

Minimum Shares Required: 100 shares (to note that the number of free tickets increases as the number of shares increase). For JAL this website (in Japanese) has a good summary of the benefits, there are also added bonuses such as additional coupons for holding the stock for 3 consecutive years.  

Investment Amount: ANA (3,750 * 100 = 375,000 JPY) JAL (3,607 * 100 = 360,700 JPY)

(2) Oriental Land Co. Ltd (4661) 

olc

Company Profile: Headquartered in Urayasu, Oriental Land runs Disney Land and DisneySea, two very popular theme parks in Chiba. In addition to its theme park business, the company also manages a number of hotels including the Disney Ambassador Hotel.

Gift:  1 free entry pass for either Disney Land or DisneySea (entry price for adults is 7,400 JPY). If you are a fan of Disney and their theme parks I could definitely see the appeal for this gift. Alternatively the coupon can also be easily sold online as there is huge demand for it. 

Minimum Shares Required: 100 shares

Investment Amount: (12,935 * 100 = 1,293,500 JPY)

(1) Aeon (8267)

Aeon

Company Profile: Aeon runs a large chain of supermarkets across Japan and Asia. If you hold their shares you will be sent their “Owner’s Card”. This will entitle you to claiming 3% cash back on your purchases made in cash or via Aeon credit cards (please note that purchases made with non-approved credit cards will not be counted) at their stores. If you regularly do your shopping at Aeon the cash back becomes quite appealing. Similarly to other Yutai gifts, you will entitled to cash back every 6 months. For example, let’s say that over the past 6 months you spent 500,000 JPY at Aeon, your cash back amount will be 500,000 * 0.03 = 15,000 JPY.  Considering the stock trades at around 2000 JPY, that’s 15,000/200,000 = 7.5% yield and we are not even including dividends.

Gift: 3% cashback card.

Minimum Shares Required: 100

Investment Amount: 1989 * 100 = 198,900 JPY

What are your top picks? Have you come across any good stocks with Yutai gifts? Please post your top picks in the comment section. Thank you for reading.

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.