November 2019
Beginner
394 pages
10h 31m
English
In this section, the code demonstrates how you would implement a simple moving average, using a list (history) to maintain a moving window of prices and a list (SMA values) to maintain a list of SMA values:
import statistics as statstime_period = 20 # number of days over which to averagehistory = [] # to track a history of pricessma_values = [] # to track simple moving average valuesfor close_price in close: history.append(close_price) if len(history) > time_period: # we remove oldest price because we only average over last 'time_period' prices del (history[0]) sma_values.append(stats.mean(history))goog_data = goog_data.assign(ClosePrice=pd.Series(close, index=goog_data.index))goog_data = goog_data.assign(Simple20DayMovingAverage=pd.Series(sma_values, ...