Book Image

Learning Pandas

By : Michael Heydt
Book Image

Learning Pandas

By: Michael Heydt

Overview of this book

Table of Contents (19 chapters)
Learning pandas
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Performing a moving-average calculation


The moving average of a stock can be calculated using the pandas statistical package that is a part of pandas and is in the pd.stats namespace, specifically, the .rolling_mean() function.

The moving average will give you a sense of the performance of a stock over a given time period by eliminating "noise" in the performance of the stock. The larger the moving window, the smoother and less random the graph will be—at the expense of accuracy.

To demonstrate, the following calculates the moving average for MSFT on 30 and 90 day periods using the daily close. The difference in the reduction of noise can be easily determined from the visual:

In [27]:
   # extract just MSFT close
   msft_close = close_px[['MSFT']]['MSFT']
   # calculate the 30 and 90 day rolling means
   ma_30 = pd.stats.moments.rolling_mean(msft_close, 30)
   ma_90 = pd.stats.moments.rolling_mean(msft_close, 90)
   # compose into a DataFrame that can be plotted
   result = pd.DataFrame({...