0

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()
1
  • I see from your script that the expected output is the average for each week, but where do you link the average value to a date in your plot? What did your output show? We can't reproduce it, because this is not a MCVE. Commented Feb 16, 2018 at 18:47

2 Answers 2

1

You should check out this example from the matplotlib website. It seems that you should be able to do the following:

plt.xticks(range(0,len(average_prices), 14), dates[0:len(average_prices):14])

Sign up to request clarification or add additional context in comments.

Comments

0

Right now you aren't using your x-axis data at all in the plot. You are only submitting "average_prices" to plt.plot, so it will just use the index value for the x-axis. If you want the x-axis to show your date information, you should format your date data as datetime objects. Here is an example of how to format the x-axis ticks and make a plot with dates in the x-axis.

Also, for your comment about rounding to two decimal places

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.