多股票投资组合+马科维茨计算组合

import matplotlib.pyplot as plt
from pandas import read_excel
import numpy as np
import tushare as ts
import pandas as pd
import datetime
token=''
pro=ts.pro_api(token)

获取财务数据

#获取财务数据
ticker_list = ['601318.SH','601336.SH','601398.SH','601888.SH','603993.SH']
for ticker in ticker_list:df = pro.daily_basic(ts_code = ticker,fields = 'ts_code,trade_date,total_mv,circ_mv,pe,pb')df1 = pro.daily(ts_code = ticker)df1.to_excel('stock_data/'+ticker + '.xlsx')df.to_excel('stock_data/'+ticker + '_basic.xlsx')

获取股票价格数据

#获取股票价格数据
ticker_list = ['601318.SH','601336.SH','601398.SH','601888.SH','603993.SH']
for ticker in ticker_list:df = pro.daily(ts_code = ticker)df.to_excel('stock_data/'+ticker + '.xlsx')

 设定股票池

#设定股票池
ticker_list = ['601318.SH','601336.SH','601398.SH','601888.SH','603993.SH']
#循环获取股票价格和财务数据
for ticker in ticker_list:df1 = pd.read_excel('stock_data/'+ticker + '.xlsx',engine='openpyxl')df2 = pd.read_excel('stock_data/'+ticker + '_basic.xlsx',engine='openpyxl')df2 = df2[['trade_date','pe','pb','total_mv','circ_mv']]df3 = pd.merge(df1,df2,on='trade_date')df3.to_excel('stock_data/'+ticker + '.xlsx')
#设定空的DataFrame变量,存储数据
StockPrices = pd.DataFrame()
#存储每只股票的平均市值
market_value_list = []
ticker_list = ['601318.SH','601336.SH','601398.SH','601888.SH','603993.SH']
for ticker in ticker_list:df = read_excel('stock_data/'+ticker+'.xlsx',engine='openpyxl')#更改日期格式df['trade_date'] = df.trade_date.apply(lambda x:datetime.datetime.strptime(str(x),"%Y%m%d").strftime("%Y-%m-%d"))#按照日期升序排列。上小下大df =df.sort_values('trade_date',ascending=True)stock_data = df.set_index('trade_date')#print(stock_data.head())
#     stock_data = stock_data.loc['2016-03-01':'2017-12-29']#print(stock_data.head())#获取股票收盘价StockPrices[ticker] = stock_data['close']#print(StockPrices.head())#将市值存入列表market_value_list.append(stock_data['total_mv'].mean())#print(market_value_list[:5])
StockPrices.index.name= 'trade_date'
print(StockPrices.head())#计算每日收益率,并丢弃缺失值
StockReturns = StockPrices.pct_change().dropna()
#打印前5行数据
print(StockReturns.head())

计算加权收益

#将收益率数据拷贝到新的变量stock_return,这是为了后续调用的方便
stock_return = StockReturns.copy()
#print(stock_return.head())
#设置组合权重,存储为numpy数据类型
portfolio_weights = np.array([0.32,0.15,0.10,0.18,0.25])
#计算加权的股票收益
WeightedReturns = stock_return.mul(portfolio_weights,axis=1)
#计算投资组合的收益
StockReturns['Portfolio'] = WeightedReturns.sum(axis=1)#print(StockReturns.head())
#绘制组合收益随时间变化的图
StockReturns.Portfolio.plot()
plt.show()

组合收益累计曲线

#定义累积收益曲线绘制函数
def cumulative_returns_plot(name_list):for name in name_list:CumlativeReturns = ((1+StockReturns[name]).cumprod()-1)CumlativeReturns.plot(label=name)plt.legend()plt.show()
#计算累积的组合收益,并绘图
cumulative_returns_plot(['Portfolio'])

等权重收益曲线

#等权重的投资组合
#设置投资组合中的股票的数据
numstocks = 5
#平均分配每一项的权重
portfolio_weights_ew = np.repeat(1/numstocks,numstocks)
#计算等权重组合的收益
StockReturns['Portfolio_EW'] = stock_return.mul(portfolio_weights_ew,axis=1).sum(axis=1)
#打印前5行数据
print(StockReturns.head())
#绘制累计收益曲线
cumulative_returns_plot(['Portfolio','Portfolio_EW'])

市值加权

#市值加权的投资组合
#将上述获得的每支股票的平均是指转换为数组
market_values = np.array(market_value_list)
#计算市值权重
market_weights = market_values / np.sum(market_values)
#计算市值加权的组合收益
StockReturns['Portfolio_MVal'] = stock_return.mul(market_weights,axis=1).sum(axis=1)
#打印前5行数据
print(StockReturns.head())
#绘制累积收益曲线
cumulative_returns_plot(['Portfolio','Portfolio_EW','Portfolio_MVal'])
投资组合的相关性分析
#投资组合的相关矩阵
#相关矩阵用于估算多支股票收益之间的线性关系
#计算相关矩阵
correlation_matrix = stock_return.corr()
#输出相关矩阵
print(correlation_matrix)
import seaborn as sns
#创建热力图
sns.heatmap(correlation_matrix,annot=True,cmap='rainbow',linewidths=1.0,annot_kws={'size':8})
plt.xticks(rotation=0)
plt.yticks(rotation=75)
plt.show()
#投资组合的协方差矩阵
#相关系数只反应了股票之间的线性关系,但并不能告诉我们股票的波动情况,而协方差矩阵则包含这一信息
#计算协方差矩阵
cov_mat = stock_return.cov()
#年化协方差矩阵
cov_mat_annual = cov_mat * 252
#输出协方差矩阵
print(cov_mat_annual)
sns.heatmap(cov_mat_annual,annot=True,cmap='rainbow',linewidths=1.0,annot_kws={'size':8})
#投资组合的标准差
#计算投资组合的标准差
portfolio_volatility = np.sqrt(np.dot(portfolio_weights.T,np.dot(cov_mat_annual,portfolio_weights)))
print(portfolio_volatility)
#计算股票的最优投资组合
#使用蒙特卡洛模拟Markowitz模型
#设置模拟的次数
number  = 10000
#设置空的numpy数组,用于存储每次模拟得到的权重,收益率和标准差
random_p = np.empty((number,7))
#设置随机数种子,这里是为了结果可重复
np.random.seed(7)#循环模拟10000次随机的投资组合
for i in range(number):#生成5个随机数,并归一化,得到一组随机的权重数据random5 = np.random.random(5)random_weight =  random5/np.sum(random5)#计算年平均收益率mean_return = stock_return.mul(random_weight,axis=1).sum(axis=1).mean()annual_return = (1+mean_return)**252 -1#计算年化标准差,也成为波动率random_volatility = np.sqrt(np.dot(random_weight.T,np.dot(cov_mat_annual,random_weight)))#将上面生成的权重,和计算得到的收益率、标准差存入数据random_p中random_p[i][:5] =random_weightrandom_p[i][:5] = annual_returnrandom_p[i][6] = random_volatility#将Numpy数组转化为DataF数据框
RandomPortfolios = pd.DataFrame(random_p)
#设置数据框RandomPortfolios每一列的名称
RandomPortfolios.columns=[ticker + '_weight' for ticker in ticker_list]+['Returns','Volatility']#绘制散点图
RandomPortfolios.plot('Volatility','Returns',kind='scatter',alpha=0.3)
plt.show()
#投资风险最小组合
#找到标准差最小数据的索引列
min_index = RandomPortfolios.Volatility.idxmin()#在收益-风险散点图中突出风险最小的点
RandomPortfolios.plot('Volatility','Returns',kind= 'scatter',alpha = 0.3)
x = RandomPortfolios.loc[min_index,'Volatility']
y = RandomPortfolios.loc[min_index,'Returns']
plt.scatter(x,y,color='red')
#将该点坐标显示在途中并保留四位小数
plt.text(np.round(x,4),np.round(y,4),(np.round(x,4),np.round(y,4)),ha= 'left',va='bottom',fontsize=10)
plt.show()
#提取足校波动组合对应的权重,并转换成numpy数组
GMV_weights = np.array(RandomPortfolios.iloc[min_index,0:numstocks])
#计算GMV投资组合收益
StockReturns['Portfolio_GMV'] = stock_return.mul(GMV_weights,axis=1).sum(axis=1)
#输出风险最小投资组合的权重
print(GMV_weights)
#投资风险最大组合
#找到标准差最大数据的索引列
max_index = RandomPortfolios.Volatility.idxmax()#在收益-风险散点图中突出风险最小的点
RandomPortfolios.plot('Volatility','Returns',kind= 'scatter',alpha = 0.3)
x = RandomPortfolios.loc[max_index,'Volatility']
y = RandomPortfolios.loc[max_index,'Returns']
plt.scatter(x,y,color='red')
#将该点坐标显示在途中并保留四位小数
plt.text(np.round(x,4),np.round(y,4),(np.round(x,4),np.round(y,4)),ha= 'left',va='bottom',fontsize=10)
plt.show()
#提取足校波动组合对应的权重,并转换成numpy数组
GMV_weights = np.array(RandomPortfolios.iloc[max_index,0:numstocks])
#计算GMV投资组合收益
StockReturns['Portfolio_GMV'] = stock_return.mul(GMV_weights,axis=1).sum(axis=1)
#输出风险最小投资组合的权重
print(GMV_weights)
#投资收益最小组合
#找到收益最小数据的索引列
min_index = RandomPortfolios.Returns.idxmin()#在收益-风险散点图中突出风险最小的点
RandomPortfolios.plot('Volatility','Returns',kind= 'scatter',alpha = 0.3)
x = RandomPortfolios.loc[min_index,'Volatility']
y = RandomPortfolios.loc[min_index,'Returns']
plt.scatter(x,y,color='red')
#将该点坐标显示在途中并保留四位小数
plt.text(np.round(x,4),np.round(y,4),(np.round(x,4),np.round(y,4)),ha= 'left',va='bottom',fontsize=10)
plt.show()
#提取足校波动组合对应的权重,并转换成numpy数组
GMV_weights = np.array(RandomPortfolios.iloc[min_index,0:numstocks])
#计算GMV投资组合收益
StockReturns['Portfolio_GMV'] = stock_return.mul(GMV_weights,axis=1).sum(axis=1)
#输出风险最小投资组合的权重
print(GMV_weights)
#投资收益最大组合
#找到收益最大数据的索引列
max_index = RandomPortfolios.Returns.idxmax()#在收益-风险散点图中突出风险最小的点
RandomPortfolios.plot('Volatility','Returns',kind= 'scatter',alpha = 0.3)
x = RandomPortfolios.loc[max_index,'Volatility']
y = RandomPortfolios.loc[max_index,'Returns']
plt.scatter(x,y,color='red')
#将该点坐标显示在途中并保留四位小数
plt.text(np.round(x,4),np.round(y,4),(np.round(x,4),np.round(y,4)),ha= 'left',va='bottom',fontsize=10)
plt.show()
#提取足校波动组合对应的权重,并转换成numpy数组
GMV_weights = np.array(RandomPortfolios.iloc[max_index,0:numstocks])
#计算GMV投资组合收益
StockReturns['Portfolio_GMV'] = stock_return.mul(GMV_weights,axis=1).sum(axis=1)
#输出风险最小投资组合的权重
print(GMV_weights)
#投资最优组合
#夏普最优组合的选择
#设置无风险回报率为0.03
risk_free = 0.03
#计算每项资产的夏普比率
RandomPortfolios['Sharpe'] = (RandomPortfolios.Returns - risk_free) / RandomPortfolios.Volatility
#绘制收益-标准差的散点图,并用颜色描绘夏普比率
plt.scatter(RandomPortfolios.Volatility,RandomPortfolios.Returns,c=RandomPortfolios.Sharpe)
plt.colorbar(label='Sharpe Ratio')
plt.show()
# 找到夏普比率最大数据对应的索引值
max_index = RandomPortfolios.Sharpe.idxmax()
# 在收益-风险散点图中突出夏普比率最大的点
RandomPortfolios.plot('Volatility', 'Returns', kind='scatter', alpha=0.3)
x = RandomPortfolios.loc[max_index,'Volatility']
y = RandomPortfolios.loc[max_index,'Returns']
plt.scatter(x, y, color='red')
#将该点坐标显示在图中并保留四位小数
plt.text(np.round(x,4),np.round(y,4),(np.round(x,4),np.round(y,4)),ha='left',va='bottom',fontsize=10)
plt.show()# 提取最大夏普比率组合对应的权重,并转化为numpy数组
MSR_weights = np.array(RandomPortfolios.iloc[max_index, 0:numstocks])
# 计算MSR组合的收益
StockReturns['Portfolio_MSR'] = stock_return.mul(MSR_weights, axis=1).sum(axis=1)
#输出夏普比率最大的投资组合的权重
print(MSR_weights)
# 找到夏普比率最大数据对应的索引值
max_index = RandomPortfolios.Sharpe.idxmax()
# 在收益-夏普散点图中突出夏普比率最大的点
RandomPortfolios.plot('Sharpe', 'Returns', kind='scatter', alpha=0.3)
x = RandomPortfolios.loc[max_index,'Sharpe']
y = RandomPortfolios.loc[max_index,'Returns']
plt.scatter(x, y, color='red')
#将该点坐标显示在图中并保留四位小数
plt.text(np.round(x,4),np.round(y,4),(np.round(x,4),np.round(y,4)),ha='left',va='bottom',fontsize=10)
plt.show()# 提取最大夏普比率组合对应的权重,并转化为numpy数组
MSR_weights = np.array(RandomPortfolios.iloc[max_index, 0:numstocks])
# 计算MSR组合的收益
StockReturns['Portfolio_MSR'] = stock_return.mul(MSR_weights, axis=1).sum(axis=1)
#输出夏普比率最大的投资组合的权重
print(MSR_weights)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/449558.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

并发编程(十六)——java7 深入并发包 ConcurrentHashMap 源码解析

以前写过介绍HashMap的文章,文中提到过HashMap在put的时候,插入的元素超过了容量(由负载因子决定)的范围就会触发扩容操作,就是rehash,这个会重新将原数组的内容重新hash到新的扩容数组中,在多线…

[边分治+线段树合并]「CTSC2018」暴力写挂

题目梗概 给出两棵1为根的树,求\(d[x]d[y]-d[lca(x,y)]-d[lca(x,y)]\)的最大值 解题思路 套路化简之后\((d[x]d[y]dis(x,y)-2*d[lca(x,y)])/2\) 第二棵树上的lca化不掉,所以考虑在第二棵上枚举lca 先说说这题的解法,边分树的合并. 边分和点分有什么区别,边分在合并类似\(d[x]d[…

HEVC/H265 文档获得

HEVC/H265文档是很重要的标准,因为代码有时由于效率问题而修改,这是最重要的参考: HEVC approved by ITU-T and ISO/IEC "Geneva, 25 January 2013 – A new video coding standard building on the PrimeTime Emmy award winning IT…

期权计算隐含波动率

牛顿迭代法 from scipy.stats import norm import numpy as np def bscall(S,K,r,sigma,t):d1(np.log(S/K)(r0.5*sigma**2)*t)/(sigma*np.sqrt(t))d2d1-sigma*np.sqrt(t)return S*norm.cdf(d1)-K*np.exp(-r*t)*norm.cdf(d2) def bsput(S,K,r,sigma,t):d1(np.log(S/K)(r0.5*sigm…

进击的二维码 | ArcBlock 课堂预告

ArcBlock Technical Learning Series 第十七期进击的二维码本周三,1 月 30 日下午 1:30 时 (美国太平洋时间 29日下午 21:30 时),由 ArcBloc 后端工程师孙博山 授课。复制代码二维码源于日本,如今世界各国都在使用。一张简单的二维…

期权数据计算

判断是否为调仓日 ef is_adjust_day(self, dom1):判断是否是每月的调仓日。 :params int dom: 每月第几个交易日进行调仓,缺省是第1个交易日。:return: 如果是调仓日,返回True,否则返回False。ret Falsetoday self.datetime.date()…

由Docker的MySQL官方镜像配置的容器无法启动问题解决办法(修改配置后无法启动)

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。 为了方便阅读,我在原文基础上加了一些批注,说明我自己的情况,用红色标示。 这篇文章记录了我在使用…

HEVC/H265 主要设计者谈HEVC/H265

Overview of the High Efficiency Video Coding (HEVC) Standard Gary J. Sullivan, Fellow, IEEE, Jens-Rainer Ohm, Member, IEEE, Woo-Jin Han, Member, IEEE, and Thomas Wiegand, Fellow, IEEE Gary J. Sullivan是H263&#xff…

阿里云 Aliplayer高级功能介绍(九):自动播放体验

基本介绍经常会碰到客户询问,为什么我设置了autoplay为true,但是没有自动播放,每次都要向客户解释这个是浏览器从用户体验角度考虑做的限制,客户会继续询问那我要怎么做? 针对这个问题Aliplayer也专们做过优化&#xf…

指数定投(行不行学习)

import tushare as ts import pandas as pd import numpy as np from scipy import stats import tushare as ts import matplotlib.pyplot as plt %matplotlib inline #正常显示画图时出现的中文和负号 from pylab import mpl mpl.rcParams[font.sans-serif][SimHei] mpl…

centOS安装python3.7.2

1.查看centos中自带的Python地址:which python(一般在 /usr/bin/python) 2.切换到python安装目录:cd /usr/bin 3.查看对应的Python版本指向:ls -l python* 4.创建一个空目录:mkdir /usr/local/python3 5.…

有进度条圆周率Π计算

圆周率π的计算 一、圆周率π的简介 圆周率的介绍圆周率用希腊字母 π(读作pi)表示,是一个常数(约等于3.141592654),是代表圆周长和直径的比值。它是一个即无限不循环小数,在日常生活中&#xf…

期权制作回测数据

将指定的档位的期权,指定阶段剩余到期日的期权数据合并,用于回测 import pandas as pd import numpy as np import akshare as ak pd.set_option("display.max_rows",None) pd.set_option("display.max_columns",None)nh_price ak…

HEVC/H265 HM10.0 分析(一)NALread.cpp

下面分析 NALread.cpp 函数和代码。 void read(InputNALUnit& nalu, vector<uint8_t>& nalUnitBuf) {/* perform anti-emulation prevention */TComInputBitstream *pcBitstream new TComInputBitstream(NULL);convertPayloadToRBSP(nalUnitBuf, (nalUnitBuf[0]…

Docker run 命令 参数说明

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 docker run &#xff1a;创建一个新的容器并运行一个命令 语法 docker run [OPTIONS] IMAGE [COMMAND] [ARG...][OPTIONS] IMAGE [COM…

【云周刊】第205期:阿里云重磅开源实时计算平台Blink,挑战计算领域的“珠峰”...

本期头条 阿里云重磅开源实时计算平台Blink&#xff0c;挑战计算领域的“珠峰” 信息爆炸的时代&#xff0c;智能推荐已经被应用到各类互联网产品中&#xff0c;但为千万级甚至亿级规模的用户实时做精准的推荐难度极高。这一难题已经被阿里攻克了&#xff1a;双11的第1分钟&…

凯特勒通道(backtrader)

import backtrader as bt import datetime import pandas as pd import matplotlib.pyplot as plt import backtrader.analyzers as btanalyzers#定义指标 class Ketler(bt.Indicator):params dict(ema20,atr 17)lines (expo,atr,upper,lower)plotinfo dict(subplot False)p…

MYSQL安装报错 -- 出现Failed to find valid data directory.

运行环境&#xff1a;windows10数据库版本&#xff1a;mysql.8.0.12安装方式&#xff1a;rpm包直接安装 问题描述&#xff1a;mysql初始化的时候找不到对应的数据库存储目录 报错代码&#xff1a; 2018-10-13T03:29:24.179826Z 0 [System] [MY-010116] [Server] D:\Program Fil…

Mysql 取用逗号分隔的字串的子串的方法:SUBSTRING_INDEX

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 有一张部门表&#xff1a;appbricks_department &#xff0c;有 id 字段和 rank_tree 字段。 rank_tree&#xff1a;记录的是当前部门的…

UCloud首尔机房整体热迁移是这样炼成的

2019独角兽企业重金招聘Python工程师标准>>> 2018年下半年&#xff0c;UCloud首尔数据中心因外部原因无法继续使用&#xff0c;需要在很短时间内将机房全部迁走。为了不影响用户现网业务&#xff0c;我们放弃了离线迁移方案&#xff0c;选择了非常有挑战的机房整体热…