Hello friends. In this demo I will show how to calculate the moving average of a company’s stocks. In finance, this means the average of a section of stock volumes, which moves through every section of a company’s stock. In this demo, I will use AAPL(Apple)’s stocks.

Here is the demo:

Here is the code:

import numpy as np
from matplotlib import pyplot as plt
import csv
mavg2 = []
calcedStockDates1 = []
stockDates = []
stockFind = []
dataDates = []
data = []
def getShares():
iterate = 0
with open('aapl2.csv', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter = ' ', quotechar = '|')
for row in reader:
if iterate != 0:
string = ', '.join(row);
data = string.split(",")
dataDates = string.split("-")
stockDates.append(int(dataDates[0]))
stockFind.append(int(data[5]))
iterate += 1
def calcMavg(rnge):
mvg = []
for i in range(len(stockFind) - rnge):
if i != 0:
avg = 0
for n in range(rnge):
avg += stockFind[i + n]
mvg.append(avg/rnge)
return mvg
def calcCsds(rnge):
csds = []
for i in range(len(stockFind) - rnge):
if i != 0:
csds.append(stockDates[i + rnge])
return csds
def plotMavg(mvg,csds):
plt.plot(csds, mvg, linestyle='-', marker='*')
getShares()
mavg = calcMavg(5)
calcedStockDates1 = calcCsds(5)
plotMavg(mavg, calcedStockDates1)
plt.title("Moving average calculation (* = mavg)")
plt.xlabel("Every five days from start")
plt.ylabel("Mavg")
plt.show()</pre>
<pre>

### Like this:

Like Loading...

*Related*

## Leave a Reply