変化率
価格は比較しにくいものです。5ドルの動きは20ドルの株と500ドルの株では意味が違います。単純リターンは規模を取り除きます。前の価格に対する価格変化の割合なので、+2% はどの資産でも同じ意味になります。
r_t = (P_t - P_{t-1}) / P_{t-1} = P_t / P_{t-1} - 1
pandas では prices.shift(1) が各値を1つ下にずらすので、各行が前の価格を見られます。それで割ればすべてのリターンが一度に求まり、最初は前の価格がないので NaN です。prices.pct_change() なら1回の呼び出しで同じ結果になります。
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% の日が来ても、2日間で +1% にはなりません。各リターンは異なる出発価格にかかるので、成長係数 1 + r を掛け合わせます。総リターンは (1 + r1) * (1 + r2) * ... - 1 です。最初の行の NaN は除き(prod は無視します)、結果は最終価格を最初の価格で割って1を引いた値と一致します。リターンの単純な合計は近い値になりますが誤りで、ボラティリティが大きいほど差が開きます。
# 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資産をまたぐ場合と年をまたぐ場合
単純リターンは資産をまたいで足し算できます。ポートフォリオの1期間のリターンは、各保有の ウェイト * リターン の合計です。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で各資産のリターンを加重して1つの数にする25点annualized_returnでリターンを年率で表す25点