我有一个关于从插值返回结果的问题。我有以下小数据帧,我对其进行了线性回归(多项式回归)。
K Implied_Volatility_adjusted_settlement
1621531 50.0 0.479460
1621532 55.0 0.455387
1621533 60.0 0.435977
1621534 70.0 0.403611
1621535 75.0 0.389726
1621536 80.0 0.378349
1621537 85.0 0.368299
1621538 90.0 0.360906
1621539 95.0 0.355987
1621540 100.0 0.354016
1621541 105.0 0.355128
1621542 110.0 0.353875
1621543 115.0 0.355639
1621544 120.0 0.356574
1621545 130.0 0.361490
1621546 140.0 0.370661
1621547 160.0 0.391378
为了生成图表,我做了以下操作:
# Assign columns to variables
x = df[['K']]
y = df[['Implied_Volatility_adjusted_settlement']]
# Regressions
poly = PolynomialFeatures(degree=4)
x_poly = poly.fit_transform(x)
poly.fit(x_poly, y)
regression = LinearRegression()
regression.fit(x_poly, y)
# Create plots
plt.scatter(x, y, color='blue')
plt.plot(x, regression.predict(poly.fit_transform(x)), color='red')
plt.title('Polynomial Regression')
plt.xlabel('K')
plt.ylabel('Implied volatility')
抱歉,我不允许上传图片(少于 10 个声誉),所以我将描述图表:在 x 轴上,您获得值 K (60-150),y 轴获得隐含波动率 (0.35-0.5)。但是,我想知道 K=65 和 K=150 点的隐含波动率(通过使用线性回归的"公式")。
我正在寻找以下内容:我想知道如何使用回归来插值 K=65 和 K=150 时的隐含波动率。
解决方案@knh190提供了以下解决方案:
#Regressions
poly = PolynomialFeatures(degree=3)
x_poly = poly.fit_transform(x)
poly.fit(x_poly, y)
regression = LinearRegression()
regression.fit(x_poly, y)
inter_poly = poly.fit_transform(np.array([65, 150]).reshape((-1, 1))) #new lines of code
inter_result = regression.predict(inter_poly) #new lines of code
print(inter_result)
这将得到我正在寻找的隐含波动率
[[0.41726855]
[0.38131657]]
如果您还对点为 K=65 和 K=160 的图形感兴趣,则可以使用以下代码:
plt.scatter(x, y, color='blue') # Data points
plt.plot(x, regression.predict(x_poly), color='red') # Plot of the expected points
plt.scatter([65, 150], regression.predict(inter_poly), color='purple', marker='x')
plt.title('Polynomial Regression')
plt.xlabel('K')
plt.ylabel('Implied volatility')
plt.show()
您应该使用fit_transform
将插值位置拟合到所需的输入形状,从LinearRegression
:
xs = poly.fit_transform(np.array([65, 100]).reshape((-1, 1)))
plt.plot([65, 100], regression.predict(xs), color='red')