Skip to content

Instantly share code, notes, and snippets.

@accessnash
Last active July 16, 2018 18:14
Show Gist options
  • Select an option

  • Save accessnash/05e54776da0ef68943b3b70ecf997a23 to your computer and use it in GitHub Desktop.

Select an option

Save accessnash/05e54776da0ef68943b3b70ecf997a23 to your computer and use it in GitHub Desktop.
Intro to Portfolio Risk Management in Python - course on Datacamp - Chapter 1
import pandas as pd
import numpy as np
from scipy.stats import skew
from scipy.stats import kurtosis
from scipy import stats
from scipy.stats import shapiro
# Chapter 1: Univariate Investment Risk and Returns
StockPrices = pd.read_csv('StockData.csv', parse_dates=['Date'])
StockPrices = StockPrices.sort_values(by='Date')
StockPrices.set_index('Date', inplace=True)
# Read in the csv file
StockPrices = pd.read_csv(fpath_csv, parse_dates=['Date'])
# Ensure the prices are sorted by Date
StockPrices = StockPrices.sort_values(by='Date')
# Print the first five rows of StockPrices
print(StockPrices.head())
# Calculate the daily returns of the adjusted close price
StockPrices['Returns'] = StockPrices['Adjusted'].pct_change()
# Check the first five rows of StockPrices
print(StockPrices.head())
# Plot the returns over time
StockPrices['Returns'].plot()
plt.show()
# Convert the decimal returns into percentage returns
percent_return = StockPrices['Returns']*100
# Drop the missing values
returns_plot = percent_return.dropna()
# Plot the returns histogram
plt.hist(returns_plot, bins=75, density=False)
plt.show()
# Calculate the average daily return of the stock
mean_return_daily = np.mean(StockPrices['Returns'])
print(mean_return_daily)
# Calculate the implied annualized average return
mean_return_annualized = ((1 + mean_return_daily)**252)-1
print(mean_return_annualized)
# Calculate the standard deviation of daily return of the stock
sigma_daily = np.std( StockPrices['Returns'])
print(sigma_daily)
# Calculate the daily variance
variance_daily = sigma_daily**2
print(variance_daily)
sigma_annualized = sigma_daily*np.sqrt(252)
print(sigma_annualized)
# Calculate the annualized variance
variance_annualized = sigma_annualized**2
print(variance_annualized)
# Drop the missing values
clean_returns = StockPrices['Returns'].dropna()
# Calculate the third moment (skewness) of the returns distribution
returns_skewness = skew(clean_returns)
print(returns_skewness)
# Calculate the excess kurtosis of the returns distribution
excess_kurtosis = kurtosis(clean_returns)
print(excess_kurtosis)
# Derive the true fourth moment of the returns distribution
fourth_moment = excess_kurtosis + 3
print(fourth_moment)
# Run the Shapiro-Wilk test on the stock returns
shapiro_results = stats.shapiro(clean_returns)
print("Shapiro results:", shapiro_results)
# Extract the p-value from the shapiro_results
p_value = shapiro_results[1]
print("P-value: ", p_value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment