I'm currently plotting a list of stock prices using matplotlib, however I'm not sure how to get the corresponding dates to show correctly in the graph. The data in the csv is daily stock prices but I would only want to show dates for every 2 weeks on the x-axis. The stock dates and prices are in 2 different lists, is it possible to do it this way? or should I use a dictionary instead and try and plot it that way?
import csv
import sys
import matplotlib.pyplot as plt
def main():
filename = 'somefile.csv'
with open(filename, newline='') as f:
reader = csv.reader(f)
next(reader, None) # skips the column headers
dates = list()
prices = list()
try:
for row in reader:
dates.append(row[0])
prices.append(float(row[1])) # converts prices to floats and saves in a new list.
ma_window = 7
reverse_prices = prices[::-1]
average_reverse_prices = []
r = len(prices) - ma_window + 1
for i in range(r):
interval = reverse_prices[i:(i + ma_window)]
average = float(sum(interval)) / ma_window # might want to round to 2 decimal places
average_reverse_prices.append(average)
average_prices = average_reverse_prices[::-1]
print(average_prices)
plt.plot(average_prices)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()
except csv.Error as e:
sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))
if __name__ == '__main__':
main()