Skip to content

Can't set traces on specific row/col when processing .add_trace(Scatter()) #5375

@huangweichi950201-cmd

Description

@huangweichi950201-cmd

im trying to write a ATR indicator by following codes in
https://datadave1.medium.com/15-essential-technical-indicators-and-how-to-plot-them-using-plotly-de9c29d0070f

but i get an error every time when i try to set traces (things like add_traces(scatter(.......... row=1, col=1)) on stacked subplot.
have been searching for a while but cant rally find an answer.

what showed up:
ValueError: Invalid property specified for object of type plotly.graph_objs.Scatter: 'row'
with a loooooong list of Valid properties

heres the code i wrote:

import yfinance as yf
import talib as ta

import plotly.graph_objs as pgo
import plotly.io as pio
from plotly.tools import make_subplots

pio.renderers.default = "browser"

ticker = "TSLA"
yfticker = yf.Ticker(ticker)
df = yfticker.history(start="2024-01-01")

df["20_SMA"] = ta.SMA(df["Close"], 20)
df["yes_close"] = df["Close"].shift(1)

df["tr1"] = (df["High"] - df["Low"]).abs()
df["tr2"] = (df["High"] - df["yes_close"]).abs()
df["tr3"] = (df["Low"] - df["yes_close"]).abs()

df["TR"] = df[["tr1", "tr2", "tr3"]].max(1)
df["20_ATR"] = df["TR"].rolling(20).mean()

fig = make_subplots(rows=2, #建立疊在一起的圖 rows表示圖行數
cols=1,
shared_xaxes=1,
shared_yaxes=0,
vertical_spacing=0.2,
row_heights=[0.7, 0.3],
subplot_titles=[f"{ticker} Price and 20SMA", "20 Days ATR"])

candlestick = pgo.Candlestick(
x=df.index,
open=df.Open,
high=df.High,
low=df.Low,
close=df.Close,
name="Price"
)

fig.add_trace(candlestick, row=1, col=1) # row跟col決定物件的位置(在哪張圖上)

fig.add_trace(pgo.Scatter(
x=df.index,
y=df["20_SMA"],
name="SMA (20)",
line=dict(color="white", width=1),
row=1,
col=1
))

fig.add_trace(pgo.Scatter(
x=df.index,
y=df["20_ATR"],
name="ATR (20)",
line=dict(color="lightblue", width=1),
row=2,
col=1
))

fig.add_shape(type="line",
xref="paper",
x0=0,
x1=1,
yref="paper",
y0=0.4,
y1=0.4,
line=dict(color="black", width=0.5)
)

for r in [1, 2]:
fig.update_xaxes(
row=r,
col=1,
showgrid=True,
gridwidth=1,
gridcolor="lightgray",
dtick="M1",
tickangle=-45
)

fig.update_yaxes(title_text="Price", row=1, col=1)
fig.update_yaxes(title_text="ATR (20)", row=1, col=2)

fig.update_layout(
title=f"{ticker} Technical Analysis",
xaxis_rangeslider_visible=False,
height=800,
template="plotly_dark"
)

fig.show()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions