<jupyter_start><jupyter_text>Apple Stock  Introduction:We are going to use Apple's stock price. Step 1. Import the necessary libraries<jupyter_code>import pandas as pd<jupyter_output><empty_output><jupyter_text>Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/09_Time_Series/Apple_Stock/appl_1980_2014.csv)<jupyter_code>url = "https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/09_Time_Series/Apple_Stock/appl_1980_2014.csv"<jupyter_output><empty_output><jupyter_text>Step 3. Assign it to a variable apple * combine steps 2 and 3<jupyter_code>apple = pd.read_csv(url)
apple.head()<jupyter_output><empty_output><jupyter_text>Step 4.  Check out the type of the columns<jupyter_code>apple.dtypes<jupyter_output><empty_output><jupyter_text>Step 5. Transform the Date column as a datetime type<jupyter_code>apple["Date"] = pd.to_datetime(apple["Date"])
apple.dtypes<jupyter_output><empty_output><jupyter_text>Step 6.  Set the date as the index<jupyter_code>apple = apple.set_index("Date")
apple.head()<jupyter_output><empty_output><jupyter_text>Step 7.  Is there any duplicate dates?<jupyter_code># No
apple.index.has_duplicates<jupyter_output><empty_output><jupyter_text>Step 8.  Ops...it seems the index is from the most recent date. Make the first entry the oldest date.<jupyter_code>apple.sort_index(ascending=True, inplace=True)<jupyter_output><empty_output><jupyter_text>Step 9. Get the last business day of each month<jupyter_code># as df is now sorted from oldest to most recent, last day of each month will be
# last row (tail) of each group dataframe
#apple.groupby(apple.index.month, group_keys=False).apply(lambda x: x.tail(1)).index.day

# alternatively, more naturally, and the prices are averages for the month
apple.resample('BM').mean()<jupyter_output><empty_output><jupyter_text>Step 10.  What is the difference in days between the first day and the oldest<jupyter_code># 12261 days
days = apple.index
abs(days[-1] - days[0])
# more clear:
(days.max() - days.min()).days<jupyter_output><empty_output><jupyter_text>Step 11.  How many months in the data we have?<jupyter_code># groupby year, month, find no. of unique groups
# 404 months
apple.groupby([apple.index.year, apple.index.month]).ngroups

# alternatively, len instead of .shape[0]
apple.resample('BM').mean().shape[0]<jupyter_output><empty_output><jupyter_text>Step 12. Plot the 'Adj Close' value. Set the size of the figure to 13.5 x 9 inches<jupyter_code>import matplotlib.pyplot as plt
fig = plt.figure(figsize=(13.5, 9))
fig.patch.set_facecolor('white')  # set axes to white
apple["Adj Close"].plot();<jupyter_output><empty_output><jupyter_text>BONUS: Create your own question and answer it.Plot the yearly rolling average for the average monthly continuously compounded return.<jupyter_code>import numpy as np

monthly_price = apple["Adj Close"].asfreq('MS', method='pad')
monthly_return = np.log(monthly_price.shift(-1)/monthly_price)
monthly_return

roll_yearly = monthly_return.rolling(12, center=True)
roll_yearly
data = pd.DataFrame({'Monthly return': monthly_return, 'Rolling Yearly average': roll_yearly.mean()})
ax = data.plot(style=['-', ':'])
ax.patch.set_facecolor('white')
ax.lines[0].set_alpha(0.3)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11837723281864972, 'fraction_numerical': 0.01937632455343627, 'mean_word_length': 7.158024691358024, 'pattern_counts': {'":': 0, '<': 53, '<?xml version=': 0, '>': 53, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '346372', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 1199, 'n_tokens_neox': 1138, 'n_words': 270, 'path': '09_Time_Series/Apple_Stock/Exercises.ipynb', 'repo_name': 'BrownianNotion/pandas_exercises', 'size': '3303'}