我正在運行一個龐大的Python程序來優化(Markowitz)金融投資組合優化投資組合權重。當我剖析代碼時,90%的運行時間用於計算投資組合回報,這已經完成了數百萬次。我能做些什麼來加速我的代碼?我曾嘗試:如何加速異形NumPy代碼 - 矢量化,Numba?
- 矢量化回報的計算:使代碼較慢,從1.5毫秒〜3毫秒
- 用於從Numba功能autojit加快代碼:無變化
請參閱下面的示例 - 任何建議?
import numpy as np
def get_pf_returns(weights, asset_returns, horizon=60):
'''
Get portfolio returns: Calculates portfolio return for N simulations,
assuming monthly rebalancing.
Input
-----
weights: Portfolio weight for each asset
asset_returns: Monthly returns for each asset, potentially many simulations
horizon: 60 months (hard-coded)
Returns
-------
Avg. annual portfolio return for each simulation at the end of 5 years
'''
pf = np.ones(asset_returns.shape[1])
for t in np.arange(horizon):
pf *= (1 + asset_returns[t, :, :].dot(weights))
return pf ** (12.0/horizon) - 1
def get_pf_returns2(weights, asset_returns):
''' Alternative '''
return np.prod(1 + asset_returns.dot(weights), axis=0) ** (12.0/60) - 1
# Example
N, T, sims = 12, 60, 1000 # Settings
weights = np.random.rand(N)
weights *= 1/np.sum(weights) # Sample weights
asset_returns = np.random.randn(T, sims, N)/100 # Sample returns
# Calculate portfolio risk/return
pf_returns = get_pf_returns(weights, asset_returns)
print np.mean(pf_returns), np.std(pf_returns)
# Timer
%timeit get_pf_returns(weights, asset_returns)
%timeit get_pf_returns2(weights, asset_returns)
編輯
解決方案:MATMUL是我的機器上速度最快:
def get_pf_returns(weights, asset_returns):
return np.prod(1 + np.matmul(asset_returns, weights), axis=0) ** (12.0/60) - 1
謝謝!知道我能期待什麼是一個很大的幫助,然後我會看看其餘的代碼。 –