Python DataFrame中3年期收益率转等价1年期收益率的实现
Alright, let's work through converting those 3-year yields to equivalent 1-year yields using your formula. Here's a step-by-step solution using pandas:
First, let's make sure your data is formatted as a clear pandas DataFrame. Based on the input you provided, we can organize it with two columns: Date (the date of the yield) and 3Y_R (the 3-year yield value):
import pandas as pd # Build the DataFrame from your raw data data = { 'Date': ['1987-01-26', '1988-01-25', '1989-01-23', '1990-01-22', '1991-01-21', '1992-01-20', '1993-01-18'], '3Y_R': [-0.629487, 0.552159, 0.247890, 0.294639, 0.400885, 0.099296, 0.256380] } df = pd.DataFrame(data)
You want to calculate the equivalent 1-year yield r using the formula:r = (1 + R) ** (1/3) - 1
where R is the 3-year yield. You have two options here:
Option 1: Keep the original data (add a new column)
If you want to retain the 3-year yields alongside the new 1-year yields, create a new column 1Y_r:
df['1Y_r'] = (1 + df['3Y_R']) ** (1/3) - 1
Option 2: Replace the existing column
If you don't need the original 3-year yield data anymore, overwrite the column and rename it to reflect the change:
# Replace the 3-year yield values with 1-year equivalents df['3Y_R'] = (1 + df['3Y_R']) ** (1/3) - 1 # Rename the column to match the new data df.rename(columns={'3Y_R': '1Y_r'}, inplace=True)
Let's spot-check one value to confirm it works. Take the first entry where R = -0.629487:
(1 + (-0.629487)) ** (1/3) - 1 = 0.370513 ** (1/3) - 1 ≈ 0.718 - 1 = -0.282
Running the code will compute this value (and all others) accurately for your DataFrame.
内容的提问来源于stack exchange,提问作者AlexandrosB

