Skip to content

Instantly share code, notes, and snippets.

@tomGdow
Created February 13, 2016 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomGdow/8a0ccad9737310e7fbdc to your computer and use it in GitHub Desktop.
Save tomGdow/8a0ccad9737310e7fbdc to your computer and use it in GitHub Desktop.
python 2 function for calculating the Sharpe Ratio
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## calcSharpe"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**1 Description **\n",
"\n",
" calcSharpe(start_date, end_date, ls_allocations, initial_allocation) \n",
" calculates the _annualized_ Sharpe ratio for an investment fund or a single stock\n",
" using the following formula"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$Sharpe\\ Ratio = {\\sqrt{Number\\ Trading\\ Days}\\ \\times\\ {{Average\\ Daily\\ Return}\\over {Standard\\ Deviation}}}$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**2 Usage **\n",
"\n",
"To calculate the annualized Sharpe Ratio for Apple ('aapl') for the year 2010, \n",
"with an initial allocation of 1"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"data": {
"text/plain": [
"1.6854261764221505"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"calcSharpe(dt.datetime(2010, 1, 1), dt.datetime(2010, 12, 31), ['AAPL'], [1],initial_allocation=1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"** Usage**\n",
"\n",
"To calculate the annualized Sharpe ratio for 2010 for a fund consisting of four stocks, \n",
"AAPL, BRCM, TXN,ADI, using a weighting factor of 0.25 for each fund, and an\n",
"initial allocation of 1"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"1.3171269057934021"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"calcSharpe(dt.datetime(2010, 1, 1), dt.datetime(2010, 12, 31), ['AAPL', 'BRCM', 'TXN', 'ADI'], [0.25, 0.25, 0.25, 0.25],initial_allocation=1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"** Usage**\n",
"\n",
"To calculate the annualized Sharpe Ratio of Apple (AAPL) for each \n",
"year from 2000 to 2012"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[-0.93904334765251041,\n",
" 0.97277269499193475,\n",
" -0.80979975389743264,\n",
" 1.1659624486930709,\n",
" 2.9658383823909986,\n",
" 2.3150902550685979,\n",
" 0.52024589363877627,\n",
" 2.507595011527894,\n",
" -1.1037245228671726,\n",
" 2.7114807424428973,\n",
" 1.6854261764221505,\n",
" 0.91996571936467764]"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"aapl_sharpe = []\n",
"for i in range(2000, 2012,1): \n",
" aapl_sharpe.append(\n",
" calcSharpe(dt.datetime(i, 1, 1), dt.datetime(i, 12, 31),\n",
" ['AAPL'], [1],initial_allocation=1))\n",
"aapl_sharpe "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"** 3 Dependencies**\n",
"\n",
" The [QTSK package](http://wiki.quantsoftware.org/index.php?title=QSToolKit_Installation_Guide), and the **getData()** function from that package. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"** 4 Notes**\n",
"\n",
"* The sum of the weighting factors (ls_allocations) should always equal 1. Thus for a single stock use a weighting factor of 1.\n",
"* The default value for the initial allocation is 1\n",
"* calcSharpe() is a modification of the function simulate() from the [QTSK package](http://wiki.quantsoftware.org/index.php?title=QSToolKit_Installation_Guide)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Functions and Dependencies"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/thomas/anaconda2/lib/python2.7/site-packages/QSTK/qstkutil/qsdateutil.py:36: FutureWarning: TimeSeries is deprecated. Please use Series\n",
" return pd.TimeSeries(index=dates, data=dates)\n"
]
}
],
"source": [
"import QSTK.qstkutil.qsdateutil as du\n",
"import QSTK.qstkutil.tsutil as tsu\n",
"import QSTK.qstkutil.DataAccess as da\n",
"# Third Party Imports\n",
"import datetime as dt\n",
"import matplotlib.pyplot as plt\n",
"import pandas as pd\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def getData(dt_start, dt_end, ls_symbols):\n",
"\n",
" # The Time of Closing is 1600 hrs \n",
" dt_timeofday = dt.timedelta(hours=16)\n",
" ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)\n",
"\n",
" # Creating an object of the dataaccess class with Yahoo as the source.\n",
" c_dataobj = da.DataAccess('Yahoo', cachestalltime=0)\n",
"\n",
" # Keys to be read from the data, it is good to read everything in one go.\n",
" ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']\n",
"\n",
" # Reading the data, now d_data is a dictionary with the keys above.\n",
" # Timestamps and symbols are the ones that were specified before.\n",
" ldf_data = c_dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys)\n",
" d_data = dict(zip(ls_keys, ldf_data))\n",
" \n",
" # Filling the data for NAN\n",
" for s_key in ls_keys:\n",
" d_data[s_key] = d_data[s_key].fillna(method='ffill')\n",
" d_data[s_key] = d_data[s_key].fillna(method='bfill')\n",
" d_data[s_key] = d_data[s_key].fillna(1.0)\n",
"\n",
" # Getting the numpy ndarray of close prices.\n",
" na_price = d_data['close'].values\n",
" \n",
" # returning the closed prices for all the days \n",
" return na_price\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def calcSharpe(dt_start, dt_end, ls_symbols, ls_allocations,initial_allocation=1):\n",
" \n",
" # This function returns the annualized Sharpe ratio for an investment fund \n",
"\n",
" na_price = getData(dt_start, dt_end, ls_symbols)\n",
" dt_timeofday = dt.timedelta(hours=16)\n",
" ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)\n",
" num_tradingDays = (len(ldt_timestamps))\n",
" \n",
" arr_firstdayPrices = na_price[0,:]\n",
" \n",
" fund_stats = np.zeros((num_tradingDays, 2)) # Number of trading days * 3\n",
"\n",
" for i in range(num_tradingDays):\n",
" for j in range(len(na_price[i,:])):\n",
" fund_stats[i,0] += ((na_price[i,j]/arr_firstdayPrices[j]) * ( initial_allocation * ls_allocations[j]) )\n",
"\n",
" for i in range(num_tradingDays):\n",
" if i != 0:\n",
" fund_stats[i,1] = ((fund_stats[i,0]/fund_stats[i-1,0]) - 1 )\n",
" \n",
" sharpe = (num_tradingDays **(1/2.0))*(np.average(fund_stats[:,[1]]) / np.std(fund_stats[:,[1]])) \n",
"\n",
" return sharpe\n",
" "
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.10"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment