Hi, everybody!
I’m having trouble to plot a graph_objects and I’m not finding where error is. Can somebody help me?
My code is:
def gerar_grafico(w1, mostrar_curvas):
fig = go.Figure()
# Desenha um ponto com o retorno e a volatilidade da carteira
fig.add_scatter(y=[carteira.iloc[w1]['retorno']],
x=[carteira.iloc[w1]['volatilidade']],
text=['CARTEIRA'],
mode='markers+text', name='CARTEIRA')
# Desenha os pontos das ações individuais
fig.add_scatter(y=carteira.iloc[[-1, 0]]['retorno'],
x=carteira.iloc[[-1, 0]]['volatilidade'],
text=tickers,
mode='markers+text', name='Ações')
# Desenha a curva
fig.add_scatter(y=carteira['retorno'],
x=carteira['volatilidade'],
mode='lines', name='Curva',
visible=mostrar_curvas)
# Plotar a carteira de volatilidade mÃnima
fig.add_scatter(y=[carteira.loc[min_vol_idx]['retorno']],
x=[carteira.loc[min_vol_idx]['volatilidade']],
mode='markers',
name='Carteira de MÃnima Variância',
visible=mostrar_curvas)
# Desenha a fronteira eficiente
fig.add_scatter(y=fe['retorno'],
x=fe['volatilidade'],
mode='lines', name='Fronteira Eficiente',
line={'color': 'red'},
visible=mostrar_curvas)
fig.update_traces(textfont_size=12,
textposition='middle right',
textfont_color='white',
hovertemplate='<b>retorno: </b> %{y:.1%}' +
'<br><b>volatilidade:</b> %{x:.1%}')
fig.layout.autosize = False
fig.layout.xaxis.title = 'Volatilidade'
fig.layout.yaxis.title = 'Retorno Esperado'
fig.layout.yaxis.range = [carteira['volatilidade'].min()-0.05, carteira['volatilidade'].max()+0.05]
fig.layout.yaxis.range = [carteira['retorno'].min()-0.05, carteira['retorno'].max()+0.05]
fig.layout.xaxis.tickformat = '.0%'
fig.layout.yaxis.tickformat = '.0%'
fig.layout.title = f"<b>{tickers[0]}:</b> {w1}% <b>{tickers[1]}:</b> {100-w1}%"
fig.layout.template = 'plotly_dark'
fig.show(config=dict(
displayModeBar=True
))
# Dispara o grafico
interact(gerar_grafico, w1=(0,100,1), mostrar_curvas=False);
The full text of result is:
ValueError Traceback (most recent call last)
~\anaconda3\lib\site-packages\ipywidgets\widgets\interaction.py in update(self, *args)
254 value = widget.get_interact_value()
255 self.kwargs[widget._kwarg] = value
--> 256 self.result = self.f(**self.kwargs)
257 show_inline_matplotlib_plots()
258 if self.auto_display and self.result is not None:
~\AppData\Local\Temp/ipykernel_7484/2661297897.py in gerar_grafico(w1, mostrar_curvas)
28
29 # Desenha a fronteira eficiente
---> 30 fig.add_scatter(y=fe['retorno'],
31 x=fe['volatilidade'],
32 mode='lines', name='Fronteira Eficiente',
~\anaconda3\lib\site-packages\plotly\graph_objs\_figure.py in add_scatter(self, cliponaxis, connectgaps, customdata, customdatasrc, dx, dy, error_x, error_y, fill, fillcolor, groupnorm, hoverinfo, hoverinfosrc, hoverlabel, hoveron, hovertemplate, hovertemplatesrc, hovertext, hovertextsrc, ids, idssrc, legendgroup, line, marker, meta, metasrc, mode, name, opacity, orientation, r, rsrc, selected, selectedpoints, showlegend, stackgaps, stackgroup, stream, t, text, textfont, textposition, textpositionsrc, textsrc, texttemplate, texttemplatesrc, tsrc, uid, uirevision, unselected, visible, x, x0, xaxis, xcalendar, xperiod, xperiod0, xperiodalignment, xsrc, y, y0, yaxis, ycalendar, yperiod, yperiod0, yperiodalignment, ysrc, row, col, secondary_y, **kwargs)
11171 from plotly.graph_objs import Scatter
11172
> 11173 new_trace = Scatter(
11174 cliponaxis=cliponaxis,
11175 connectgaps=connectgaps,
~\anaconda3\lib\site-packages\plotly\graph_objs\_scatter.py in __init__(self, arg, cliponaxis, connectgaps, customdata, customdatasrc, dx, dy, error_x, error_y, fill, fillcolor, groupnorm, hoverinfo, hoverinfosrc, hoverlabel, hoveron, hovertemplate, hovertemplatesrc, hovertext, hovertextsrc, ids, idssrc, legendgroup, line, marker, meta, metasrc, mode, name, opacity, orientation, r, rsrc, selected, selectedpoints, showlegend, stackgaps, stackgroup, stream, t, text, textfont, textposition, textpositionsrc, textsrc, texttemplate, texttemplatesrc, tsrc, uid, uirevision, unselected, visible, x, x0, xaxis, xcalendar, xperiod, xperiod0, xperiodalignment, xsrc, y, y0, yaxis, ycalendar, yperiod, yperiod0, yperiodalignment, ysrc, **kwargs)
3120 _v = x if x is not None else _v
3121 if _v is not None:
-> 3122 self["x"] = _v
3123 _v = arg.pop("x0", None)
3124 _v = x0 if x0 is not None else _v
~\anaconda3\lib\site-packages\plotly\basedatatypes.py in __setitem__(self, prop, value)
4802 # ### Handle simple property ###
4803 else:
-> 4804 self._set_prop(prop, value)
4805 else:
4806 # Make sure properties dict is initialized
~\anaconda3\lib\site-packages\plotly\basedatatypes.py in _set_prop(self, prop, val)
5146 return
5147 else:
-> 5148 raise err
5149
5150 # val is None
~\anaconda3\lib\site-packages\plotly\basedatatypes.py in _set_prop(self, prop, val)
5141
5142 try:
-> 5143 val = validator.validate_coerce(val)
5144 except ValueError as err:
5145 if self._skip_invalid:
~\anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in validate_coerce(self, v)
391 v = to_scalar_or_list(v)
392 else:
--> 393 self.raise_invalid_val(v)
394 return v
395
~\anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in raise_invalid_val(self, v, inds)
275 name += "[" + str(i) + "]"
276
--> 277 raise ValueError(
278 """
279 Invalid value of type {typ} received for the '{name}' property of {pname}
ValueError:
Invalid value of type 'numpy.float64' received for the 'x' property of scatter
Received value: 0.4396981653578547
The 'x' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
I have a function that generates random portfolios weights, my hyphotesis is that this function is the cause.
def peso(df, w1):
pesos = [w1,1-w1]
df2 = df.dot(pesos).copy()
return df2.mean() * 252, df2.std() * np.sqrt(252)
I appreciate any help.