0
#Import
import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt
from mplfinance.original_flavor import candlestick_ohlc
import matplotlib.dates as mdates

#Dates to get stocks
start_date = "2020-01-01"
end_date = "2023-05-08"

#Get to the site
tesla_data = yf.download("TSLA", start = start_date, end = end_date)

#Get info off the site
tesla_weekly_data = tesla_data.resample("W").agg({"Open":"first", "High":"max", "Low":"min", "Close":"last", "Volume":"sum"}).dropna()
tesla_weekly_data.reset_index(inplace = True)
tesla_weekly_data["Date"] = tesla_weekly_data["Date"].map(mdates.date2num)

#Configer the plot
fig, ax = plt.subplots(figsize=(16,8))

#Show Canddlestick
candlestick_ohlc(ax, tesla_weekly_data.values, width = 5, colorup = "green", colordown = "red")

#Fonts
font1 = {"family":"serif", "color":"black", "size":40, "fontweight":"bold"}
font2 = {"family":"serif", "color":"black", "size":20, "fontweight":"bold"}

#Show Descripton of title and labels
plt.xlabel("Date", fontdict = font2)
plt.ylabel("Price",fontdict = font2)
plt.title("Tesla Stock Prices", fontdict = font1)

#Show the stocks line
plt.plot(tesla_data["Close"], color = "cyan", linewidth = 2)

#Add legend
plt.legend({"Tesla Close Prices":"cyan", "Price Up":"green", "Price Down":"red"})

#Show the plot
plt.show()

When it opens a window, the legend is not correct even thought it support to be!

When you click on run, the legend box is there but not correctly, First the tesla close prices are support to be cyan but is a green line, the price up is good but not the price down.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Damian
  • 29
  • 5
  • This is two questions (1) why isn't the legend showing (2) how to format the plot, which is answered in [How can I customize mplfinance.plot?](https://stackoverflow.com/q/60599812/7758804). Your question should be only a single question. – Trenton McKinney May 10 '23 at 02:33
  • If @r-beginners's answer works, you should accept their answer. – jared Jun 20 '23 at 04:04

1 Answers1

1

I have reproduced your code in the latest mplfinance modul. Indeed the handles and labels in the legend are wrong, and there is a solution up on githjub that addresses this precedent, but it was not applicable to this case. So as a workaround, I created a new red patch and reused the existing handle to create a handle. I am not sure if this workaround is the best. The examples I used for customization are styles and additional graphs.

import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import mplfinance as mpf
import matplotlib.dates as mdates

#Dates to get stocks
start_date = "2020-01-01"
end_date = "2023-05-08"

tesla_data = yf.download("TSLA", start = start_date, end = end_date)
tesla_weekly_data = tesla_data.resample("W").agg({"Open":"first", "High":"max", "Low":"min", "Close":"last", "Volume":"sum"}).dropna()

#Fonts
font1 = {"family":"serif", "color":"black", "size":40, "fontweight":"bold"}
font2 = {"family":"serif", "color":"black", "size":20, "fontweight":"bold"}
title = "\nTesla Stock Prices"
apd = mpf.make_addplot(tesla_weekly_data['Close'], color='cyan', linewidths=2)
mc = mpf.make_marketcolors(up='g',down='r')
s  = mpf.make_mpf_style(marketcolors=mc)

fig, axes = mpf.plot(tesla_weekly_data,
                       figratio=(16,8),
                       type='candle',
                       style=s,
                       addplot=apd,
                       update_width_config=dict(candle_width=1.2),
                       returnfig=True
                      )

axes[0].set_title(title, **font1)
axes[0].set_ylabel('Prise', **font2)
axes[0].set_xlabel('Date', **font2)

axes[0].legend([None]*(len(apd)+2))
handles = axes[0].get_legend().legend_handles
red_patch = mpatches.Patch(color='red')
axes[0].legend(handles=[handles[1], red_patch, handles[-1]], labels={"Price Up":"green", "Price Down":"red","Tesla Close Prices":"cyan"})

plt.show()

enter image description here

Legend with issues

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32