Stack Overflow en español Asked by efueyo on December 10, 2020
Iniciándome en Plotly. Importo en un dataframe cotizaciones de un valor de bolsa. Calculo varias medias móviles y construyo un único dataframe con las cotizaciones importadas y y las medias móviles calculadas. Utilizando plotly.express intento visualizar un gráfico que incluya todas que incluya la gráfica de las cotizaciones y las gráficas de las medias móviles. Este es el script.
# Importar cotizaciones
import pandas as pd
import pandas_datareader.data as pdr
start = "2016-1-4"
end = "2020-10-19"
iberdrola = pdr.DataReader("IBE.MC", "yahoo", start, end)
iberdrola = iberdrola[["Close"]]
# Calcular medias móviles
dfSMA =iberdrola[["Close"]].reset_index()
SMA2 = dfSMA["Close"].rolling(2).mean().dropna()
SMA5 = dfSMA["Close"].rolling(5).mean().dropna()
SMA10= dfSMA["Close"].rolling(10).mean().dropna()
SMA20= dfSMA["Close"].rolling(20).mean().dropna()
SMA50= dfSMA["Close"].rolling(50).mean().dropna()
# Crear el DataFrame valor- medias móviles
dfs = [dfSMA, SMA2, SMA5, SMA10, SMA20, SMA50 ]
dfs = iter(dfs)
val_SMA = next(dfs)
for df_ in (dfs):
val_SMA = val_SMA.merge(df_, left_index = True, right_index = True)
# Mostrar gráfica
import plotly.express as px
#df = px.data.stocks()
val_SMA.reset_index(inplace=True)
fig = px.line(val_SMA, x="Date", y=val_SMA.columns,
hover_data={"Date": "|%B %d, %Y"},
title='custom tick labels')
fig.update_xaxes(
dtick="M1",
tickformat="%bn%Y")
fig.show()
Me devuelve el error:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Agradeceré ayuda para solucionar este problema.
Información completa del error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2-30075cd79f70> in <module>
27
28 val_SMA.reset_index(inplace=True)
---> 29 fig = px.line(val_SMA, x="Date", y=val_SMA.columns,
30 hover_data={"Date": "|%B %d, %Y"},
31 title='custom tick labels')
~/anaconda3/envs/plotly/lib/python3.8/site-packages/plotly/express/_chart_types.py in line(data_frame, x, y, line_group, color, line_dash, hover_name, hover_data, custom_data, text, facet_row, facet_col, facet_col_wrap, facet_row_spacing, facet_col_spacing, error_x, error_x_minus, error_y, error_y_minus, animation_frame, animation_group, category_orders, labels, orientation, color_discrete_sequence, color_discrete_map, line_dash_sequence, line_dash_map, log_x, log_y, range_x, range_y, line_shape, render_mode, title, template, width, height)
250 a polyline mark in 2D space.
251 """
--> 252 return make_figure(args=locals(), constructor=go.Scatter)
253
254
~/anaconda3/envs/plotly/lib/python3.8/site-packages/plotly/express/_core.py in make_figure(args, constructor, trace_patch, layout_patch)
1824 apply_default_cascade(args)
1825
-> 1826 args = build_dataframe(args, constructor)
1827 if constructor in [go.Treemap, go.Sunburst] and args["path"] is not None:
1828 args = process_dataframe_hierarchy(args)
~/anaconda3/envs/plotly/lib/python3.8/site-packages/plotly/express/_core.py in build_dataframe(args, constructor)
1356 # now that things have been prepped, we do the systematic rewriting of `args`
1357
-> 1358 df_output, wide_id_vars = process_args_into_dataframe(
1359 args, wide_mode, var_name, value_name
1360 )
~/anaconda3/envs/plotly/lib/python3.8/site-packages/plotly/express/_core.py in process_args_into_dataframe(args, wide_mode, var_name, value_name)
1177 else:
1178 col_name = str(argument)
-> 1179 df_output[col_name] = to_unindexed_series(df_input[argument])
1180 # ----------------- argument is likely a column / array / list.... -------
1181 else:
~/anaconda3/envs/plotly/lib/python3.8/site-packages/plotly/express/_core.py in to_unindexed_series(x)
1028 required to get things to match up right in the new DataFrame we're building
1029 """
-> 1030 return pd.Series(x).reset_index(drop=True)
1031
1032
~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/series.py in __init__(self, data, index, dtype, name, copy, fastpath)
200 name = ibase.maybe_extract_name(name, data, type(self))
201
--> 202 if is_empty_data(data) and dtype is None:
203 # gh-17261
204 warnings.warn(
~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/construction.py in is_empty_data(data)
584 is_none = data is None
585 is_list_like_without_dtype = is_list_like(data) and not hasattr(data, "dtype")
--> 586 is_simple_empty = is_list_like_without_dtype and not data
587 return is_none or is_simple_empty
588
~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/generic.py in __nonzero__(self)
1476
1477 def __nonzero__(self):
-> 1478 raise ValueError(
1479 f"The truth value of a {type(self).__name__} is ambiguous. "
1480 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
He encontrado una solución al problema, creando el dataframe de la siguiente manera.
He resuelto el problema creando el dataframe de la siguiente manera.
# Calcular medias móviles
dfSMA =iberdrola[["Close"]].reset_index()
dfSMA["SMA2"] = dfSMA["Close"].rolling(2).mean().dropna()
dfSMA["SMA5"] = dfSMA["Close"].rolling(5).mean().dropna()
dfSMA["SMA10"]= dfSMA["Close"].rolling(10).mean().dropna()
dfSMA["SMA20"]= dfSMA["Close"].rolling(20).mean().dropna()
dfSMA["SMA50"]= dfSMA["Close"].rolling(50).mean().dropna()
import plotly.express as px
fig = px.line(dfSMA, x="Date", y=dfSMA.columns,
hover_data={"Date": "|%B %d, %Y"},
title='custom tick labels')
fig.update_xaxes(
dtick="M1",
tickformat="%bn%Y")
fig.show()
No obstante, sigue sin respuesta el por qué da error con el otro método seguido para crear el DataFrame.
Correct answer by efueyo on December 10, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP