2016-12-14 29 views
3

我正在运行一个庞大的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 

回答

2

在我的环境,mutmul@)具有适度的时间优势einsumdot

In [27]: np.allclose(np.einsum('ijk,k',asset_returns,weights),[email protected] 
    ...: hts) 
Out[27]: True 
In [28]: %timeit [email protected] 
100 loops, best of 3: 3.91 ms per loop 
In [29]: %timeit np.einsum('ijk,k',asset_returns,weights) 
100 loops, best of 3: 4.73 ms per loop 
In [30]: %timeit np.dot(asset_returns,weights) 
100 loops, best of 3: 6.8 ms per loop 

我认为时间是由计算的总数,比编码细节较为有限。所有这些都将计算传递给编译的numpy代码。原始循环版本相对较快的事实可能与较少的循环(仅60)以及更全面的dot中的内存管理问题有关。

numba可能不会取代dot的代码。

因此,这里或那里的调整可能会使您的代码加速2倍,但不要期望数量级的提高。

+0

谢谢!知道我能期待什么是一个很大的帮助,然后我会看看其余的代码。 –

1

下面是一个使用np.einsum得到一个加速的一点点版本:

def get_pf_returns3(weights, asset_returns, horizon=60): 
    pf = np.ones(asset_returns.shape[1]) 
    z = np.einsum("ijk,k -> ij",asset_returns[:horizon,:,:], weights) 
    pf = np.multiply.reduce(1 + z) 
    return pf ** (12.0/horizon) - 1 

然后计时:

%timeit get_pf_returns(weights, asset_returns) 
%timeit get_pf_returns3(weights, asset_returns) 
print np.allclose(get_pf_returns(weights, asset_returns), get_pf_returns3(weights, asset_returns)) 

# 1000 loops, best of 3: 727 µs per loop 
# 1000 loops, best of 3: 638 µs per loop 
# True 

机器上的时间可能会因硬件而有所不同,而库numpy是编译时的时间。