date and graph alignment - Economic analysis

Viewed 69

I'm am running a fundamental economic analysis and when I get to visualising and charting I am not able to align the dates with the graph.

I wanted the most recent date entry to show on the right and the rest of the dates to show every two years.

I have tried literally everything and cant find the solution.

Here is my code:

%matplotlib inline
import pandas as pd
from matplotlib import pyplot
import matplotlib.dates as mdates

df = pd.read_csv('https://fred.stlouisfed.org/graph/fredgraph.csvbgcolor=%23e1e9f0&chart_type=line&drp=0&fo=open%20sans&graph_bgcolor=%23ffffff&height=450&mode=fred&recession_bars=off&txtcolor=%23444444&ts=12&tts=12&width=1168&nt=0&thu=0&trc=0&show_legend=yes&show_axis_titles=yes&show_tooltip=yes&id=NAEXKP01EZQ657S&scale=left&cosd=1995-04-01&coed=2020-04-01&line_color=%234572a7&link_values=false&line_style=solid&mark_type=none&mw=3&lw=2&ost=-99999&oet=99999&mma=0&fml=a&fq=Quarterly&fam=avg&fgst=lin&fgsnd=2020-02-01&line_index=1&transformation=lin&vintage_date=2020-09-21&revision_date=2020-09-21&nd=1995-04-01')
df = df.set_index('DATE')
df['12MonthAvg'] = df.rolling(window=12).mean().dropna(how='all')
df['9MonthAvg'] = df['12MonthAvg'].rolling(window=12).mean().dropna(how='all')
df['Spread'] = df['12MonthAvg'] - df['9MonthAvg']

pyplot.style.use("seaborn")
pyplot.subplots(figsize=(10, 5), dpi=85)
df['Spread'].plot().set_title('EUROPE: GDP Q Growth Rate (12M/12M Avg Spread)', fontsize=16)
df['Spread'].plot().axhline(0, linestyle='-', color='r',alpha=1, linewidth=2, marker='')
df['Spread'].plot().spines['left'].set_position(('outward', 10))
df['Spread'].plot().spines['bottom'].set_position(('outward', 10))
df['Spread'].plot().spines['right'].set_visible(False)
df['Spread'].plot().spines['top'].set_visible(False)
df['Spread'].plot().yaxis.set_ticks_position('left')
df['Spread'].plot().xaxis.set_ticks_position('bottom')
df['Spread'].plot().text(0.50, 0.02, "Crossing red line downwards / Crossing red line Upwards", 
                     transform=pyplot.gca().transAxes, fontsize=14, ha='center', color='blue')
df['Spread'].plot().fmt_xdata = mdates.DateFormatter('%Y-%m-%d')

print(df['Spread'].tail(3))
pyplot.autoscale()
pyplot.show()

And the output:

enter image description here

This is the raw data:

enter image description here

1 Answers

There is a couple of corrections to your code.

  1. In your URL insert "?" after fredgraph.csv. It starts so called query string, where bgcolor is the first parameter.

  2. Read your DataFrame with additional parameters:

    df = pd.read_csv('...', parse_dates=[0], index_col=[0])
    

    The aim is to:

    • read Date column as datetime,
    • set it as the index.
  3. Create additional columns as:

    df['12MonthAvg'] = df.NAEXKP01EZQ657S.rolling(window=12).mean()
    df['9MonthAvg'] = df.NAEXKP01EZQ657S.rolling(window=9).mean()
    df['Spread'] = df['12MonthAvg'] - df['9MonthAvg']
    

    Corrections:

    • 9MonthAvg (as I think) should be computed from the source column, not from 12MonthAvg,
    • dropna here is not needed, as you create whole column anyway.
  4. Now is the place to use dropna() on Spread column and save it in a dedicated variable:

    spread = df['Spread'].dropna()
    
  5. Draw your figure the following way:

    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    
    plt.style.use("seaborn")
    fig, ax = plt.subplots(figsize=(10, 5), dpi=85)
    plt.plot_date(spread.index, spread, fmt='-')
    ax.set_title('EUROPE: GDP Q Growth Rate (12M/12M Avg Spread)', fontsize=16)
    ax.axhline(0, linestyle='-', color='r',alpha=1, linewidth=2, marker='')
    ax.spines['left'].set_position(('outward', 10))
    ax.spines['bottom'].set_position(('outward', 10))
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.text(0.50, 0.02, "Crossing red line downwards / Crossing red line Upwards", 
        transform=ax.transAxes, fontsize=14, ha='center', color='blue')
    ax.xaxis.set_major_formatter(mdates.DateFormatter(fmt='%Y-%m-%d'))
    plt.show()
    

    Corrections:

    • plt.subplots returns fig and ax, so I saved them (actually, only ax is needed).
    • When one axis contains dates, it is better to use plot_date.
    • I changed the way DateFormatter is set.

Using the above code I got the following picture:

enter image description here

Related