我有一个关于从插值返回结果的问题。我有以下小型DataFrame,我对其进行了线性回归(多项式回归)。
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()
答案 0 :(得分:0)
您应该使用fit_transform
使插值位置适合LinearRegression
中所需的输入形状:
xs = poly.fit_transform(np.array([65, 100]).reshape((-1, 1)))
plt.plot([65, 100], regression.predict(xs), color='red')