0

En el desarrollo de un modelo para la implementación de estrategias, al intentar emular con plotly una gráfica desarrollada con matplotlib, me devuelve un error. (este script es una adaptación de algoritmo trading)

Este es el script y la gráfica que me devuelve con matplotlib.

import pandas as pd
import yfinance as yf
import numpy as np

# Importación de cotizaciones
start = "2017-1-2"
end = "2021-4-28"
nom_val = "GOOG"
ticker_val = "GOOG"
df = yf.download(ticker_val, start= start, end = end)

#df.rename(columns={'High': 'high',  'Low': 'low', 'Open':'open', "Close":nom_val, 'Volume':'volume', nom_val:nom_val}, inplace=True)
df.rename(columns={ "Close":nom_val}, inplace=True)

df.dropna(inplace=True)
df_value = df[[nom_val]].copy(deep=True)

# Implementación de una estrategia

def get_signal(price, WindowsSlow, WindowsFast, WindosSmooth):
    # window fast
    exp1 = price.ewm(span = WindowsFast, adjust = False).mean()
    
    # window slow
    exp2 = price.ewm(span = WindowsSlow, adjust = False).mean()
    
    # MACD LINE = FAST LENGTH window - SLOW LENGTH window
    EMAsDiff = pd.DataFrame(exp1 - exp2).rename(columns = {nom_val:'EMAsDiff'})
    
    #window  smooth
    signal = pd.DataFrame(EMAsDiff.ewm(span = WindosSmooth, adjust = False).mean()).rename(columns = {'EMAsDiff':'signal'})

    # HISTOGRAM = EMAsDiff line - Signal line
    hist = pd.DataFrame(EMAsDiff['EMAsDiff'] - signal['signal']).rename(columns = {0:'hist'})
    
    """Unimos las tres listas en un único DataFrame"""
    frames =  [price[nom_val], EMAsDiff, signal, hist]
    df_signal = pd.concat(frames, join = 'inner', axis = 1)
    return df_signal, EMAsDiff, signal, hist

WindowsSlow = 200
WindowsFast = 70
WindosSmooth = 9

price = df_value.copy(deep=True)

df_signal, EMAsDiff, signal, hist = get_signal(price, 26, 12, 9)

# Gráficas

import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = (20, 10)
plt.style.use('fivethirtyeight')

def plot_signal(prices, macd, signal, hist):
    ax1 = plt.subplot2grid((8,1), (0,0), rowspan = 5, colspan = 1)
    ax2 = plt.subplot2grid((8,1), (5,0), rowspan = 3, colspan = 1)

    ax1.plot(prices)
    ax2.plot(EMAsDiff, color = 'grey', linewidth = 1.5, label = 'EMAsDiff')
    ax2.plot(signal, color = 'skyblue', linewidth = 1.5, label = 'SIGNAL')

    for i in range(len(prices)):
        if str(hist[i])[0] == '-':
            ax2.bar(prices.index[i], hist[i], color = '#ef5350')
        else:
            ax2.bar(prices.index[i], hist[i], color = '#26a69a')

    plt.legend(loc = 'lower right')

plot_signal(df_signal[nom_val], df_signal['EMAsDiff'], df_signal['signal'], df_signal['hist'])

introducir la descripción de la imagen aquí

Con plotly, represento la primera gráfica ejecutando

# Columna Close del DataFrame aapl
import plotly.express as px
px.line(df_signal , y=nom_val ,title=nom_val + " Cotizaciones al cierre")

Asimismo, represento las otras dos gráfiacs, juntas en un mismo gráfico, ejecutando

px.line(df_signal , y=['EMAsDiff', 'signal'] ,title=nom_val + " Cotizaciones al cierre")

Intento representar las tres gráficas juntas en la parte inferior del gráfico matplotlib ejecutando

import plotly.graph_objects as go

# Create random data with numpy
import numpy as np
 
# Create traces
fig = go.Figure()
fig.add_trace(go.Scatter(x=df_signal.index, y=df_signal["signal"],
                    mode='lines',
                    name='signal'))
fig.add_trace(go.Scatter(x=df_signal.index, y=df_signal["EMAsDiff"],
                    mode='lines',
                    name='EMAsDiff'))
fig.add_trace(go.Scatter(df_signal.index, y=df_signal["hist"],
                    mode='histogram', name='histogram'))

fig.show()

y me devuelve el error

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-30-2dbdb852ad2e> in <module>
     13                     name='EMAsDiff'))
     14 fig.add_trace(go.Scatter(df_signal.index, y=df_signal["hist"],
---> 15                     mode='histogram', name='histogram'))
     16 
     17 fig.show()

~/anaconda3/envs/yfinance/lib/python3.7/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, legendgrouptitle, legendrank, line, marker, meta, metasrc, mode, name, opacity, orientation, selected, selectedpoints, showlegend, stackgaps, stackgroup, stream, text, textfont, textposition, textpositionsrc, textsrc, texttemplate, texttemplatesrc, uid, uirevision, unselected, visible, x, x0, xaxis, xcalendar, xhoverformat, xperiod, xperiod0, xperiodalignment, xsrc, y, y0, yaxis, ycalendar, yhoverformat, yperiod, yperiod0, yperiodalignment, ysrc, **kwargs)
   2997 The first argument to the plotly.graph_objs.Scatter
   2998 constructor must be a dict or
-> 2999 an instance of :class:`plotly.graph_objs.Scatter`"""
   3000             )
   3001 

ValueError: The first argument to the plotly.graph_objs.Scatter 
constructor must be a dict or 
an instance of :class:`plotly.graph_objs.Scatter`

¿Cuál es la causa?¿Cómo puedo resolver este problema?. Agradeceré ayuda.

1 respuesta 1

0

¡Qué sencillo era y cómo me ha costado encontrar esta solución!. 2Para conseguirlo, es necesario crear figuras diferentes, como en este ejemplo que muestro a continuación.

# Columna Close del DataFrame aapl
import plotly.express as px
df_aux = df.copy().reset_index()

fig1 = px.line(df_aux ,y = df_aux[nom_val] ,title="Historical quotes of " + nom_val, range_x=[start_day, end_day])
fig1.show()

fig2 = px.line(df_aux, x="Date", y="Momentum",
              range_x=['2016-07-01','2020-12-31'])

fig2.add_shape(type="line",
    x0 = df_aux.iloc[0, 0], y0 = 0, x1 = df_aux.iloc[-1, 0], y1 = 0,
    line=dict(color="Red",width=1.5)
 )

fig2.update_layout(title_text='Momentum', title_x=0.5)

fig.show()

Que devuelve

introducir la descripción de la imagen aquí

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.