Q#39: Plotting stock prices
Using Python, create a line chart with both the daily and 7-day moving average for the close price for Apple stock. You can download a CSV with the current prices using the Yahoo Finance API.
TRY IT YOURSELF (in your browser for free on Colab)
This question tests our ability to generate a quick figure to visualize the data using Python. There are multiple solutions as there are a variety of plotting packages in Python, however we are going to use the inbuilt plotting functionality of the Pandas library.
As a true data scientist you would be expected to procure the data yourself using an API or other source; however, here we are provided with the data already pre-loaded from 2015 to 2020 in a pandas dataframe. Therefore, we simply need to decide which column is of interest and use the .plot() method to produce our solution. For stock prices, we are most interested in the closing price, therefore this is the column we will focus on. Inside the .plot() method, we can use arguments title and ylabel to set the title and the ylabel respectively.
data['Adj Close'].plot(title = 'Apple Stock Prices 2015-2020', ylabel = 'Price ($US)')
The second part of this problem is to plot the 7-day rolling average. To do this we can create a new column in our dataframe using the indexers  and call the .rolling() method chained with the .mean() method. Inside the .rolling(<#>) method we can specify the number of periods we want, in this case 7, indicating 7 business days as our data is sampled as such. Finally, we can call the .plot() method querying both columns for a composite figure.
data['Adj Close 7-Day Rolling Avg'] = data['Adj Close'].rolling(7).mean()data[['Adj Close','Adj Close 7-Day Rolling Avg']].plot(title = 'Apple Stock Prices 2015-2020', ylabel = 'Price ($US)')