2017-08-15 33 views
3

我試圖解決一個優化問題,我需要建立一個組合,從基準投資組合中最小的跟蹤誤差,它是受到一些限制:SciPy的優化忽視的制約因素一個

import scipy.optimize as opt 
import numpy as np 

def random_portfolio(n): 
    a = np.random.random(n) 
    a /= a.sum() 
    return a 

portfolio_weights = [1 for i in range(20)] 
portfolio_weights = [i/len(portfolio_weights) for i in portfolio_weights] 

def tracking_error_function(W, port_weights): 
    weight_diff = list(np.array(port_weights)-np.array(W)) 
    weight_diff = sum([i**2 for i in weight_diff]) 
    return weight_diff 

def total_max_weight_constraint(weights): 
    max_weights_share = sum([i for i in weights if i > 0.045]) 
    max_ineq = 0.36 - max_weights_share 
    return max_ineq 

def gen_initial_weights(n): 
    max_weights = [0.089 for i in range(4)] 
    rest_of_n = n - 4 
    rest_of_weight = 1 - sum(max_weights) 
    other_weights = [rest_of_weight/rest_of_n for i in range(rest_of_n)] 
    all_weights = max_weights + other_weights 
    return all_weights 

initial_weights = np.asarray(gen_initial_weights(len(portfolio_weights))) 

tr_err = tracking_error_function(initial_weights, portfolio_weights) 
b_ = [(0.0, 0.09) for i in range(len(initial_weights))] 
c_ = ({'type': 'eq', 'fun': lambda W: sum(W) - 1}, 
    {'type': 'ineq', 'fun': total_max_weight_constraint}) 

optimized = opt.minimize(tracking_error_function, initial_weights, args=(portfolio_weights), method='SLSQP', constraints=c_, bounds=b_, options={'maxiter': 100000 }) 

所以我初始猜測遵守約束條件,基準線的權重相等。當我運行它時,結果是完全相等的權重組合,雖然它顯然違反了第二個約束。而且,地位是成功的。任何想法我做錯了什麼?

更新: 這是似乎在我的情況

import scipy.optimize as opt 
import numpy as np 
import random 
import matplotlib.pyplot as plt 


def random_portfolio(n): 
    #random.seed(123) 
    a = np.random.random(n) 
    a /= a.sum() 
    return a 

def continous_step_function(x, cutoff): 
    return x/(1 + safe_exp(-(x - cutoff) * 200000)) 

def safe_exp(x): 
    try: 
     ans = np.math.exp(x) 
    except OverflowError: 
     ans = float('inf') 
    return ans 

def gen_initial_weights(n): 
    max_weights = [0.0899999 for i in range(4)] 
    rest_of_n = n - 4 
    rest_of_weight = 1 - sum(max_weights) 
    other_weights = [rest_of_weight/rest_of_n for i in range(rest_of_n)] 
    all_weights = max_weights + other_weights 
    return all_weights 

def tracking_error_function(W, port_weights): 
    weight_diff = port_weights - W 
    weight_diff = np.sum(weight_diff ** 2) 

    excessive_weight = max(0,(sum([continous_step_function(i,0.045) for i in W]) - 0.36)) 

    return weight_diff + excessive_weight 

def total_max_weight_constraint(weights): 
    max_weights_share = sum([continous_step_function(i,0.045) for i in weights]) 
    max_ineq = 0.36 - max_weights_share 
    return max_ineq 

def run(): 
    portfolio_weights = sorted(random_portfolio(20)) 

    initial_weights = np.asarray(gen_initial_weights(len(portfolio_weights))) 
    initial_weights = sorted(initial_weights) 

    b_ = [(0.0, 0.09) for i in range(len(initial_weights))] 
    c_ = ({'type': 'eq', 'fun': lambda W: sum(W) - 1}, 
      {'type': 'ineq', 'fun': total_max_weight_constraint} 
     ) 

    optimized = opt.minimize(tracking_error_function, initial_weights, args=(portfolio_weights), constraints=c_, 
          bounds=b_, options={'eps': 0.00000001, 'ftol' : 0.00000001, 'iprint': 0, 'disp': 0, 'maxiter': 10000}) 

    result = optimized.x 

    if tracking_error_function(result, portfolio_weights) > 0.05: 
     print('Excessive tracking error: ') 
     print('Residual error: {}'.format(tracking_error_function(result, portfolio_weights))) 
     print('Target: {} {}'.format(sum(portfolio_weights), portfolio_weights)) 
     print('Result: {} {}'.format(sum(result), result)) 

    if sum([i for i in result if i > 0.045]) > 0.36: 
     print('Excessive weight > .045: ') 
     print('Percentage > .045: {}'.format(sum([x for x in result if x > 0.045]))) 
     print('Target: {} {}'.format(sum(portfolio_weights), portfolio_weights)) 
     print('Result: {} {}'.format(sum(result), result)) 

    if not all(b >= (a - 0.001) for a, b in zip(result, result[1:])): 
     print('Result not continously rising: ') 
     print('Target: {} {}'.format(sum(portfolio_weights), portfolio_weights)) 
     print('Result: {} {}'.format(sum(result), result)) 

def plot_output(result, target): 
    plt.bar(range(len(result)), result, color='b', width = 0.3) 
    plt.plot(range(len(target)), target, color='r') 
    plt.show() 
+0

我認爲問題在於你的'initial_weights'違反了約束條件。但是,我不知道爲什麼'opt.minimize'不會抱怨。 (順便說一句,很好的自包含的例子!) – kazemakase

+0

我認爲相同,所以我創建了一個不違反約束條件的初始投資組合: –

+0

對於凌亂的代碼感到抱歉。習慣於在堆棧溢出中寫入 –

回答

0

看來,最小化簡單地忽略在這種特殊情況下的不等式約束工作的解決方案。我不知道爲什麼會發生這種情況 - 當測試一個簡單的例子時,平等和不平等約束一起正確地工作。

等式約束通常會導致數字優化問題,因爲浮點數可能無法與其完全匹配。擺脫平等約束似乎是解決手頭問題的一種解決方法。

約束{'type': 'eq', 'fun': lambda W: sum(W) - 1}強制所有N的權重來概括準確到1。有另一種方式來執行這樣的:我們可以優化只N-1權重和約束它們的和是< 1,然後將剩餘的重量1 - sum(other_weights)是隱式給出。這需要一些修改代碼:

def expand_weights(weights): 
    """This function takes N-1 weights and adds the implicit Nth weight 
     so that together their sum is 1.""" 
    return np.append(weights, 1 - np.sum(weights)) 

def tracking_error_function(W, port_weights): 
    weight_diff = port_weights - expand_weights(W) 
    weight_diff = np.sum(weight_diff ** 2) 
    return weight_diff 

def total_max_weight_constraint(weights): 
    weights = expand_weights(weights) 
    max_weights_share = sum([i for i in weights if i > 0.045]) 
    max_ineq = 0.36 - max_weights_share 
    return max_ineq 

我們乾脆把原來的初始權重,並刪除最後一個:

initial_weights = np.asarray(gen_initial_weights(len(portfolio_weights))) 
initial_weights = initial_weights[:-1] 

最後,成爲制約:

c_ = ({'type': 'ineq', 'fun': lambda W: 1 - sum(W)}, 
     {'type': 'ineq', 'fun': total_max_weight_constraint}) 

運行優化並查看約束是否得到滿足:

optimized = opt.minimize(tracking_error_function, initial_weights, 
         args=(portfolio_weights), method='SLSQP', 
         constraints=c_, bounds=b_, 
         options={'maxiter': 100000, 'disp': 5}) 

assert np.allclose(1, np.sum(expand_weights(optimized.x))) # check equality constraint 
assert total_max_weight_constraint(optimized.x) > 0 # check second constraint 
+0

非常感謝您的解決方法。我測試了它。有趣的是,它適用於n = 20和22,但違反了n = 19和n = 21的限制。不知道爲什麼。它似乎與浮點基準權重有關。因爲我的初始權重保持不變。 –