<jupyter_start><jupyter_text>Calculating Returns<jupyter_code>%load autoreload
%autoreload 2

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import edhec_risk_kit as erk

prices = np.array([8.7, 8.91, 8.71])
prices[1]/prices[0]-1
prices[1:] / prices[:-1] - 1

df_prices = pd.DataFrame({'BLUE':[8.7, 8.91, 8.71, 8.43, 8.73],
                          'ORANGE':[10.66, 11.08, 10.71, 11.59, 12.11]})
df_prices
df_prices.iloc[1:] / df_prices[:-1].values -1 #Removing index from one varible
df_prices/df_prices.shift(1) - 1 # Shifting to the 1 row
df_prices.pct_change() # Using pct_change function from Pandas Dataframe

df_sample = pd.read_csv('course_1/sample_prices.csv')
df_sample

df_returns = df_sample.pct_change()
df_returns.plot.bar()
df_sample.plot()
print(df_returns.std()) # Standard Deviation of returns

df_returns = df_returns + 1

# using numpy to compound the returns
print(np.prod(df_returns)-1)<jupyter_output>BLUE      0.023977
ORANGE    0.079601
dtype: float64
BLUE      0.123310
ORANGE    0.087167
dtype: float64<jupyter_text>Annualization of Returns<jupyter_code>rm = 0.01 # 1% return per month
(1+rm) ** 12 -1 # return over a year

rd = 0.0001
(1+rd)**252 -1 # daily returns times trading days<jupyter_output><empty_output><jupyter_text>Risk-Adjusted Returns<jupyter_code>df_returns.std()

# calculating volatility step by step
deviations = df_returns - df_returns.mean()
sq_dev = deviations ** 2
vari = sq_dev.mean()
volatility = np.sqrt(vari) # remember that the standard deviation divides by n-1

print(volatility)
print(df_returns.std())

vari = sq_dev.sum()/(df_returns.shape[0] -1)
volatility = np.power(vari, 0.5)
print(volatility)

ann_volat = df_returns.std()*np.sqrt(12) # annualizing volatility
print(ann_volat)
# loading the dataset, indicating if it has header and telling it to try to figure out dates and specifying a value
# for the na's (99.99)
returns = pd.read_csv('course_1/Portfolios_Formed_on_ME_monthly_EW.csv', header=0, index_col=0,parse_dates=True,
                      na_values=99.99)

columns = ['Lo 10', 'Hi 10']
returns = returns[columns]/100
returns.columns = ['SmallCap', 'LargeCap']
returns.plot.line()

returns.std()

annualized_vol = returns.std()*np.sqrt(12)
annualized_vol

# annualizing returns
return_per_month = (returns + 1).prod() ** (1/returns.shape[0]) -1
return_per_month

annualized_return = (return_per_month + 1) ** (12) - 1
annualized_return

# risk-adjusted return
print(annualized_return / annualized_vol)

riskfree_rate = 0.03
excess_return = annualized_return - riskfree_rate
sharpe_ratio = excess_return / annualized_vol
sharpe_ratio # SmallCap give you a slightly superior return over LargeCap<jupyter_output>SmallCap    0.454825
LargeCap    0.497063
dtype: float64<jupyter_text>Risk-Adjusted Returns (Max Drawdown)A worst-case measure: if you buy at the peak-price and sell at the lowest.<jupyter_code>returns.index = pd.to_datetime(returns.index, format='%Y%m')
returns.index = returns.index.to_period('M')

# code to compute drawdowns
# 1. Compute a wealth index
# 2. Compute previous peaks
# 3. Compute the drawdown

wealth_index = 1000*(1+returns.LargeCap).cumprod() # multiply by each monthly-return
wealth_index.plot.line()


previous_peaks = wealth_index.cummax() # maximum up to a certain point
previous_peaks.plot.line()

drawdown = (wealth_index - previous_peaks)/ previous_peaks # maximum loss
plt.figure()
drawdown.plot()

drawdown['1975':].idxmin() # index of the minimum position
drawdown(returns.LargeCap)[['wealth', 'peaks']].plot()
drawdown(returns[:'1950'].LargeCap)[['wealth', 'peaks']].plot()
drawdown(returns.LargeCap).min()
returns_2 = erk.get_ffme_returns()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12415836251009965, 'fraction_numerical': 0.04847831941826017, 'mean_word_length': 5.1490066225165565, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, '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': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '210779', 'license': 'MIT', 'n_tokens_mistral': 1464, 'n_tokens_neox': 1330, 'n_words': 317, 'path': '.ipynb_checkpoints/introduction-checkpoint.ipynb', 'repo_name': 'dcardonav/finance_python', 'size': '3713'}