添加或减去 2 条插值曲线的最佳方法是什么?
What's the best way to add or subtract 2 interpolated curves?
在 Python 中添加或减去 2 条插值曲线的最佳方法是什么。一个例子是在国债利率上增加信用利差。两条曲线没有相同的项点。我可以通过获得特定的男高音来重建曲线,但我希望有更好的方法。
import scipy as sc
ATenor = [0.25,0.5,1,5,10,20]
ARate = [0.02,0.022,0.025,0.03,0.035,0.039]
ACurve = sc.interpolate.interp1d(ATenor,ARate)
BTenor = [0.25,1,4,5,7,10,15,20]
BRate = [0.025,0.28,0.032,0.036,0.038,0.042,0.04,0.038]
BCurve = sc.interpolate.interp1d(BTenor,BRate)
CCurve = ACurve + BCurve # <-- This does not work but to get the idea across
如果它尝试添加 2 条插值曲线,我会收到此错误:
+ 不支持的操作数类型:'interp1d' 和 'interp1d'
如果要创建新的 interp1d
对象,则可以合并 tenor 数组 (x-axis) 并重新计算速率值 (y-axis)。例如,这段代码将执行:
ABTenor = sorted(set(ATenor + BTenor)) # Merge points on the x-axis.
ABCurve = [ACurve(x) + BCurve(x) for x in ABTenor] # Compute y values.
ABCurve = scipy.interpolate.interp1d(ABTenor, ABCurve)
或者,您可以创建惰性求值函数:
def add_curves(A, B):
def compute(x):
return A(x) + B(x)
return compute
ABCurve = add_curves(ACurve, BCurve)
# ABCurve(10.0) will call ACurve(10.0) and BCurve(10.0) and sum the results.
在 Python 中添加或减去 2 条插值曲线的最佳方法是什么。一个例子是在国债利率上增加信用利差。两条曲线没有相同的项点。我可以通过获得特定的男高音来重建曲线,但我希望有更好的方法。
import scipy as sc
ATenor = [0.25,0.5,1,5,10,20]
ARate = [0.02,0.022,0.025,0.03,0.035,0.039]
ACurve = sc.interpolate.interp1d(ATenor,ARate)
BTenor = [0.25,1,4,5,7,10,15,20]
BRate = [0.025,0.28,0.032,0.036,0.038,0.042,0.04,0.038]
BCurve = sc.interpolate.interp1d(BTenor,BRate)
CCurve = ACurve + BCurve # <-- This does not work but to get the idea across
如果它尝试添加 2 条插值曲线,我会收到此错误:
+ 不支持的操作数类型:'interp1d' 和 'interp1d'
如果要创建新的 interp1d
对象,则可以合并 tenor 数组 (x-axis) 并重新计算速率值 (y-axis)。例如,这段代码将执行:
ABTenor = sorted(set(ATenor + BTenor)) # Merge points on the x-axis.
ABCurve = [ACurve(x) + BCurve(x) for x in ABTenor] # Compute y values.
ABCurve = scipy.interpolate.interp1d(ABTenor, ABCurve)
或者,您可以创建惰性求值函数:
def add_curves(A, B):
def compute(x):
return A(x) + B(x)
return compute
ABCurve = add_curves(ACurve, BCurve)
# ABCurve(10.0) will call ACurve(10.0) and BCurve(10.0) and sum the results.