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!

How to Build a Black-Litterman Model in Python (Without Losing Your Mind)

What if Harry Markowitz and Thomas Bayes teamed up to manage your portfolio? That’s basically what the Black-Litterman model is: a quantitative investing tool that blends modern portfolio theory with your personal views. Today, we’re going to explore how to build this model from scratch in Python—with code, theory, and plenty of finance nerd humor along the way.


💡 What Is the Black-Litterman Model?

The Black-Litterman model was developed by Fischer Black and Robert Litterman at Goldman Sachs. In short, it starts with a “neutral” market portfolio—what the market implies are fair asset returns—and then lets you adjust those expectations with your own views (like “I think Apple will outperform Google by 5%”).

This results in a set of posterior expected returns you can plug into a mean-variance optimizer, giving you smarter, more intuitive portfolio weights than relying on historical returns alone.


📉 Why Not Just Use Mean-Variance Optimization?

Good question. Traditional Mean-Variance Optimization (MVO) has a problem: it’s hypersensitive to input assumptions—especially expected returns. A small tweak in expected return can flip your optimal portfolio completely. This makes it prone to overfitting and unrealistic allocations (like putting 100% into Tesla because it performed well last year).

The Black-Litterman model fixes this by:

  • Starting from the market-implied expected returns (based on CAPM theory)
  • Adjusting those with your own views (absolute or relative)
  • Blending them using a Bayesian approach, weighted by confidence

The result? Portfolios that are diversified, stable, and still aligned with your beliefs.


🛠️ Step-by-Step: Build a Black-Litterman Model in Python

1️⃣ Define Your Assets and Covariance Matrix

Let’s assume a tech-heavy portfolio:

  • Assets: AAPL, MSFT, GOOG, AMZN, TSLA
  • Volatilities: Between 16% and 30%
  • Correlations: About 0.6 between all pairs

import numpy as np
import pandas as pd

tickers = ['AAPL', 'MSFT', 'GOOG', 'AMZN', 'TSLA']
vols = np.array([0.20, 0.18, 0.16, 0.22, 0.30])
corr = 0.6
corr_matrix = np.full((5, 5), corr)
np.fill_diagonal(corr_matrix, 1)

cov_matrix = np.outer(vols, vols) * corr_matrix
cov_df = pd.DataFrame(cov_matrix, index=tickers, columns=tickers)

2️⃣ Set Market Capitalization Weights


market_caps = pd.Series({
    'AAPL': 3000,
    'MSFT': 2500,
    'GOOG': 1800,
    'AMZN': 1400,
    'TSLA': 900
})
market_weights = market_caps / market_caps.sum()

3️⃣ Calculate Implied Equilibrium Returns


risk_free = 0.02
delta = 2.5
Pi = delta * cov_df.values.dot(market_weights.values) + risk_free
prior = pd.Series(Pi, index=tickers)

These are the market-implied expected returns for each asset. You can think of this as the “default” starting point.

4️⃣ Express Your Views (P & Q Matrices)

Let’s assume two views:

  1. Absolute view: TSLA will return 20%
  2. Relative view: AAPL will outperform GOOG by 5%

P = np.array([
    [0, 0, 0, 0, 1],  # TSLA
    [1, 0, -1, 0, 0]  # AAPL vs GOOG
])
Q = np.array([0.20, 0.05])
view_conf = np.array([0.5, 0.95])

5️⃣ Combine Everything in Black-Litterman


from pypfopt.black_litterman import BlackLittermanModel

bl = BlackLittermanModel(
    cov_df,
    pi=prior,
    P=P,
    Q=Q,
    omega="idzorek",
    view_confidences=view_conf,
    tau=0.05
)
bl_rets = bl.bl_returns()

Result: A new set of expected returns, adjusted for your views and confidence levels.

6️⃣ Calculate Optimal Portfolio Weights


bl_weights = bl.bl_weights(risk_aversion=delta)
print(bl_weights)

This gives you your optimal portfolio. For example:

  • AAPL: 49%
  • TSLA: 12%
  • GOOG: 2.7%

Notice how your views shifted weight away from GOOG and toward AAPL and TSLA. Beautiful!


📈 Why Finance Nerds Love Black-Litterman

The Black-Litterman model is like giving your portfolio a brain—and a backbone. It respects the market but still lets you express strong, confident views without going overboard.

It’s especially useful if you’re:

  • Building institutional portfolios
  • Running model portfolios with tactical overlays
  • Trying to avoid overfitting in historical MVO models

Plus, it’s incredibly satisfying to watch your views translate into clean, data-driven portfolio shifts.


🧠 Final Thoughts

The Black-Litterman model gives you the best of both worlds: market rationality and personalized insights. With Python and a few libraries like PyPortfolioOpt, it’s easier than ever to implement.


Want more posts like this? Subscribe or follow me at The Finance Nerd for regular articles on quant tools, data-driven investing, and nerdy financial insights.

🕒 10 Modern Time Management Tips for Busy People

In today’s fast-paced world, time often feels like it’s slipping through our fingers. Between digital distractions, packed calendars, and the pressure to always be “on,” it’s easy to feel overwhelmed. But time management isn’t about squeezing more into your day—it’s about organizing your time around what really matters. Whether you’re working from home, raising a family, or managing multiple side projects, these ten modern tips can help you take back control and move through your day with intention and focus.

Continue reading

My Experience Attending the Le Wagon Data Science Bootcamp in Tokyo

For quite some time, I had been considering enrolling in a data science bootcamp. Working in finance, I’ve found that more and more of my responsibilities involve programming—particularly in Python and SQL. As AI continues to evolve, I felt it was the right time to skill up and explore how I could integrate AI and data science into my professional development.

Living in Tokyo, I was looking specifically for an international bootcamp with in-person or hybrid offerings. Options were surprisingly limited, but Le Wagon stood out. Not only do they have a strong international presence, but they’ve done a great job promoting their tech community locally through Meetup events and free workshops. I attended a few of their free sessions and was impressed with both the content and teaching style—clear, practical, and beginner-friendly.

Continue reading

Resuming Blogging After a Long Break

Hello, readers. After a very long break, I am delighted to resume writing my posts. I don’t really have any excuses for my prolonged silence. Yes, I’ve been occupied with various projects and studies, but, at the end of the day, the truth is that I succumbed to procrastination on a few writing days. Those days turned into weeks, which eventually turned into months…

I suspect that I’m not in the minority, and I must say that this experience has given me insight into how some blogs come to an end. Drawing a comparison to running, it felt like I stopped when I shouldn’t have, as resuming my writing feels more tiring and painful than pushing through those extra miles to reach a goal (although I wouldn’t know how to define a goal, especially when it comes to this blog).

Continue reading

The Quantic EMBA, Capstone Project & Graduation Feb-23

A few months have passed since I completed the Quantic EMBA and since then, I have been getting quite a lot of questions from prospective students regarding my experience and most importantly, whether I would recommend this course. This will be my final post regarding Quantic and I am hoping to touch upon most of your questions to help you make an informed decision.

1. The Capstone Project

I have written extensively about my learning experience for the individual models and if you read my past posts, you will recall that I was not a huge fan of their teaching style. The Capstone Project was a pleasant surprise as it was more engaging and gave me the opportunity to interact more with other students. In a nutshell, the project required us to come up with a viable business plan, something which incorporates most of the concepts that we learned throughout the course. We must have spent around a month in finding group members, a couple of months in discussing and finally choosing the business idea and finally a solid 3-4 months in drafting the business plan.

Overall I found myself in a good group, with professionals from a wide range of industries and backgrounds. I am not saying that we didn’t have any hiccups on the way but I thought that we managed to submit a reasonable piece of work and a very viable business idea (I will not go into details here). We had weekly meetings and worked on market research, developed mock ups of our product, created a pricing plan and finally some very realistic financial projections.

The only disappointing part of this project was the marking. Based on the comments that we received, it was very clear that the marker had not understood or thoroughly read our plan, the comments came across as very rushed and generic. To add insult to injury, the comments that we got from our appeal process were very unprofessional, something that I would never expect from a well reputable academic institution.

2. The Graduation Ceremony

The graduation ceremony was also disappointing; to summarise, it was pretty much just your name being read out in a big ZOOM meeting. While I understand that given the number of students (and cost?) it might not be feasible to organise hybrid events, I thought that some additional work could be done in hosting a more inclusive graduation ceremony.

3. Has the degree been a game changer?

This is a question that I get asked quite a lot but I might not be the best person to answer it as I have not been actively looking to change careers with this EMBA, however I can speak based on what I have seen in my cohort. I would say that the short answer is no (at least in APAC). Unlike past degrees, I did not get the impression that student made big career moves after graduating; as someone who has invested in this EMBA, I would love to hear that I am wrong though. I regularly speak with recruiters and I must say that the brand image is still low so I believe Quantic still has a lot of work to do to increase the perceived value of their degrees.

4. The Network

The networking aspect is where I see the most potential. Quantic have done a very good job in gaining momentum and attracting smart students around the world. There are various WhatsApp groups and communities and they are all very active. The question to ask is whether this momentum will continue to get stronger or whether the networks will fade away. I am optimistic here and as a graduate, I am hoping that the Quantic brand continues to grow. I am also looking forward to exploring the “Quantic network” in the following months.

5. Final verdict

My advice for Quantic is to review the teaching style and add more opportunities for students to interact. The few group projects throughout the course were the most enjoyable experience and the Smart Cases were extremely monotonous and ended up becoming a tick box rather than the intended active learning tool. The tutorials and events are still very US centric in terms of timezone and I thought that greater consideration for APAC based students would have been nicer. As a prospective student you might ask me whether I would enrol in the course if I could go back in time and the short answer is No. However I would like to re-iterate that this will depend on your personal circumstances. If you do not want to get into debt in gaining a degree, Quantic might be a suitable choice but I still think it’s a bit of a gamble. As a graduate I do hope that they keep adding to the learning experience to avoid becoming one of the many degree mills.

Preparing for the GMAT Exam (Post 1)

Hello Readers, this is post number one of my experience in preparing for the GMAT exam. Just to give you some background, I took the GMAT exam for the first time 12 years ago during my last year of university but I opted to cancel my score which was a big, big mistake. A lot of time has passed since my first attempt but I recall that the questions that I was seeing at the end of the exam were easy, leading me to think that I had done very poorly. It was a bad decision to cancel the score and there are a lot of articles out there including this one from Manhattan Prep that argue why you should not. My second attempt was three years ago and this time I did not cancel my score just to receive my extremely underwhelming result of 470…….
So what went wrong? If you check out other posts on this blog page you, can see how I have been taking other arguably challenging exams so why did I perform so poorly on the GMAT exam? There are a lot of posts out there from test takers who got their desired scores and got accepted at their target business schools. This is not one of those posts but I am hoping that this gives you some insight as to the bad habits that you should avoid when preparing for this exam.

Continue reading

Does Mindfulness Work?

Mindfulness has been a buzz word in the past years, there are a lot of definitions out there, however the one that I like is the one that refers to mindfulness as the ability to focus on the present moment experience without evaluation. I started practising mindfulness three years ago and I have had a very positive experience. It has had a very strong impact on my professional career and on my personal life, but most importantly, it has allowed me to better understand how my mind works.

Continue reading

Trying Out a ‘Shut Up & Write’ Event

Have you been struggling with writer’s block recently? You have that piece that you are working on and the harder you try to think the harder it is to get words? Then you might want to try attending a Shut up & Write session. I joined a meeting for the first time a few months ago and it has been a great experience. If you need to write regularly, have an urgent deadline but get stuck, or like me, you love procrastinating and get easily distracted, you should try Shut Up & Write. This is a group that I recently discovered and my experience so far has been extremely positive. For those of you who are just hearing about this group for the first time, Shut Up & Write is a community of people around the world who host chapters where members meet together, update each other on their writing projects and get cracking on with their work. Events are free and hosted online and in-person.

Continue reading