Deseo graficar con Ploty los resultados de cálcular el índicador Técnico MACD. Deseo dos gráficas. En la superior precios, en la inferior MACD, signal e hist. Para ello he elaborado el script siguiente.
import pandas as pd
import yfinance as yf
import plotly.graph_objects as go
# Importamos cotizaciones
quote_closings_df = yf.download('^IBEX', start='2010-1-4', end='2019-12-30', progress=False)
df_value = quote_closings_df[['Close']]
# Cálculo del MACD
def get_macd(df_value, slow, fast, smooth):
price = df_value['Close'].values
exp1 = df_value.ewm(span=fast, adjust=False).mean()
exp2 = df_value.ewm(span=slow, adjust=False).mean()
macd = pd.DataFrame(exp1 - exp2).rename(columns={'Close': 'macd'})
signal = pd.DataFrame(exp1.ewm(span=smooth, adjust=False).mean()).rename(columns={'Close': 'signal'})
hist = pd.DataFrame(macd['macd'] - signal['signal']).rename(columns={0: 'hist'})
# Crear un nuevo DataFrame para almacenar los resultados
df_macd = pd.concat([df_value, macd, signal, hist], axis=1)
return macd, signal, hist, df_macd
slow = 26
fast = 12
smooth = 9
macd, signal, hist, df_macd = get_macd(df_value, slow, fast, smooth)
# Gráficas MACD
import yfinance as yf
import plotly.graph_objs as go
from plotly.subplots import make_subplots
df_macd.reset_index(inplace=True)
# Crear los traces de la subgráfica superior
trace1 = go.Scatter(
x = df_macd['Date'],
y = df_macd['Close'],
mode='lines',
name='IBEX 35',
line=dict(color='skyblue', width=2)
)
# Crear el layout de la subgráfica superior
layout1 = go.Layout(
yaxis_title='Price'
)
# Crear el layout de la subgráfica inferior
layout2 = go.Layout(
yaxis_title='IBEX 35',
height=200
)
# Crear las subgráficas
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1)
fig.add_trace(trace1, row=1, col=1)
fig.add_trace(trace2, row=2, col=1)
fig.add_trace(trace3, row=2, col=1)
fig.add_trace(trace4, row=2, col=1)
# Actualizar los layouts de las subgráficas
fig.update_layout(layout1, row=1, col=1)
fig.update_layout(layout2, row=2, col=1)
# Mostrar el gráfico
fig.show()
trace3 = go.Scatter(
x = df_macd['Date'],
y = df_macd['signal'],
mode='lines',
name='SIGNAL',
line=dict(color='skyblue', width=1.5)
)
trace4 = go.Bar(
x =df_macd['Date'],
y = df_macd['hist'],
marker=dict(
color=df_macd['hist'],
colorscale=[[0, '#ef5350'], [1, '#26a69a']],
reversescale=True
),
opacity=0.5,
name='HISTOGRAM'
)
# Crear el layout de la subgráfica inferior
layout2 = go.Layout(
yaxis = dict(title='IBEX 35'),
xaxis = dict(title='Date'),
height = 200
)
# Crear las subgráficas
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1)
fig.add_trace(trace1, row=1, col=1)
fig.add_trace(trace2, row=2, col=1)
fig.add_trace(trace3, row=2, col=1)
fig.add_trace(trace4, row=2, col=1)
# Actualizar los layouts de las subgráficas
fig.update_layout(layout1, row=1, col=1)
fig.update_layout(layout2, row=2, col=1)
# Mostrar el gráfico
fig.show()
Al ejecutarlo, me devuelve.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[20], line 62
59 fig.add_trace(trace4, row=2, col=1)
61 # Actualizar los layouts de las subgráficas
---> 62 fig.update_layout(layout1, row=1, col=1)
63 fig.update_layout(layout2, row=2, col=1)
65 # Mostrar el gráfico
File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/plotly/graph_objs/_figure.py:775, in Figure.update_layout(self, dict1, overwrite, **kwargs)
749 def update_layout(self, dict1=None, overwrite=False, **kwargs) -> "Figure":
750 """
751
752 Update the properties of the figure's layout with a dict and/or with
(...)
773
774 """
--> 775 return super(Figure, self).update_layout(dict1, overwrite, **kwargs)
File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/plotly/basedatatypes.py:1393, in BaseFigure.update_layout(self, dict1, overwrite, **kwargs)
1369 def update_layout(self, dict1=None, overwrite=False, **kwargs):
1370 """
1371 Update the properties of the figure's layout with a dict and/or with
1372 keyword arguments.
(...)
1391 The Figure object that the update_layout method was called on
1392 """
-> 1393 self.layout.update(dict1, overwrite=overwrite, **kwargs)
1394 return self
File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/plotly/basedatatypes.py:5114, in BasePlotlyType.update(self, dict1, overwrite, **kwargs)
5112 with self.figure.batch_update():
5113 BaseFigure._perform_update(self, dict1, overwrite=overwrite)
-> 5114 BaseFigure._perform_update(self, kwargs, overwrite=overwrite)
5115 else:
5116 BaseFigure._perform_update(self, dict1, overwrite=overwrite)
File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/plotly/basedatatypes.py:3877, in BaseFigure._perform_update(plotly_obj, update_obj, overwrite)
3873 continue
3874 # If no match, raise the error, which should already
3875 # contain the _raise_on_invalid_property_error
3876 # generated message
-> 3877 raise err
3879 # Convert update_obj to dict
3880 # --------------------------
3881 if isinstance(update_obj, BasePlotlyType):
ValueError: Invalid property specified for object of type plotly.graph_objs.Layout: 'row'
Did you mean "font"?
Valid properties:
activeselection
:class:`plotly.graph_objects.layout.Activeselection`
instance or dict with compatible properties
...........................................................
yaxis
:class:`plotly.graph_objects.layout.YAxis` instance or
dict with compatible properties
Did you mean "font"?
Bad property path:
row
^^^
¿Cuál es la causa y cómo puedo solucionarlo?- Tengo instalado ploty 5.13.0