Я пишу программу, которая создает график цен OHLC для каждого актива в предоставленном мной списке, но я пытаюсь изменить отметку оси X, чтобы сделать ее ежеквартальной. Я нашел решение, но галочки не в одном и том же месяце каждый год, поэтому оно бесполезно.
Вот мой код. Кто-нибудь знает, как решить мою проблему?
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)
Я пытался использовать DateFormatter, чтобы изменить тики на формат «%b %Y», но даты на графике были искажены, перекрывались или даже имели даты 1969 года, тогда как мои данные всегда относятся к 6-летнему периоду.>
Я пишу программу, которая создает график цен OHLC для каждого актива в предоставленном мной списке, но я пытаюсь изменить отметку оси X, чтобы сделать ее ежеквартальной. Я нашел решение, но галочки не в одном и том же месяце каждый год, поэтому оно бесполезно. Вот мой код. Кто-нибудь знает, как решить мою проблему? [code]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):
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')
[/code] Я пытался использовать DateFormatter, чтобы изменить тики на формат «%b %Y», но даты на графике были искажены, перекрывались или даже имели даты 1969 года, тогда как мои данные всегда относятся к 6-летнему периоду.>