У меня проблемы с отображением 4-го измерения в качестве цвета. Абстрактно, я пытаюсь построить функцию f (x, y, z) и отобразить ее как график поверхности с 4-м измерением, показанным в виде цветовой карты.
Проблема заключается в ответе, который я вычисляю ( Значение параметра Блэка-Шоулза) хранится в массиве 3D numpy, но каждое построенное измерение должно быть сохранено как двумерный массив «сеток».
Предыдущие ответы, на которые я ссылался: - Ответ 1 - Ответ 2
Функция определения:
import numpy as np
import math
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from scipy.stats import norm
def d1(sigma, time_to_expire, S, K, r):
return (math.log(S/K) + (r + sigma**2 / 2) * (time_to_expire)) / (sigma * math.sqrt(time_to_expire))
def d2(sigma, time_to_expire, S, K, r):
return d1(sigma, time_to_expire, S, K, r) - sigma * math.sqrt(time_to_expire)
def PV(K, r, time_to_expire):
return K * math.exp(-r*(time_to_expire))
def black_scholes(sigma, time_to_expire, S, K, r):
return norm.cdf(d1(sigma, time_to_expire, S, K, r)) * S - norm.cdf(d2(sigma, time_to_expire, S, K, r)) * PV(K, r, time_to_expire)
Печать:
# Plot option value as a function of multiple variables
fig = plt.figure()
ax = plt.axes(projection='3d')
S = np.linspace(0.01,2,25)
T = np.linspace(0,2,25)
volatility = np.array(range(0,25))
X, Y, Z = np.meshgrid(S, T, volatility)
print(X.shape, Y.shape, Z.shape)
value = np.zeros((len(S),len(T),len(volatility)))
# Calculate 4th dimension explicitly
for i in range(len(S)):
for j in range(len(T)):
for k in range(len(volatility)):
value[i,j,k] = black_scholes(volatility[k], T[j], S[i], 1, 0.02)
# Map 4th dimension to colour
C = Z
minn, maxx = C.min(), C.max()
norm = matplotlib.colors.Normalize(minn, maxx)
scamap = plt.cm.ScalarMappable(cmap='inferno')
scamap.set_array([])
fcolors = scamap.to_rgba(C)
# Plot surface
ax.view_init(45, -80)
ax.plot_surface(X,Y,Z, facecolors=fcolors)
ax.set_xlabel("S")
ax.set_ylabel("T")
ax.set_zlabel("Volatility")
ax.set_title("Option value as a function of\ntime to expiry (T), asset price (S) and volatility")
Сообщение об ошибке:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
in
44 scamap = plt.cm.ScalarMappable(cmap='inferno')
45 scamap.set_array([])
---> 46 fcolors = scamap.to_rgba(C)
47
48 ax.view_init(45, -80)
~/anaconda3/lib/python3.7/site-packages/matplotlib/cm.py in to_rgba(self, x, alpha, bytes, norm)
221 xx = x
222 else:
--> 223 raise ValueError("third dimension must be 3 or 4")
224 if xx.dtype.kind == 'f':
225 if norm and (xx.max() > 1 or xx.min() < 0):
ValueError: third dimension must be 3 or 4
Пожалуйста, дайте мне знать, если что-то неясно. Спасибо!