Apr-10-2022, 06:31 PM
Hello All!
I'm using historical stock prices for which I am using to calculate the SMA, but the SMA returns "None". Could you help figure out why my SMA is not returning a numerical value? Thank you for your help.
I'm using historical stock prices for which I am using to calculate the SMA, but the SMA returns "None". Could you help figure out why my SMA is not returning a numerical value? Thank you for your help.
''' The Simple Moving Average (SMA) is calculated by adding the price of an instrument over a number of time periods and then dividing the sum by the number of time periods. The SMA is basically the average price of the given time period, with equal weighting given to the price of each period. Simple Moving Average SMA = ( Sum ( Price, n ) ) / n Where: n = Time Period ''' from tracemalloc import start from matplotlib import ticker import pandas_datareader as pdr import datetime as dt import statistics as stats ticker = "AAPL" start = dt. datetime(2021, 1, 14) end = dt.datetime(2021, 3, 18) data = pdr.get_data_yahoo(ticker, start, end) print(data["Adj Close"]) #================================================================================ close = data['Adj Close'] time_period = 20 # number of days over which to average history = [] # to track a history of prices sma_values = [] # to track simple moving average values for 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)) quotes = sma_values.append(stats.mean(history)) print(quotes)
Error:Date
2021-01-14 127.957146
2021-01-15 126.200218
2021-01-19 126.885124
2021-01-20 131.054077
2021-01-21 135.858307
2021-01-22 138.042068
2021-01-25 141.863586
2021-01-26 142.101807
2021-01-27 141.009964
2021-01-28 136.076660
2021-01-29 130.984619
2021-02-01 133.148483
2021-02-02 133.992203
2021-02-03 132.949982
2021-02-04 136.374451
2021-02-05 135.951965
2021-02-08 136.101074
2021-02-09 135.206390
2021-02-10 134.590073
2021-02-11 134.331604
2021-02-12 134.570175
2021-02-16 132.403061
2021-02-17 130.066925
2021-02-18 128.943619
2021-02-19 129.102676
2021-02-22 125.255547
2021-02-23 125.116371
2021-02-24 124.609383
2021-02-25 120.275139
2021-02-26 120.543556
2021-03-01 127.034966
2021-03-02 124.380745
2021-03-03 121.338821
2021-03-04 119.420227
2021-03-05 120.702599
2021-03-08 115.672493
2021-03-09 120.374542
2021-03-10 119.271118
2021-03-11 121.239410
2021-03-12 120.314903
2021-03-15 123.257416
2021-03-16 124.828079
2021-03-17 124.022865
2021-03-18 119.817863
Name: Adj Close, dtype: float64
None