Skip to content

Instantly share code, notes, and snippets.

@jl4730
Created June 9, 2021 03:09
Show Gist options
  • Save jl4730/2e21d23ca8263d95d9134ff90656ca32 to your computer and use it in GitHub Desktop.
Save jl4730/2e21d23ca8263d95d9134ff90656ca32 to your computer and use it in GitHub Desktop.
def calculate_stats(allocs, prices):
# standardize the price series
prices_norm = prices / prices.iloc[0,:]
# Get position values
position_val = prices_norm * allocs
# Sum to get portfolio value
portfolio_val = position_val.sum(axis = 1)
# Calculate portfolio cumulative return
cr = (portfolio_val[-1] / portfolio_val[0]) - 1
# Calculate portfolio daily return series
port_daily_returns = (portfolio_val/portfolio_val.shift(1) - 1)
# Calculate average daily return
adr = port_daily_returns.mean()
# Calculate standard deviation of daily return
sddr = port_daily_returns.std()
# Calculate Sharpe Ratio - For simplicity assuming risk free rate is 0
sr = adr / sddr * np.sqrt(252)
return cr, adr, sddr, sr
# Minimize the negative value of the Sharpe ratio as it's essentially the
# same as maximizing of the Sharpe ratio
def min_func_sharpe(allocs, prices):
return -calculate_stats(allocs, prices)[3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment