0

I have added a text box to matplotlib via the axes.text method. I am wanting to conditionally format the color of the text within this box based on other text. I am including a simplified version to hopefully show the situation a little better.

import matplotlib.pyplot as plt
import yfinance as yf
import pandas_datareader.data as data
from datetime import datetime, timedelta
import mplfinance as mpf

end_date = datetime.today()
start_date = datetime.today() - timedelta(days=20)
df = data.get_data_yahoo('SPY', start_date, end_date)
df['ma'] = df['Close'].rolling(window=5).mean().values

close = df['Close'][-1]
ma = df['ma'][-1]

text_box = r"""Close: {0}
5-MA: {1}""".format(round(close,2), round(ma,2))

fig, axlist = mpf.plot(df,type='candle', returnfig=True, mav=(5), figsize=(8,7), volume=False)
calls_bought = axlist[0].text(0.01, 0.98, text_box, transform=axlist[0].transAxes, verticalalignment='top', horizontalalignment='left', fontsize= 'small', bbox=dict(boxstyle='round', facecolor='white', alpha=0.4))
plt.show()

So in the above example I am wanting to color the text within the box of the closing price if it above or below the moving average.

Thanks for any guidance.

1 Answer 1

1

Looks like you should be able to simply change your call to axes.text() to include the "color" argument and pass a value for it based on an in-line if-else statement like the following:

calls_bought = axlist[0].text(
    0.01, 0.98, text_box, transform=axlist[0].transAxes, 
    verticalalignment='top', horizontalalignment='left', fontsize= 'small', 
    bbox=dict(boxstyle='round', facecolor='white', alpha=0.4),
    color="red" if close > ma else "blue"
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.