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!

Quantic: The Accounting Module

I have recently completed the Accounting module which is the EMBA’s first module so in this post I will share some thoughts about my learning experience. In past posts, I gave a general overview about the EMBA but now that I have taken and completed a course, I can share more concrete details which I hope readers find helpful.

What does the Accounting module cover?

As the module’s name suggests, the course covers general accounting concepts such as ledgers, credits and debits, key financial statements, ratios and some aspects of managerial accounting. The unit also covers some non-accounting concepts such as general explanations of financial instruments such as stocks and bonds. It is quite a lot of material to cover over five weeks, especially if you are new to these concepts. I did a management degree for my undergraduate studies and these are concepts you would normally cover in 1-2 semesters.

Continue reading

Re: Bloomberg Opinion Piece: “Wall Street’s CFA Program Is a Colossal Waste of Time”

On 17th August 2021, Bloomberg published an opinion piece titled “Wall Street’s CFA Program Is a Colossal Waste of Time ” and this post is a response to that article. The CFA Charter has very often been regarded as the gold standard when it comes to qualifications in the financial industry and this article has undoubtedly ignited some discussions, with subreddit threads such as this one being just one of the few examples. Calling the CFA program a “Colossal Waste of Time” seems to be a pretty bold statement and given that in the article the author (Jared Dillian) mentions that he passed level I but never completed the qualification, a lot of readers were quick to dismiss his opinion. The author also expressed his view that he favours MBAs over the CFA program which caused a slight digression towards the comparison of the two qualifications. However, some readers were eager to identify elements of truth in the article as they possibly mull over their options following the decrease in pass rates for the latest sittings.

Continue reading

LSE Masters in Finance (full-time and part-time) Part 1: The Application Stage

Introduction
This post will cover LSE’s MSc in Finance and it will be divided into 3 separate parts: (1) Application Stage (2) Year 1 (3) Year 3.

Having graduated from the course myself, I would like to share some information which prospective students might find useful in evaluating the course prior to applying. As a disclaimer, I have no affiliation with LSE and with the exception of the factual information regarding the course, most of the content represents my personal opinion.

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.

CFA Level 1 General Overview and Tips

So, you are seriously considering taking the CFA exam and you might be looking for some information online, if so, congratulations you have come to the right place. I sat and passed the exam back in 2011 and I would be happy to share my advice here. Luckily, not much has changed since then with regards to the test format and the content so I believe that what I cover in this post is still valid for candidates preparing for the exam today.

Topics Covered

The CFA Institute provides here a detailed overview of topics which are covered in each level. Not all topics are weighted equally so successful candidates are good at identifying core topics and questions and are able to focus on these areas in their preparation. The learning focus according to the CFA Institute is “Knowledge and Comprehension” rather than “Application and Analysis” which will be tested in Level 2. In my opinion, Level 1 is all about the candidate gaining a general knowledge of all topics whilst grasping the foundation of investment analysis concepts which he/she will use later on in performing investment analysis.

 

weights

Exam Format and Exam Strategy

The exam consists of a morning and afternoon part, each containing 120 multiple choice questions (to note that there is no negative marking so do not leave any questions blank). You will have 3 hours to complete the questions so you will be under a lot of time pressure. It’s important to avoid spending too much time on any single question so if you are not sure about a question, mark it and come back to it later. Aim not to spend more than 90 seconds on a single question, there won’t be long calculations involved so if you have a good mastery of the topic you should be able to come up with an answer relatively quickly. When I took the exam I aimed to finish the exam in an hour so I had the last 20-30 minutes to review my answers. As you take mock exams  you will develop your own test taking technique but the key point that I want to get across is that pacing yourself is as important as your knowledge of the curriculum.

Study Resources

The moment you register for the CFA Institute you will get access to the Institute Curriculum which will be shared to you as an E-Book. I also recommend ordering the hard copies of the Institute books which will be sent to you via post. The whole curriculum consists of 6 thick volumes that will take a lot of space up and will be a perfect substitute-friend for the upcoming 6 months or so. The question that a lot of candidates ask themselves now is whether the Institute materials are enough or if they require some additional source of help in the form of study notes or video lectures. Schweser is a very popular choice amongst candidates. Others might also opt to take classes via other training providers. So, are training providers worth the additional cost? It really depends on the candidate’s background and circumstances in my opinion. If a person already has a good finance background and has time to commit in reading the curriculum I don’t think he/she needs to rely on training providers. If instead time is a constraint or finance is a new subject then possibly the additional help will provide to be valuable and worth it. Overall I think training providers have done a very good job in analysing the exam, identifying the key topics and ensuring that their students have a high chance of passing. My experience with them has been positive.

The Calculator is your Friend

There are only two types of calculators that you will be able to take into the exam with you – read the official Calculator Policy here – Texas Instruments BA II Plus and Hewlett Packard 12C. If you have registered for the exam and you are in the early stages of your preparation my advice is to start getting familiar with the calculator as soon as possible. There are a lot of questions on the exam where you will need it and you will be able to quickly score valuable points. Some examples of where your calculator will come in handy are: Present Value/Future Value, Bond Calculations, NPVs (maybe some Statistics functions and Annuity calculations).

calculator

Last Words of Advice

  • Remember to do the end of chapter questions in the official CFA books. All questions are of high quality and are very likely to be tested on exam day.
  • Do not have a heavy lunch in between the morning and afternoon exam.
  • Remember your exam ticket and passport on exam day otherwise you will not be able to sit the exam that day.
  • Think of your study as a marathon not as a sprint, towards the final week of the exam do some light revision and preserve your energies for exam day.
  • Get yourself a nice study group to have people who you can share your joys and pain with.

Thank you for reading and I hope you look forward to future posts.