在 Julia(或 Matlab)中绘制投资组合构成图

Plot portfolio composition map in Julia (or Matlab)

我正在优化 N 股票的投资组合,超过 M 预期水平 return。因此,在这样做之后,我得到了权重的时间序列(即 N x M 矩阵,其中每一行都是特定预期水平的股票权重的组合 return)。权重加起来为 1.

现在我想绘制一个叫做投资组合构成图(图片右图)的图,它是这些股票权重在所有预期水平上的图return,每个都有不同的颜色和长度(在 return 的每个级别)与其重量成正比。

我的问题是如何在 Julia(或 MATLAB)中做到这一点?

matplotlib 具有非常强大的多边形绘图功能,例如link 关于绘制填充的多边形:

ploting filled polygons in python

您可以通过出色的 PyPlot.jl 包从 Julia 使用它。

请注意,某些内容的语法会发生变化;请参阅 PyPlot.jl 自述文件,例如this 示例集。

您 "just" 需要根据矩阵计算坐标并构建一组多边形来绘制投资组合构成图。如果能正常运行,很高兴看到代码!

所以我能够画出来,这是我的代码:

using PyPlot
using PyCall
@pyimport matplotlib.patches as patch

N = 10
D = 4

weights = Array(Float64, N,D)

for i in 1:N
    w = rand(D)
    w = w/sum(w)
    weights[i,:] = w
end
weights = [zeros(Float64, N) weights]
weights = cumsum(weights,2)
returns = sort!([linspace(1,N, N);] + D*randn(N))

##########
#  Plot  #
##########
polygons = Array(PyObject, 4)
colors = ["red","blue","green","cyan"]
labels = ["IBM", "Google", "Apple", "Intel"]
fig, ax = subplots()
fig[:set_size_inches](5, 7)
title("Problem 2.5 part 2")
xlabel("Weights")
ylabel("Return (%)")
ax[:set_autoscale_on](false)
ax[:axis]([0,1,minimum(returns),maximum(returns)])

for i in 1:(size(weights,2)-1)
    xy=[weights[:,i] returns;
        reverse(weights[:,(i+1)]) reverse(returns)]
    polygons[i] = matplotlib[:patches][:Polygon](xy, true, color=colors[i], label = labels[i])
    ax[:add_artist](polygons[i])
end

legend(polygons, labels, bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0)

show()
# savefig("CompositionMap.png",bbox_inches="tight")

不能说这是最好的方法,但至少它是有效的。

我遇到了这个,接受的解决方案似乎很复杂。以下是我的做法:

using Plots
@userplot PortfolioComposition

@recipe function f(pc::PortfolioComposition)
    weights, returns = pc.args
    weights = cumsum(weights,dims=2)
    seriestype := :shape
    for c=1:size(weights,2)
        sx = vcat(weights[:,c], c==1 ? zeros(length(returns)) : reverse(weights[:,c-1]))
        sy = vcat(returns, reverse(returns))
        @series Shape(sx, sy)
    end
end

# fake data
tickers = ["IBM", "Google", "Apple", "Intel"]
N = 10
D = length(tickers)
weights = rand(N,D)
weights ./= sum(weights, dims=2)
returns = sort!((1:N) + D*randn(N))

# plot it
portfoliocomposition(weights, returns, labels = tickers)