The Sharpe ratio, defined by William Sharpe, is a fundamental investing metric. The ratio is given as follows:
The ratio depends on the returns of the asset and the returns of a benchmark. We will use the S&P 500 index as the benchmark. The ratio is supposed to represent a reward to risk ratio. We want to maximize reward while minimizing risk, which corresponds to maximizing the Sharpe ratio.
Another important investing variable is liquidity. Cash is the ultimate liquid asset, but most other assets are less liquid, which means that they change value when we try to sell or buy them. We will use trading volume in this recipe as a measure of liquidity. (Trading volume corresponds to the number of transactions for a financial asset. Liquidity measures how liquid an asset is—how easy it is to buy or sell it.)
You can find the code in the sharpe_liquidity.ipynb
file in this book's code bundle:
import numpy as np import dautil as dl import matplotlib.pyplot as plt import ch7util
def calc_metrics(ticker, ohlc): stock = ohlc.get(ticker) sp500 = ohlc.get('^GSPC') merged = ch7util.merge_sp500(stock, sp500) rets_stock = ch7util.log_rets(merged['Adj Close_stock']) rets_sp500 = ch7util.log_rets(merged['Adj Close_sp500']) stock_sp500 = rets_stock - rets_sp500 sharpe_stock = stock_sp500.mean()/stock_sp500.std() avg_vol = np.log(merged['Volume_stock'].mean()) return (sharpe_stock, avg_vol)
ch7util
module:dfb = dl.report.DFBuilder(cols=['Ticker', 'Sharpe', 'Log(Average Volume)']) ohlc = dl.data.OHLC() for symbol in ch7util.STOCKS: sharpe, vol = calc_metrics(symbol, ohlc) dfb.row([symbol, sharpe, vol]) df = dfb.build(index=ch7util.STOCKS)
_, ax = plt.subplots() ax.scatter(df['Log(Average Volume)'], df['Sharpe']) dl.plotting.plot_polyfit(ax, df['Log(Average Volume)'], df['Sharpe']) dl.plotting.plot_text(ax, df['Log(Average Volume)'], df['Sharpe'], ch7util.STOCKS) ax.set_xlabel('Log(Average Volume)') ax.set_ylabel('Sharpe') ax.set_title('Sharpe Ratio & Liquidity')
Refer to the following screenshot for the end result: