Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
guipsamora
GitHub Repository: guipsamora/pandas_exercises
Path: blob/master/09_Time_Series/Apple_Stock/Exercises-with-solutions-code.ipynb
613 views
Kernel: Python 3

Apple Stock

Check out Apple Stock Exercises Video Tutorial to watch a data scientist go through the exercises

Introduction:

We are going to use Apple's stock price.

Step 1. Import the necessary libraries

import pandas as pd import numpy as np # visualization import matplotlib.pyplot as plt %matplotlib inline

Step 2. Import the dataset from this address

Step 3. Assign it to a variable apple

url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/09_Time_Series/Apple_Stock/appl_1980_2014.csv' apple = pd.read_csv(url) apple.head()

Step 4. Check out the type of the columns

apple.dtypes
Date object Open float64 High float64 Low float64 Close float64 Volume int64 Adj Close float64 dtype: object

Step 5. Transform the Date column as a datetime type

apple.Date = pd.to_datetime(apple.Date) apple['Date'].head()
0 2014-07-08 1 2014-07-07 2 2014-07-03 3 2014-07-02 4 2014-07-01 Name: Date, dtype: datetime64[ns]

Step 6. Set the date as the index

apple = apple.set_index('Date') apple.head()

Step 7. Is there any duplicate dates?

# NO! All are unique apple.index.is_unique
True

Step 8. Ops...it seems the index is from the most recent date. Make the first entry the oldest date.

apple.sort_index(ascending = True).head()

Step 9. Get the last business day of each month

apple_month = apple.resample('BM').mean() apple_month.head()

Step 10. What is the difference in days between the first day and the oldest

(apple.index.max() - apple.index.min()).days
12261

Step 11. How many months in the data we have?

apple_months = apple.resample('BM').mean() len(apple_months.index)
404

Step 12. Plot the 'Adj Close' value. Set the size of the figure to 13.5 x 9 inches

# makes the plot and assign it to a variable appl_open = apple['Adj Close'].plot(title = "Apple Stock") # changes the size of the graph fig = appl_open.get_figure() fig.set_size_inches(13.5, 9)
Image in a Jupyter notebook

BONUS: Create your own question and answer it.