We will create a function in python that will print out the Simple Moving Average of a given price list, for a given period of time.
For this, I shall be using the original closing prices of NIFTY from 17th March’25 to 06th May’25.
Let’s get into the code.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
#calculating simple moving average nifty_price=[22508.75, 22834.30, 22907.60, 23190.65, 23350.40, 23658.35, 23668.65, 23486.85, 23591.95, 23519.35, 23165.70, 23332.35, 23250.10, 22904.45, 22161.60, 22535.85, 22399.15, 22828.55, 23328.55, 23437.20, 23851.65, 24125.55, 24167.25, 24328.95, 24246.70, 24039.35, 24328.50, 24335.95, 24334.20, 24346.70, 24461.15, 24379.60] n=len(nifty_price) def sma(p): if len(nifty_price)>p: placeholder=[] i=0 while i<=p-1: placeholder.append(nifty_price[n-p+i]) if i==p-1: sma = sum(placeholder)/p print(sma) print(placeholder) i=i+1 else: print("Length of the list is smaller than the period desired.") sma(9) |
Let me explain the code to you.
Step 1 : I built a list by the name ‘nifty_price’ and entered all the closing prices from 17th March 2025 till 6th May 2025. I have used the orignal prices, so that we could compare it to the chart values of brokerage sites.
Step 2 : Get the length of the list .
Step 3 : Create a function with an argument. Here the name of the function is sma(p), where ‘p’ is the argument. Here you will enter the number of days or period for which you want to calculate the SMA (Simple Moving Average).
Step 4 : Create an empty list by the name ‘placeholder’ and append to this list the last ‘p’ numbers of elements from the nifty_price list.
Let me tell you why I did it like this.
If you want to calculate the SMA of 5 days, then the function will populate the ‘placeholder’ list with the last 5 closing prices from the nifty_price list.
Step 5 : Get the average of the list ‘placeholder’. For this I have used the sum function of the python list to get the sum and then I computed the average by diving it by the number of days.
In this example, I have computed the SMA for 9 days and compared it with the charts from Groww. The SMA comes out to be 24311.23 and that’s an exact match.