- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试解决一个优化问题,我需要创建一个投资组合,该投资组合与基准投资组合的跟踪误差最小,并且受到一些限制:
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()
最佳答案
在这种特殊情况下,最小化似乎只是忽略了不等式约束。我不知道为什么会发生这种情况 - 在测试一个更简单的示例时,相等和不等约束都可以正常工作。
等式约束通常会导致数值优化出现问题,因为 float 可能无法与它们完全匹配。摆脱等式约束似乎可以解决手头的问题。
约束 {'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
关于python - SciPy 优化器忽略了其中一个约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45697017/
我正在尝试设置我的 git 配置,以便我可以使用工作环境和个人环境。 这是我的 ~.gitconfig 文件的内容(碰巧 work 和 private 在 github 上): [url "git@
我有以下情况。我在 Sheet1 上有一个项目列表,我想将项目复制到 Sheet2 并排除特定项目。 假设我在 Sheet1 上有以下项目列表: 我想将“梨”单元格留在 Sheet2 上。 它应该完全
我试图让 gcc 以不同的语言提供错误消息。但它仍然给我英文的错误信息。 我的语言环境输出 varun@varun-desktop:$ 语言环境 LANG=en_IN LC_CTYPE="es_EC.
我在 Linux x86 上使用 gcc。 我的程序将指向 C 函数的指针导出到 LLVM JIT 函数。调用约定是 cdecl。它在 Windows 上的 MingW 上运行良好。但是奇怪的事情发生
windows 上 php 的奇怪问题...我的应用程序加载了一个“核心”文件,该文件加载了一个设置文件、注册自动加载、进行初始化等。在核心文件的顶部我有 include_once("config.p
在工具|选项|调试器选项 |语言异常可以忽略特定的异常类型。是否可以为每个项目定义这个?例如在调试构建配置中(Delphi 2009 和/或 2010)? /编辑:Reported in QC 最佳答
我在一个文本框旁边有 2 个按钮,在这 2 个按钮后面还有另一个文本框。第一个文本框的 tabindex 为 1000,第一个按钮为 1001,第二个按钮为 1002。第二个文本框的 tabindex
我是 python 新手,正在尝试类型提示,但它们似乎只在某些情况下起作用。它们似乎在属性返回类型上按预期工作,但是当我尝试将整数分配给字符串值(即 self._my_string = 4)时,我没有
问题陈述 我有一些国家和这些国家的州的依赖组合框。我使用 VBA 在第一个组合框中填充唯一值,然后在第二个组合框中动态填充唯一值。该代码似乎忽略了初始传递中的条件。 例如,该代码适用于第一个国家/地区
我对 Javascript 有点陌生。我试图做到这一点,以便单击一个页面上的图像会将您带到一个新页面,并在该新页面上显示特定的 div,因此我使用 sessionStorage 来记住并使用 bool
我不确定我是否正确地处理了这个问题。 我有一个 ASP.NET MVC Web 应用程序。有 4 个主要“页面”通过单击菜单选项,可以选择一个页面,并将该页面选项存储在本地存储中。 现在,如果我刷新页
我的页面工作正常,并按预期显示日期和时间,直到我不得不添加 new Date() 以避免 momentjs deprecation warning 。现在我的约会比应有的时间晚了 5 个小时。 我该如
我需要合并一个 fork 项目。不幸的是,CVS $Id 行不同,因此我尝试的合并工具报告所有文件都不同(其中 95% 只有这一行不同) 是否有一个合并工具可以配置为忽略基于模式的行比较结果? [编辑
我是 python 新手,正在尝试类型提示,但它们似乎只在某些情况下起作用。它们似乎在属性返回类型上按预期工作,但是当我尝试将整数分配给字符串值(即 self._my_string = 4)时,我没有
我正在尝试根据 How do a send an HTTPS request through a proxy in Java? 使用代理访问 https 网页 但是我遇到了一个奇怪的问题:HttpsU
我有一个简单的 CMakeLists.txt 文件: cmake_minimum_required(VERSION 2.8.9) project (sample) add_library(Shared
这个问题在这里已经有了答案: typedef pointer const weirdness (6 个答案) 关闭 8 年前。 我有一个结构体 type_s。然后我将指向 struct type_s
我正在尝试制作一个使用 AES 256 加密的应用程序。不幸的是我无法让它工作。也许我没有完全理解密码逻辑。 所以它正在工作,但据我了解,哈希包含密码。但如果我更改密码,输出是相同的。因此,Crypt
我的文件包含一些行,例如 "This is a string." = "This is a string's content." " Another \" example \"" = " New ex
我尝试使用此查询来获取所选健身房的所有用户。 我的问题是查询忽略了这部分:ual.user_id = weekUsers.user_id 查询似乎获取了与我选择的日期匹配的所有用户 ID,而不检查该用
我是一名优秀的程序员,十分优秀!