Plot line with markerts

I have a pandas DataFrame:

time close signal
1000 2021-01-04 11:20:00 0.22973 NaN
1001 2021-01-04 11:25:00 0.22824 NaN
1002 2021-01-04 11:30:00 0.22716 NaN
1003 2021-01-04 11:35:00 0.22806 NaN
1004 2021-01-04 11:40:00 0.22885 NaN

signal column could be ‘buy’ or ‘sell’ or NaN

I am able to plot the close, but was not able to add buy or sell markers to the plot, to nicely show a trading results.

plt.plot(df.index, df.close)
plt.plot(df.index, df.signal, 'r-X' , label='signal')

Thank you

The separate plot calls do not know anything about each other and always plot at what ever x/y you give it. In your second line you are saying “please plot using the index as the x and {buy, sell, NaN} as the y”.

I think you want to do this as :


fig, ax = plt.subplots()
ax.plot(df.index, df.close, label="close")
buy_mask = df.signal == "buy"
sell_mask = df.signal == "sell"
ax.plot(
    df.index[buy_mask],
    df.close[buy_mask],
    linestyle="",
    marker="^",
    label="buy",
    color="green",
)
ax.plot(
    df.index[sell_mask],
    df.close[sell_mask],
    linestyle="",
    marker="v",
    color="red",
    label="sell",
)

modulo my getting the pandas wrong.

You may also be interested in GitHub - matplotlib/mplfinance: Financial Markets Data Visualization using Matplotlib .