0

I've written the code for showing MACD indicator graph. what I did is here:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

df = pd.read_csv(#stock_chart)
df = df.rename(columns={"<DTYYYYMMDD>":"Date"})
df['Date'] = pd.to_datetime(df['Date'].astype(str), format="%Y%m%d")
print(df.head())
#seting index for graph
df = df.set_index(df['Date'].values)
print(df.head())

which my dataframe's head is : Graph columns and rows!

#Macd
S_term = 12
L_term = 26
s_ema = df.close.ewm(span=S_term, adjust=False).mean()
l_ema = df.close.ewm(span=L_term, adjust=False).mean()
#calculate MACD
macd = s_ema - l_ema

signal_term = 9
signal_line = macd.ewm(span= signal_term, adjust=False).mean()

#plot the graphs
plt.figure(figsize=(100,10)) #width = 12.2in, height = 4.5
plt.plot(df.index, macd, label='macd', color = 'red')
plt.plot(df.index, signal_line, label='Signal Line', color='blue')
plt.tight_layout()

plt.xticks(rotation=0)
plt.legend(loc='upper left')
plt.show()

finally , I got to this :

Matplotlib's graph

Anyway , the problem is that despite row index labels are like this : 2020-08-19 or "%Y%m%d" , graph labels are incomplete and if I reorder it , the data overlaps on each other . what do I have to do ?

Dave 3652
  • 3
  • 4

1 Answers1

0

You could use Date locators and Date formatters.

import numpy
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas

N = 192
numpy.random.seed(N)

dates = pandas.date_range('1/1/2004', periods=N, freq='m')

df = pandas.DataFrame(
    data=numpy.random.randn(N), 
    index=dates,
    columns=['A']
)

fig, ax = plt.subplots()

ax.plot(df.index, df['A'])

ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))

fig.autofmt_xdate()

plt.show()

enter image description here

interval is the interval between each iteration. For example, if interval=2, mark every second occurrence.

import numpy
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas

N = 192
numpy.random.seed(N)

dates = pandas.date_range('1/1/2004', periods=N, freq='m')

df = pandas.DataFrame(
    data=numpy.random.randn(N), 
    index=dates,
    columns=['A']
)

fig, ax = plt.subplots()

ax.plot(df.index, df['A'])
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=5))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))


fig.autofmt_xdate()

plt.show()

enter image description here

Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52
  • This is not what I wanted to do , I wanna find a way to show x-axis labels completely ... thanks! – Dave 3652 Aug 26 '20 at 09:55
  • @Dave3652 If you really want to show labels completely, only use `ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))`. But that will cause unavoidable ticks overlap. And there is no easy to fix it. I offer you an example how to show months intervally. – Ynjxsjmh Aug 26 '20 at 13:04