百分比变化
价格很难比较:5 美元的波动对 20 美元的股票和 500 美元的股票意义不同。简单收益率去掉了量纲,它是价格变化占前一期价格的比例,所以 +2% 对任何资产含义都一样。
r_t = (P_t - P_{t-1}) / P_{t-1} = P_t / P_{t-1} - 1
在 pandas 中,prices.shift(1) 把每个值向下移一位,于是每一行都能看到前一期价格。除以它就一次算出所有收益率,第一个因为没有前一期价格而是 NaN。prices.pct_change() 一次调用就能做同样的事。
import pandas as pd
prices = pd.Series([100.0, 102.0, 100.98, 103.0], index=["Mon", "Tue", "Wed", "Thu"])
returns = prices / prices.shift(1) - 1
print(returns.round(4))
# Mon NaN
# Tue 0.02
# Wed -0.01
# Thu 0.02
# dtype: float64
print(prices.pct_change().round(4).tolist()) # [nan, 0.02, -0.01, 0.02]收益率是复合的,不是相加的
先涨 2% 再跌 1%,两天的收益并不是 +1%。每个收益率作用在不同的起点价格上,所以增长因子 1 + r 要相乘:总收益率是 (1 + r1) * (1 + r2) * ... - 1。跳过第一行的 NaN(prod 会忽略它),结果就等于期末价格除以期初价格再减一。把收益率直接相加很接近但并不正确,而且波动越大差距越大。
# Compounding the returns gives the same total as the end price over the start price
returns = prices.pct_change().dropna()
print(round((1 + returns).prod() - 1, 6)) # 0.03
print(round(prices.iloc[-1] / prices.iloc[0] - 1, 6)) # 0.03
print(round(returns.sum(), 6)) # 0.030004 close, but not the same
print((1 + returns).cumprod().round(4).tolist()) # [1.02, 1.0098, 1.03] the growth of 1 dollar# Gains and losses are not symmetric: +10% then -10% does not get you back
up, down = 0.10, -0.10
print(round((1 + up) * (1 + down) - 1, 4)) # -0.01
# After a -50% loss you need +100% to recover
print(1 / (1 - 0.5) - 1) # 1.0跨资产与跨年份
简单收益率在资产之间可以相加:组合在一期的收益率等于各持仓 权重 * 收益率 之和。用 Series 时,weights * returns 按标签对齐,因此代码顺序无关紧要(用 .values 就失去了这层保护)。在时间上它们不是相加而是复合,所以要由较短的区间得到年化利率,需要把增长因子取 交易日数 / 天数 次方。
# Weights times returns, matched by label (the order of the symbols differs on purpose)
weights = pd.Series({"AAPL": 0.5, "MSFT": 0.3, "TSLA": 0.2})
day = pd.Series({"TSLA": -0.03, "AAPL": 0.012, "MSFT": 0.004})
print(round((weights * day).sum(), 4)) # 0.0012 correct: AAPL with AAPL, TSLA with TSLA
print(round((weights.values * day.values).sum(), 4)) # -0.0106 wrong: position by position, TSLA met AAPL's weight# Annualising: 5% in 60 trading days, if it kept compounding at that pace for a year of 252 days
total, days = 0.05, 60
print(round((1 + total) ** (252 / days) - 1, 4)) # 0.2274收益率是相对于起点价格的给收益率一定要标明期间(日、月、年),并且不要混用不同期间:日收益 1% 与年收益 1% 完全不同。把期间写进变量名,例如
daily_returns。- 简单收益率是
价格 / 前一期价格 - 1:prices / prices.shift(1) - 1或prices.pct_change();第一个元素是NaN。 - 在时间上收益率是复合的:
(1 + returns).prod() - 1,绝不是returns.sum()。 - 跨资产时按权重相加:
(weights * returns).sum(),按标签对齐。
下一节:对数收益率,它在时间上可以相加,是统计分析中的常用选择。
实验:评分内容
- 用
simple_returns把价格转换为各期收益率25 分 - 用
cumulative_return把各期收益复合成总收益25 分 - 用
portfolio_return把各资产收益加权成一个数25 分 - 用
annualized_return把收益率表示为年化利率25 分