python 投资组合

玩美金融 2020-09-02

import yfinance as yf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(font='SimHei',rc={'figure.figsize':(15,9)})
tickers = {
    '000001.SS': '上证综指',
    '600519.SS': '贵州茅台',
    '518880.SS': '黄金ETF'
}

data = yf.download(list(tickers), start='2019-06-01', end='2020-09-01')['Close']
data.rename(columns=tickers, inplace=True)
data.head()  # 取前五

#画图
(data/data.iloc[0]).plot()

#收益率
r_log = np.log(data/data.shift(1))
#年化收益率
r_annual = np.exp(r_log.mean()*252)-1
r_annual

#风险
std = np.sqrt(r_log.var()*252) #标准差


# 随机生成权重
def gen_weights(n):
    w = np.random.rand(n)
    return w / np.sum(w)


n = len(list(tickers))
w = gen_weights(n)

list(zip(r_annual.index, w))

#投资收益
def port_ret(w):
    return np.sum(w * r_annual)

#投资风险(组合的标准差)
def port_std(w):
    return np.sqrt(w.T.dot((r_log.cov()*252).dot(w)))
port_std(w)


# 生成多次随机的投资组合
def gen_ports(times):
    for p in range(times):
        w = gen_weights(n)
        yield (port_std(w), port_ret(w), w)


df = pd.DataFrame(gen_ports(3000), columns=['std', 'ret', 'w'])
df.head()

#夏普比率
df['sharp'] = (df['ret']-0.03)/df['std']
plt.scatter(df['std'],df['ret'],c=df['sharp'],cmap='coolwarm',marker='o')
plt.grid(True)
plt.xlabel('pstd')
plt.ylabel('pret')
plt.colorbar(label='sharp')

#推荐投资组合
list(zip(r_annual.index,df.loc[df.sharp.idxmax()].w))

sharp = (port_ret(w)-0.03)/port_std(w)
sharp

引用:https://blog.csdn.net/awishw/article/details/107693797?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param

多股票投资组合:

https://blog.csdn.net/asialee_bird/article/details/89417750

利用ARIMA进行时间序列数据分析:

https://blog.csdn.net/u012735708/article/details/82460962?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.channel_param

相关推荐

myveer / 0评论 2020-03-01