Python:投资组合优化工具

2024-04-26 00:32:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习如何编写代码,并选择Python来实现这一点。我的第一个任务是优化投资组合和有效前沿。我发现了@s666写的一段很棒的代码。与一般优化情况一样,约束条件如下:1)权重之和=1,以及2)没有库存的权重>;1.

在下面显示的代码中,您能告诉我如何添加第三个约束条件,其中除上述约束条件外,考虑的3种股票还有各自的重量边界,即0.2>;AAPL<;0.7; 0.3<;阿姆森<;0.8; 0.1<;MSFT<;0.6

提前谢谢你

import numpy as np
import pandas as pd
from pandas_datareader import data as d
import matplotlib.pyplot as plt
#list of stocks in portfolio
stocks = ['AAPL','AMZN','MSFT']#,'YHOO']
#download daily price data for each of the stocks in the portfolio
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2018, 12, 31)
data = pd.DataFrame([d.DataReader(ticker, 'yahoo', start, end)['Adj Close'] for ticker in stocks]).T
data.columns = stocks

#convert daily stock prices into daily returns
returns = data.pct_change()
#calculate mean daily return and covariance of daily returns
mean_daily_returns = returns.mean()
cov_matrix = returns.cov()
#set number of runs of random portfolio weights
num_portfolios = 25000
#set up array to hold results
#We have increased the size of the array to hold the weight values for each stock
results = np.zeros((3+len(stocks),num_portfolios))
for i in range(num_portfolios):
    #select random weights for portfolio holdings
    weights = np.array(np.random.random(len(stocks)))
    #rebalance weights to sum to 1
    weights /= np.sum(weights)

    #calculate portfolio return and volatility
    portfolio_return = np.sum(mean_daily_returns * weights) * 252
    portfolio_std_dev = np.sqrt(np.dot(weights.T,np.dot(cov_matrix, weights))) * np.sqrt(252)

    #store results in results array
    results[0,i] = portfolio_return
    results[1,i] = portfolio_std_dev
    #store Sharpe Ratio (return / volatility) - risk free rate element excluded for simplicity
    results[2,i] = results[0,i] / results[1,i]
    #iterate through the weight vector and add data to results array
    for j in range(len(weights)):
        results[j+3,i] = weights[j]
#convert results array to Pandas DataFrame
results_frame = pd.DataFrame(results.T,columns=['ret','stdev','sharpe'] + [ticker for ticker in stocks])
#locate position of portfolio with highest Sharpe Ratio
max_sharpe_port = results_frame.iloc[results_frame['sharpe'].idxmax()]
#locate positon of portfolio with minimum standard deviation
min_vol_port = results_frame.iloc[results_frame['stdev'].idxmin()]
#create scatter plot coloured by Sharpe Ratio
plt.scatter(results_frame.stdev,results_frame.ret,c=results_frame.sharpe,cmap='RdYlBu')
plt.xlabel('Volatility')
plt.ylabel('Returns')
plt.colorbar()
#plot red star to highlight position of portfolio with highest Sharpe Ratio
plt.scatter(max_sharpe_port[1],max_sharpe_port[0],marker=(5,1,0),color='r',s=1000)
#plot green star to highlight position of minimum variance portfolio
plt.scatter(min_vol_port[1],min_vol_port[0],marker=(5,1,0),color='g',s=1000)

Tags: ofthetoinfordatanpplt
1条回答
网友
1楼 · 发布于 2024-04-26 00:32:42

您可能想再次尝试测量,使用openJDK 8u212或更多(2019年4月16日)。(没有Oracle JDK,因为their license has changed

参见Grzegorz Kocur中的“Docker support in Java 8 — finally!
现在:

There is no need to use any hacky workarounds in a docker entrypoint, nor setting Xmx as fixed value anymore.

Docker support was also backported to Java 8.
Let’s check the newest openjdk image tagged as 8u212. We’ll limit the memory to 1G and use 1 CPU:

docker run -ti  cpus 1 -m 1G openjdk:8u212-jdk

您可以使用新的标志(已经出现在Java10+中,但现在已重新移植到Java8)和explained here微调堆大小

-XX:InitialRAMPercentage
-XX:MaxRAMPercentage
-XX:MinRAMPercentage

If for some reason the new JVM behaviour is not desired it can be switched off using -XX:-UseContainerSupport.

相关问题 更多 >