INNER CODE UNIT · Python
__convert_bond_rates_to_prices
paperswithbacktest/pwb-toolbox · pwb_toolbox/datasets/__init__.py:870
def __convert_bond_rates_to_prices(df: pd.DataFrame, face_value: float = 100.0) -> pd.DataFrame:
"""
Convert bond yields (in percent) to prices, in-place, for rows whose
symbols encode maturity like 'US10Y', 'US2Y', 'US3M', etc.
Assumes columns: ['symbol', 'open', 'high', 'low', 'close'] and that
open/high/low/close are yields in percent.
"""
# Vectorized extraction of maturity from symbol: last part "10Y", "2Y", "3M", ...
m = df["symbol"].str.extract(r"(\d+)([YM])$") # 0: number, 1: unit
num = pd.to_numeric(m[0], errors="coerce")
unit = m[1]
years = pd.Series(np.nan, index=df.index, dtype="float64")
years[unit == "Y"] = num[unit == "Y"]
years[unit == "M"] = num[unit == "M"] / 12.0
# Only apply to rows where we successfully parsed the maturity