<jupyter_start><jupyter_text>Finance notebooks  Some basics: prices and returns  Let's start with some basics in financial markets analysis! We'll use **python** (https://www.python.org/) as programming language, starting with **pandas** (http://pandas.pydata.org/), a well-renowned module for data manipulation and analysis. First of all, let's import the modules we need.<jupyter_code>import pandas as pd
import pandas_datareader.data as web
import matplotlib.pyplot as plt

# Defines the chart color scheme using Tableu's Tableau10 
plt.style.use('https://gist.githubusercontent.com/mbonix/8478091db6a2e6836341c2bb3f55b9fc/raw/7155235ed03e235c38b66c160d402192ad4d94d9/tableau10.mplstyle')

%matplotlib inline<jupyter_output><empty_output><jupyter_text>Then, let's choose a bunch of stocks to analyze. They are: **Apple** (AAPL), **Alphabet** (former Google, GOOGL), **Microsoft** (MSFT), **McDonald's** (MCD), **Coca-Cola** (KO). Three technology companies and two food & beverage stocks.<jupyter_code># List of stocks tickers
STOCKS = ['NASDAQ:AAPL', 'NASDAQ:GOOGL', 'NASDAQ:MSFT', 'NYSE:MCD', 'NYSE:KO']

# Analysis period
START = '12-30-2006'
END = '12-31-2016'<jupyter_output><empty_output><jupyter_text>Now, let's download stock data from Yahoo!Finance, using **pandas-datareader** module.<jupyter_code>data = web.DataReader(STOCKS, 'google', pd.to_datetime(START), pd.to_datetime(END))<jupyter_output><empty_output><jupyter_text>We'll work only on **Close** prices, so let's discard the other data.<jupyter_code>prices = data.loc['Close', :, :]
prices.tail(10)<jupyter_output><empty_output><jupyter_text>Now, let's plot prices.<jupyter_code>prices.plot(figsize=(10, 8), title='Stock prices');<jupyter_output><empty_output><jupyter_text>**Alphabet**, or Google, seems to be the winner in these 10 years. But comparison of stocks is difficult because of different ranges of prices. Let's try to normalize them, rebasing to 100.<jupyter_code>norm_prices = 100 * prices / prices.iloc[0, :]
norm_prices.head(10)<jupyter_output><empty_output><jupyter_text>Now, a plot of rebased prices.<jupyter_code>norm_prices.plot(figsize=(10, 8), title='Stock prices ({} = 100)'.format(START));<jupyter_output><empty_output><jupyter_text>Now, it's clear that **Apple** and not Alphabet was the winner. Which was its return over the period, anyway? Let's calculate it!<jupyter_code>absolute_returns = (norm_prices.iloc[-1, :]).to_frame().T
absolute_returns.index = ['Absolute Return (%)']
absolute_returns<jupyter_output><empty_output><jupyter_text>An astonishing **967.59%**! Or a **26.72%** compound annual return, if you prefer.<jupyter_code>compound_returns = 100 * ((1 + absolute_returns / 100) ** 0.1 - 1)
compound_returns.index = ['Compound Annual Return (%)']
compound_returns<jupyter_output><empty_output><jupyter_text>Now, let's resample data into yearly percent returns.<jupyter_code>yearly_returns = prices.resample('A').last().pct_change()
yearly_returns<jupyter_output><empty_output><jupyter_text>Then, let's plot the returns.<jupyter_code>ax = yearly_returns.plot(figsize=(10, 8), title='Stock yearly returns', ls='', marker='o');
ax.set_xlim(ax.get_xlim()[0], ax.get_xlim()[1] + 1)
ax.axhline(0, color='gray');<jupyter_output><empty_output><jupyter_text>And let's see how returns averaged in the period.<jupyter_code>yearly_avgs = yearly_returns.mean().to_frame().T
yearly_avgs.index = ['Average Yearly Return (%)']
yearly_avgs<jupyter_output><empty_output><jupyter_text>Then we can compute yearly logarithmic returns over the period.<jupyter_code>import numpy as np

yearly_log_returns = prices.resample('A').last().apply(np.log).diff()
yearly_log_returns<jupyter_output><empty_output><jupyter_text>Let's also plot log returns.<jupyter_code>ax = yearly_log_returns.plot(figsize=(10, 8), title='Stock yearly log returns', ls='', marker='o');
ax.set_xlim(ax.get_xlim()[0], ax.get_xlim()[1] + 1)
ax.axhline(0, color='gray');<jupyter_output><empty_output><jupyter_text>Again, let's compute averages. Quite different from percent returns, aren't they?<jupyter_code>yearly_log_avgs = yearly_log_returns.mean().to_frame().T
yearly_log_avgs.index = ['Average Yearly Log Return (%)']
yearly_log_avgs<jupyter_output><empty_output><jupyter_text>We always can transform percent returns into log returns:<jupyter_code>(1 + yearly_returns).apply(np.log)<jupyter_output><empty_output><jupyter_text>And vice versa:<jupyter_code>(yearly_log_returns).apply(np.exp) - 1<jupyter_output><empty_output><jupyter_text>If we plot daily returns, we can clearly see a different scale over time and across stocks. Let's try with **Apple** and **McDonald's**.<jupyter_code>prices.loc[:, ['NASDAQ:AAPL', 'NYSE:MCD']].pct_change().plot(figsize=(10, 8), title="Apple and McDonald's daily returns")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1416371589252239, 'fraction_numerical': 0.027285982087065196, 'mean_word_length': 8.164122137404581, 'pattern_counts': {'":': 0, '<': 73, '<?xml version=': 0, '>': 73, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '18', 'dir': 'jupyter-structured-clean-dedup', 'id': '152258', 'license': 'MIT', 'n_tokens_mistral': 1822, 'n_tokens_neox': 1672, 'n_words': 367, 'path': 'Prices and Returns.ipynb', 'repo_name': 'mbonix/finance-notebooks', 'size': '4801'}