Search code examples
pythonpandasmoving-average

Pandas Moving Average


I am trying to plot the moving average for a rolling window of 30 days on a column of a Quandl dataset that I have added as a column of a pandas dataframe. The dataframe looks like: enter image description here

How do I firstly compute the moving average, and after that, how do I plot it in Python?


Solution

  • You can use built-in Pandas DataFrame function.

    1.To compute:

    To compute moving average - e.g. 20 Days (I can see you're using daily data/business days)

    YourDataFrame['Instrument_name'].rolling(20).mean()
    

    2.To Plot:

    Pandas also provide simple plotting functionality. You can use it to plot both charts.

    YourDataFrame['Instrument_name'].plot() 
    YourDataFrame['Instrument_name'].rolling(20).mean().plot()
    

    ['Instrument_name'] --> this is your column name, for example ['value_gold']