python绘图练习——股票分析(二):风险分析与蒙特卡罗模拟
做完股票的基础分析后,接下来我们可以做一些简单的风险分析。
首先还是导入数据并进行简单的处理:
from __future__ import division
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt#import data
Tesla=pd.read_csv('Tesla_Stock.csv',index_col='Date')
Tesla.index=pd.to_datetime(Tesla.index)GM=pd.read_csv('GM_stock.csv',index_col='Date')
GM.index=pd.to_datetime(GM.index)Ford=pd.read_csv('Ford_Stock.csv',index_col='Date')
Ford.index=pd.to_datetime(Ford.index)#count daily return
GM['Return']=GM['Close'].pct_change(1)
GM=GM.dropna()
Tesla['Return']=Tesla['Close'].pct_change(1)
Tesla=Tesla.dropna()
Ford['Return']=Ford['Close'].pct_change(1)
Ford=Ford.dropna()#concatenate daily return of three stocks
ret_df=pd.concat([Tesla['Return'],GM['Return'],Ford['Return']],axis=1)
ret_df.columns=['Tesla','GM','Ford']
ret_df.head()
我们可以看下计算出的三只股票的日收益率:
接下来我们可以通过绘图描述每只股票风险与收益率的关系图:
area = np.pi*20
plt.scatter(ret_df.mean(), ret_df.std(),alpha = 0.5,s =area)
plt.xlabel('Expected returns')
plt.ylabel('Risk')# Label the scatter plots
for label, x, y in zip(ret_df.columns, ret_df.mean(), ret_df.std()):plt.annotate(label, xy = (x, y), xytext = (50, 50),textcoords = 'offset points', ha = 'right', va = 'bottom',arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3,rad=-0.3'))
这里使用了plt.annotate
对每个点进行标注,更多内容,可以查看相关的文档
输出如下:
从图中可以看出福特公司的股票风险最低,但同样收益率也较低,而特斯拉就属于高风险和高收益型股票了,从整张图明显的体现出了投资市场“高风险,高收益”的基本法则。
蒙特卡罗模拟法
接下来,我们通过蒙特卡罗模拟法来模拟计算特斯拉公司股票的风险价值。
风险价值(VaR):即在市场正常波动的条件下,在一定概率水平α%下,某一金融资产或金融资产组合的VaR是在未来特定一段时间Δt内最大可能损失。
现在我们使用蒙特卡罗模拟法进行风险价值的估算。简单来说,蒙特卡罗模拟法即运用历史数据对未来进行多次模拟,以求得未来股价结果的概率分布。蒙特卡罗模拟法的公式如下:
\frac{ΔS}{S}=μΔt+σ ε\sqrt{Δt}
其中S为股票的价格,μ为期望收益率,Δt为时间间隔,σ为股票风险,ε为随机变量。将S移项可得:
ΔS=S(μΔt+σ ε\sqrt{Δt}),
可以看出,蒙特卡罗模拟法认为股票的价格波动可以分为两部分,第一部分为drift,即股票会根据收益率波动,第二部分为shock,即随机波动。如下图:
这样,通过历史数据求得股票的平均收益率与风险,我们便可以通过蒙特卡罗模拟法对股票未来走势进行模拟。关于蒙特卡罗模拟法更多的介绍可以查看 How to use Monte Carlo simulation with GBM。接下来,我们通过python对特斯拉接下来一年的股价进行预测。
首先设置收益率与风险等参数。
'''
Monte Carlo method
'''
# Set up our time horizon
days = 365# Now our delta
dt = 1/days# Now let's grab our mu (drift) from the expected return data we got for AAPL
mu = ret_df.loc['2016-01-01':'2016-12-30'].mean()['Tesla']# Now let's grab the volatility of the stock from the std() of the average return
sigma = ret_df.std()['Tesla']
接下来定义蒙特卡罗函数:
def stock_monte_carlo(start_price,days,mu,sigma):''' This function takes in starting stock price, days of simulation,mu,sigma, and returns simulated price array'''# Define a price arrayprice = np.zeros(days)price[0] = start_price# Schok and Driftshock = np.zeros(days)drift = np.zeros(days)# Run price array for number of daysfor x in xrange(1,days):# Calculate Schockshock[x] = np.random.normal(loc=mu * dt, scale=sigma * np.sqrt(dt))# Calculate Driftdrift[x] = mu * dt# Calculate Priceprice[x] = price[x-1] + (price[x-1] * (drift[x] + shock[x]))return price
定义完蒙特卡罗函数,接下来便可以开始模拟了,首先我们模拟100次观察一下效果:
# Get start price
start_price = Tesla['Close'][-1]for run in xrange(100):plt.plot(stock_monte_carlo(start_price,days,mu,sigma))
plt.xlabel("Days")
plt.ylabel("Price")
plt.title('Monte Carlo Analysis for Tesla')
可以看到,每一次模拟所得到股价走势都是不同的,但是大部分集中在中间。接下来我们进行10000次模拟并计算风险价值:
# Set a large numebr of runs
runs = 10000# Create an empty matrix to hold the end price data
simulations = np.zeros(runs)# Set the print options of numpy to only display 0-5 points from an array to suppress output
np.set_printoptions(threshold=5)for run in xrange(runs): # Set the simulation data point as the last stock price for that runsimulations[run] = stock_monte_carlo(start_price,days,mu,sigma)[days-1];
最后,我们定义置信水平为99%,尝试绘制股票最终价格的分布图:
#define q as the 1% empirical qunatile, this basically means that 99% of the values should fall between here
q = np.percentile(simulations, 1)# plot the distribution of the end prices
plt.hist(simulations,bins=200)# Using plt.figtext to fill in some additional information onto the plot# Starting Price
plt.figtext(0.6, 0.8, s="Start price: $%.2f" %start_price)
# Mean ending price
plt.figtext(0.6, 0.7, "Mean final price: $%.2f" % simulations.mean())# Variance of the price (within 99% confidence interval)
plt.figtext(0.6, 0.6, "VaR(0.99): $%.2f" % (start_price - q,))# Display 1% quantile
plt.figtext(0.15, 0.6, "q(0.99): $%.2f" % q)# Plot a line at the 1% quantile result
plt.axvline(x=q, linewidth=4, color='r')# Title
plt.title(u"Final price distribution for Tesla Stock after %s days" % days, weight='bold');
即在99%的置信水平下,特斯拉股票一年后的价格不会低于198.51,其风险价值为15.18,而其平均价格与其初始价格基本一致。
python绘图练习——股票分析(二):风险分析与蒙特卡罗模拟相关推荐
- Excel股票分析工具_量化策略模拟
在Excel中对量化策略进行模拟 根据优选算法,每日对所有股票数据进行监控和选择: 可以根据"买入日期"列判断是否当日选出股票: 后端采用VBA通过API获取数据并创建前台分析链接 ...
- day32 Python与金融量化分析(二)
第一部分:金融与量化投资 股票: 股票是股份公司发给出资人的一种凭证,股票的持有者就是股份公司的股东. 股票的面值与市值 面值表示票面金额 市值表示市场价值 上市/IPO: 企业通过证券交易所公开向社 ...
- 【时间之外】10分钟搞懂Python+Tushare+Excel股票分析
Python+Tushare+Excel 场景和工具 不想996就多赚钱(1分钟) 需求简介(1分钟) Tushare简介(1分钟) 思路分析 三行代码取数据(2分钟) 最麻烦的一步:保存成excel ...
- python爬取股票大单历史记录_python爬取股票实时数据,python爬虫与股票分析
内容导航: Q1:怎么学python爬取财经信息 本程序使用Python 2.7.6编写,扩展了Python自带的HTMLParser,自动根据预设的股票代码列表,从Yahoo Finance抓取列表 ...
- Python数据分析之股票分析
股票分析 使用tushare包获取某股票的历史行情数据 输出该股票所有收盘比开盘上涨3%以上的日期 输出该股票所有开盘比前日收盘跌幅超过2%的日期 假如从2010年1月1日开始,每月第一个交易日买入1 ...
- python画图包_「Python量化」股票分析入门
目前,获取股票数据的渠道有很多,而且基本上是免费的,比如,行情软件有同花顺.东方财富等,门户网站有新浪财经.腾讯财经.和讯网等.Python也有不少免费的开源api可以获取交易行情数据,如pandas ...
- python大数据股票分析
import pandas as pd import numpy as np # 读取Excel文件,pd.read_excel(r'文件位置\文件名称.xlsx') hq = pd.read_exc ...
- python mysql股票分析_一颗韭菜的自我修养:用Python分析下股市,练练手
股市跌宕起伏.7 月初 A 股飙升,股票瞬间成为大家的热门讨论话题,「现在入场还来得及吗?」几乎成为新的问候语. 然而,经历了连续近 10 个交易日的快牛行情后,上证指数上涨势头放缓.这是牛市,还是熊 ...
- Python 股票分析快速入门
Python 股票分析快速入门 这段时间股市又开始火爆起来了,隐约这透着点大牛市气息,多年不用的股票账户也找回来了.然后就想着用python做下股票分析,尝试制作自己的分析脚本,本篇教程是自己的一些笔 ...
最新文章
- linux awk 用一个或多个空格做分隔符
- thinkpad触控笔怎么用_电容笔怎么用,如何选择一支电容笔来提升生产力呢?
- 自定义LeNet5,开启你的炼丹之路
- SAP 2019 TechEd Key Note解读:云时代下SAP从业人员如何做二次开发?
- 好程序员前端分享使用JS开发简单的音乐播放器
- 开源应用诊断利器 Arthas GitHub Star 突破两万
- 使用selenium框架的Python爬虫被检测到的 解决方法
- 烟花程序c语言,C语言烟花程序
- 《深入理解Android:卷III A》一一第3章 深入理解AudioService
- windows下vbs脚本添加网络打印机
- Java开发设计——UML类图
- VALSE学习(四):注意力机制-Attention Network
- mysql结构改写为hbase表_根据mysql表中字段创建hbase表
- 使用PacketSifter从pcap中筛选有价值的信息
- 华为OSPF中silent-interface语句介绍
- HTML期末作业,仿b站视频项目模板(HTML+CSS+JS)
- BIM标准丨深圳市住房和建设局关于印发《房屋建筑工程招标投标建筑信息模型技术应用标准》
- delphi第三方组件总述
- CF 1260 D 题解
- 重装win10提示在EFI系统上,Windows只能安装到GPT磁盘