2

Im making a program that creates an OHLC price graph for every asset in the list I provide, but im trying to change the ticks of my x-axis to make it quarterly. I found a solution, but the ticks are not in the same month every year, so it is not useful. Here is my code. Does someone know how to fix my problem?

import mplfinance as mpf
import yfinance as yf
import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib.ticker import MaxNLocator
from matplotlib.dates import MonthLocator, DateFormatter
from matplotlib.ticker import FixedLocator
import pandas as pd
#%% Creamos la clase que grafica la lista de activos que desee ver, desde la fecha que querramos.
class Grafico:
    def __init__(self, assets, start_date):
        
        self.assets = assets
        self.start_date = start_date
        self.end= datetime.now()
        self.start=datetime.strptime(self.start_date, '%Y-%m-%d')
        
        self.days=(self.end-self.start).days
        
        self.CCL= self.CCL_f()
        
    def CCL_f(self):
        GGAL=yf.download('GGAL', start=self.start_date)
        GGAL_BA=yf.download('GGAL.BA',start=self.start_date)
        CCL=(GGAL_BA/GGAL)*10
        return CCL
    
        

    def plot(self):
        for file in os.listdir(): #Esto borrará los archivos viejos, para que cada vez que se ejecute el programa aparezcan en carpeta los gráficos que se quieren descargar
            if file.endswith('.png'):
                try:
                    os.remove(file)
                except Exception as e:
                    print(f'Error deleting {file}: {e}')
        for asset in self.assets:
            if ".BA" in asset:
                data = yf.download(asset, start=self.start_date, end=self.end)
                data= data/self.CCL
                self.data=data
                if asset=="BYMA.BA":
                    self.data= self.data.drop("2018-12-31")
            else:
                data = yf.download(asset, start=self.start_date, end=self.end)
                self.data=data
            fig, ax = mpf.plot(self.data, type='candle', style='classic',figscale=1.5, tight_layout=False, returnfig=True)
            #mpf.plot_moving_average(data, 50, color='black', linestyle='--')   
            fig.set_size_inches(11.692913385826772,8)
            ax[0].yaxis.set_major_locator(MaxNLocator(nbins=30))
            #ax[0].xaxis.set_major_locator(MaxNLocator(nbins=10))
            comienzo = self.data.index[0]
            final = self.data.index[-1]
            locator = MonthLocator(interval=3)
            #formatter = DateFormatter('%b %Y')
            
            #ax[0].xaxis.set_major_formatter(formatter)
            ax[0].xaxis.set_major_locator(locator)
            ax[0].tick_params(axis='x', labelsize=5)
            ax[0].tick_params(axis='y', labelsize=5)
            last_price = self.data['Close'].iloc[-1]
            ax[0].axhline(y=last_price, linestyle='--', color='k',linewidth=0.5)
            ax[0].set_title(f'{asset} - (Last {self.days} days)',fontsize=15, loc='center')
            plt.savefig(f'{asset}.png',bbox_inches='tight', dpi=300)

I tried using DateFormatter to change the ticks to '%b %Y' format, but the dates of the graph were screwed, overlapping, or even having dates from 1969 when my data are always 6 years from now.

  • 2
    Try setting **`show_nontrading=True`** in your call to **`mpf.plot()`**. If that works for you, that will be the simplest solution. (There are other solutions for the [default] case of `show_nontrading=False`, however they are more complex.) – Daniel Goldfarb Dec 30 '22 at 16:40

0 Answers0