Python Quantitative Finance Fundamentals
Doing quant work does not require a formal finance background, but you must understand a set of core concepts that recur repeatedly.
This article focuses on clarifying two types of terminology: quant trading terms and basic financial market concepts, and computes the two most fundamental quantities by hand - return and volatility.
After mastering this article, reading the later strategy and backtest chapters will have no language barrier.
Core Quant Trading Terminology
The following terms run through the whole tutorial; get familiar with them first, as later chapters will put them into practice repeatedly:
| Term | Meaning |
|---|---|
| Strategy | A trading system that defines when and under what conditions to buy or sell, which can be based on technical indicators, statistical models or machine learning |
| Factor | A numeric value used to measure an asset's characteristics, such as moving averages, market cap, P/E ratio, etc.; the raw material for building strategies |
| Signal | A trading instruction generated from strategies and factors, telling the program when to buy or sell |
| Backtesting | The process of simulating a strategy on historical data and evaluating its performance, a necessary step in validating a strategy |
| Alpha | The excess return of a strategy relative to a market benchmark; a positive Alpha means the strategy outperformed the benchmark |
| Beta | The sensitivity of a strategy to overall market volatility; a Beta greater than 1 means it is more volatile than the market |
| Sharpe Ratio | A risk-adjusted return metric, computed as (strategy return - risk-free rate) / strategy volatility; the higher the better |
| Maximum Drawdown | The largest drop from a peak to a trough over a historical period, measuring how much the strategy loses at its worst |
| Money Management | Methods to protect capital through position control, diversification and the like |
Basic Financial Market Concepts
The following concepts describe how the financial market itself operates:
| Concept | Meaning |
|---|---|
| Stock | A certificate of ownership in a company; buying a stock makes you a shareholder with the right to share in the company's profits |
| Portfolio | A basket of investments made up of multiple assets (stocks, bonds, futures, etc.) that reduces risk through diversification |
| Risk Management | Methods to identify, measure and control potential risks in investing; in quant it relies mainly on statistical models |
| Return | The profit of an investment, usually expressed as a percentage, which needs to be evaluated together with risk |
| Algorithmic Trading | Using predefined rules and mathematical models to drive computers to trade automatically |
| Quantitative Model | A model that uses mathematical and statistical tools to analyze and predict financial market behavior |
| High-Frequency Trading | Executing a large number of trades at extremely high speed to profit from tiny price differences |
| Arbitrage | Simultaneously buying and selling the same or similar assets to earn low-risk profit from price differences |
| Monte Carlo Simulation | A mathematical technique that generates a large number of random samples to evaluate portfolio risk and return |
Tip: you don't need to memorize the terms by rote. When you encounter an unfamiliar word, look it up in the table first; understanding will deepen naturally when you see them in real code in later chapters.
Hands-On Calculation: Returns and Volatility
Return and risk are the two baselines of the quant world, and both have standard ways to be calculated.
Simple Returns and Log Returns
Returns measure the magnitude of price changes; two common conventions are used:
Simple return is the proportion of price change, intuitive and easy to understand; log return is the natural logarithm of the price ratio, which is additive (multi-period returns can simply be added), and is more commonly used in research.
Example
import
pandas
as
pd
import
numpy
as
np
The closing prices of a stock over 6 consecutive days
prices
=
pd.
Series
(
[
100
,
102
,
101
,
105
,
107
,
106
]
,
index
=
pd.
date_range
(
"2024-01-01"
,
periods
=
6
)
,
)
Simple return: the proportional change of today's price relative to yesterday's
simple_ret
=
prices.
pct_change
(
)
.
dropna
(
)
(
simple_ret.
round
(
4
)
.
to_string
(
)
)
Log return: the natural logarithm of the price ratio
log_ret
=
np.
log
(
prices / prices.
shift
(
1
)
)
.
dropna
(
)
(
log_ret.
round
(
4
)
.
to_string
(
)
)
The output is shown below:
2024-01-02 0.0200
2024-01-03 -0.0098
2024-01-04 0.0396
2024-01-05 0.0190
2024-01-06 -0.0093
Freq: D
2024-01-02 0.0198
2024-01-03 -0.0099
2024-01-04 0.0388
2024-01-05 0.0189
2024-01-06 -0.0094
Freq: D
Buying at 100 yuan on day one and rising to 102 yuan gives a simple return of 2%, consistent with intuition.
The two returns are nearly identical when price changes are small; the difference grows as the change gets larger. Both are used in later chapters.
Volatility and Annualization
Volatility measures how violently returns fluctuate, usually expressed as the standard deviation of returns.
Daily volatility is too small to be intuitive; the industry convention is to multiply by the square root of 252 (about 252 trading days per year) to convert it into annualized volatility:
Example
Annualized Volatility = Daily Return Standard Deviation x sqrt(252)
ann_vol
=
simple_ret.
std
(
)
- np.
sqrt
(
252
)
(
f
"Annualized volatility: {ann_vol:.2%}"
)
The output is shown below:
年化波动率: 33.74%
Note: the example has only 6 days of data, so the computed volatility is for method illustration only. In real research at least one year of daily data is typically used to estimate volatility; the more data, the more stable the estimate.
A Quick Look at Performance Metrics
Combining return and volatility gives the three classic metrics for evaluating a strategy; here we build intuition first, with full calculation in theBacktesting and Performance Evaluationchapter covered in full:
| Pointer | Question Answered | Calculation Idea |
|---|---|---|
| Annualized Return | How much the strategy earns on average per year | Converting cumulative return over any period to one year using compounding |
| Sharpe Ratio | How much excess return is earned per unit of volatility taken | (Annualized Return - Risk-Free Rate) / Annualized Volatility |
| Maximum Drawdown | How severe the deepest historical drawdown was | The maximum drop of net value from peak to trough |
Choosing a strategy by return alone is the most common beginner mistake: most people cannot hold a strategy with 50% annualized return but a 60% maximum drawdown.
The Sharpe ratio matters because it looks at return and risk together: a Sharpe ratio above 1 is generally considered good, below 0.5 calls for caution.