1

Para construir la gráfica del Indicador Técnico MACD con Plotly, he elaborado el código siguiente.

# Gráfica MACD con plotly
import pandas as pd
import plotly.graph_objs as go
import yfinance as yf

class MacdPlot:
    def __init__(self, ticker, start_date, end_date, slow=26, fast=12, smooth=9):
        self.ticker = ticker
        self.start_date = start_date
        self.end_date = end_date
        self.slow = slow
        self.fast = fast
        self.smooth = smooth
        self.df = None
        self.macd = None
        self.signal = None
        self.hist = None

    def download_quotes(self):
        self.df = yf.download(self.ticker, start=self.start_date, end=self.end_date, progress=False)['Close']

    def calculate_macd(self):
        exp1 = self.df.ewm(span=self.fast, adjust=False).mean()
        exp2 = self.df.ewm(span=self.slow, adjust=False).mean()
        self.macd = exp1 - exp2
        self.signal = self.macd.ewm(span=self.smooth, adjust=False).mean()
        self.hist = self.macd - self.signal

    def plot_macd(self):
        fig = go.Figure()

        # Primera ventana: Precio, MACD y Señal
        fig.add_trace(go.Scatter(x=self.df.index, y=self.df, name='Price', line=dict(color='blue', width=1.5)))
        fig.add_trace(go.Scatter(x=self.macd.index, y=self.macd, name='MACD', line=dict(color='grey', width=1.5)))
        fig.add_trace(go.Scatter(x=self.signal.index, y=self.signal, name='Signal', line=dict(color='skyblue', width=1.5)))

        # Segunda ventana: Histograma
        fig.add_trace(go.Bar(x=self.hist.index, y=self.hist, name='Histogram', marker=dict(color=self.hist.apply(lambda x: 'g' if x > 0 else 'r'))))

        fig.update_layout(
            title=f"MACD plot for {self.ticker}",
            xaxis=dict(title='Date'),
            showlegend=True,
        )

        fig.show()

if __name__ == '__main__':
    macd_plot = MacdPlot('AAA', '2016-1-4', '2022-12-31')
    macd_plot.download_quotes()
    macd_plot.calculate_macd()
    macd_plot.plot_macd()

Me devuelve el error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[115], line 53
     51 macd_plot.download_quotes()
     52 macd_plot.calculate_macd()
---> 53 macd_plot.plot_macd()

Cell In[115], line 38, in MacdPlot.plot_macd(self)
     35 fig.add_trace(go.Scatter(x=self.signal.index, y=self.signal, name='Signal', line=dict(color='skyblue', width=1.5)))
     37 # Segunda ventana: Histograma
---> 38 fig.add_trace(go.Bar(x=self.hist.index, y=self.hist, name='Histogram', marker=dict(color=self.hist.apply(lambda x: 'g' if x > 0 else 'r'))))
     40 fig.update_layout(
     41     title=f"MACD plot for {self.ticker}",
     42     xaxis=dict(title='Date'),
     43     showlegend=True,
     44 )
     46 fig.show()

File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/plotly/graph_objs/_bar.py:3144, in Bar.__init__(self, arg, alignmentgroup, base, basesrc, cliponaxis, constraintext, customdata, customdatasrc, dx, dy, error_x, error_y, hoverinfo, hoverinfosrc, hoverlabel, hovertemplate, hovertemplatesrc, hovertext, hovertextsrc, ids, idssrc, insidetextanchor, insidetextfont, legend, legendgroup, legendgrouptitle, legendrank, legendwidth, marker, meta, metasrc, name, offset, offsetgroup, offsetsrc, opacity, orientation, outsidetextfont, selected, selectedpoints, showlegend, stream, text, textangle, textfont, textposition, textpositionsrc, textsrc, texttemplate, texttemplatesrc, uid, uirevision, unselected, visible, width, widthsrc, x, x0, xaxis, xcalendar, xhoverformat, xperiod, xperiod0, xperiodalignment, xsrc, y, y0, yaxis, ycalendar, yhoverformat, yperiod, yperiod0, yperiodalignment, ysrc, **kwargs)
   3142 _v = marker if marker is not None else _v
   3143 if _v is not None:
-> 3144     self["marker"] = _v
   3145 _v = arg.pop("meta", None)
   3146 _v = meta if meta is not None else _v

File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/plotly/basedatatypes.py:4865, in BasePlotlyType.__setitem__(self, prop, value)
   4863 # ### Handle compound property ###
   4864 if isinstance(validator, CompoundValidator):
-> 4865     self._set_compound_prop(prop, value)
   4867 # ### Handle compound array property ###
   4868 elif isinstance(validator, (CompoundArrayValidator, BaseDataValidator)):

File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/plotly/basedatatypes.py:5276, in BasePlotlyType._set_compound_prop(self, prop, val)
   5273 # Import value
   5274 # ------------
   5275 validator = self._get_validator(prop)
-> 5276 val = validator.validate_coerce(val, skip_invalid=self._skip_invalid)
   5278 # Save deep copies of current and new states
   5279 # ------------------------------------------
   5280 curr_val = self._compound_props.get(prop, None)

File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/_plotly_utils/basevalidators.py:2475, in CompoundValidator.validate_coerce(self, v, skip_invalid, _validate)
   2472     v = self.data_class()
   2474 elif isinstance(v, dict):
-> 2475     v = self.data_class(v, skip_invalid=skip_invalid, _validate=_validate)
   2477 elif isinstance(v, self.data_class):
   2478     # Copy object
   2479     v = self.data_class(v)

File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/plotly/graph_objs/bar/_marker.py:1154, in Marker.__init__(self, arg, autocolorscale, cauto, cmax, cmid, cmin, color, coloraxis, colorbar, colorscale, colorsrc, line, opacity, opacitysrc, pattern, reversescale, showscale, **kwargs)
   1152 _v = color if color is not None else _v
   1153 if _v is not None:
-> 1154     self["color"] = _v
   1155 _v = arg.pop("coloraxis", None)
   1156 _v = coloraxis if coloraxis is not None else _v

File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/plotly/basedatatypes.py:4873, in BasePlotlyType.__setitem__(self, prop, value)
   4869         self._set_array_prop(prop, value)
   4871     # ### Handle simple property ###
   4872     else:
-> 4873         self._set_prop(prop, value)
   4874 else:
   4875     # Make sure properties dict is initialized
   4876     self._init_props()

File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/plotly/basedatatypes.py:5217, in BasePlotlyType._set_prop(self, prop, val)
   5215         return
   5216     else:
-> 5217         raise err
   5219 # val is None
   5220 # -----------
   5221 if val is None:
   5222     # Check if we should send null update

File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/plotly/basedatatypes.py:5212, in BasePlotlyType._set_prop(self, prop, val)
   5209 validator = self._get_validator(prop)
   5211 try:
-> 5212     val = validator.validate_coerce(val)
   5213 except ValueError as err:
   5214     if self._skip_invalid:

File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/_plotly_utils/basevalidators.py:1354, in ColorValidator.validate_coerce(self, v, should_raise)
   1351 invalid_els = self.find_invalid_els(v, validated_v)
   1353 if invalid_els and should_raise:
-> 1354     self.raise_invalid_elements(invalid_els)
   1356 # ### Check that elements have valid colors types ###
   1357 elif self.numbers_allowed() or invalid_els:

File ~/anaconda3/envs/yfinance/lib/python3.8/site-packages/_plotly_utils/basevalidators.py:303, in BaseValidator.raise_invalid_elements(self, invalid_els)
    301     def raise_invalid_elements(self, invalid_els):
    302         if invalid_els:
--> 303             raise ValueError(
    304                 """
    305     Invalid element(s) received for the '{name}' property of {pname}
    306         Invalid elements include: {invalid}
    307 
    308 {valid_clr_desc}""".format(
    309                     name=self.plotly_name,
    310                     pname=self.parent_name,
    311                     invalid=invalid_els[:10],
    312                     valid_clr_desc=self.description(),
    313                 )
    314             )

ValueError: 
    Invalid element(s) received for the 'color' property of bar.marker
        Invalid elements include: ['r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r']

    The 'color' property is a color and may be specified as:
      - A hex string (e.g. '#ff0000')
      - An rgb/rgba string (e.g. 'rgb(255,0,0)')
      - An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
      - An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
      - A named CSS color:
            aliceblue, antiquewhite, aqua, aquamarine, azure,...

¿Cómo puedo solucionar este problema?. Agradeceré ayuda.

1 respuesta 1

1

El mensaje de error, que es bastante bueno, dice, entre otras cosas:

Invalid element(s) received for the 'color' property of bar.marker
       Invalid elements include: ['r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r']

   The 'color' property is a color and may be specified as:
     - A hex string (e.g. '#ff0000')
     - An rgb/rgba string (e.g. 'rgb(255,0,0)')
     - An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
     - An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
     - A named CSS color:
           aliceblue, antiquewhite, aqua, aquamarine, azure,...

Y también nos dice toda la traza, desde el inicio, pasando por todas las llamadas, hasta el punto donde se genera el error dentro de las bibliotecas. Yo comienzo revisando mi propio código, por lo que voy al inicio de la traza. El primer frame no parece tener relación, pero apenas en el segundo frame, encuentro:

Cell In[115], line 38, in MacdPlot.plot_macd(self)
     35 fig.add_trace(go.Scatter(x=self.signal.index, y=self.signal, name='Signal', line=dict(color='skyblue', width=1.5)))
     37 # Segunda ventana: Histograma
---> 38 fig.add_trace(go.Bar(x=self.hist.index, y=self.hist, name='Histogram', marker=dict(color=self.hist.apply(lambda x: 'g' if x > 0 else 'r'))))
     40 fig.update_layout(
     41     title=f"MACD plot for {self.ticker}",
     42     xaxis=dict(title='Date'),
     43     showlegend=True,
     44 )
     46 fig.show()

Allí, la línea que está marcada con ---> tiene este fragmento:

color=self.hist.apply(lambda x: 'g' if x > 0 else 'r')

Que rápidamente resuena con la excelente descripción del error, gracias a color y r.

¡Eureka!

A estas alturas, la solución debiera ser evidente para ti. Yo, que no sé lo que quieres lograr, haría un cambio simple para que el color reciba un valor válido, por ejemplo:

color=self.hist.apply(lambda x: 'green' if x > 0 else 'red')

O esto:

color=self.hist.apply(lambda x: 'rgb(0,255,0)' if x > 0 else 'rgb(255,0,0)')

O esto:

color=self.hist.apply(lambda x: '#00ff00' if x > 0 else '#ff0000')

Estoy asumiendo los colores que quieres utilizar. Ya tú sabrás que valores realmente hacen sentido para lo que quieres lograr.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.