蒙特卡洛方法生成随机数

金融, 机器学习 (Finance, Machine Learning)

In this article, I will focus on how to create a procedural stock from nowhere, that at every iteration will randomly move up or down. While you may think that creating a random stock (or a sequence of them) is useless, because it does not reflect any real scenario, it is a tool that can prove itself useful for technical analysis or stressing any algo/model before even deploying it into the market.

在本文中,我将重点介绍如何从无处创建过程库存,该过程库存在每次迭代时都会随机地上下移动。 尽管您可能认为创建随机库存(或它们的序列)是没有用的,因为它不能反映任何实际情况,但它是一种工具,可以证明自己对技术分析或在部署任何算法/模型之前都非常有用进入市场。

股票走势背后的数学 (The math behind stock movements)

According to the random walk theory, stock movements (so-called returns) appear to be completely random. But this does not simply end the problem. If the issue is randomness, I could simply start from a price of 1000 on day 0, generating random numbers between -100 and 100 every day, adding them to the price of the previous day. This idea of randomness is not wrong, but too simple.

根据随机游走理论,股票走势(所谓的收益)似乎是完全随机的。 但这并不能简单地解决问题。 如果问题是随机性,我可以简单地从第0天的价格1000开始,每天生成介于-100和100之间的随机数,并将它们添加到前一天的价格中。 这种随机性的想法没有错,但是太简单了。

The idea is to simulate a stock movement randomly, but as closer to reality as possible. Therefore, choosing a random number to add to every iteration is a sloppy way of representing reality.

这个想法是随机模拟股票走势,但要尽可能接近现实。 因此,选择一个随机数添加到每个迭代中是代表现实的草率方法。

股票退货 (Stock Returns)

Movement of stock prices between iterations (in easy words, the way a stock moves from day 0 to day 1, and then from day 1 to day 2…) are measured by using a specific measure of value: returns.

两次迭代之间的股价变动(简单地说,就是股票从第0天到第1天,然后从第1天到第2天……的移动方式)是通过使用特定的价值度量来衡量的:回报。

The simplest way to calculate stock returns is by calculating the percentage change between one iteration and the next, as you can see from the picture. The only thing I need to do to simulate the movement of a stock is creating a sequence of iterations where the stock price moves thanks to the simulated return. This is how the price changes over time, I will not affect it directly.

从图中可以看出,计算股票收益的最简单方法是计算一次迭代与下一次迭代之间的百分比变化。 我唯一需要模拟的是模拟股票的波动,就是创建一系列的迭代,其中由于模拟的收益,股票的价格会波动。 这是价格随时间变化的方式,我不会直接影响它。

例 (Example)

For example, If I wanted to simulate the picture above, I know that my stock price starts at 1000 on day 0. I will generate the first return (+.03) and use it to increase the stock price on day 1:

例如,如果我想模拟上面的图片,我知道我的股价在第0天从1000开始。我将生成第一个收益(+.03),并用它来增加第1天的股价:

#day_1 stock price1000*(1+0.03) = 1030

For the price of day 2, I will generate the return of -.0048:

对于第2天的价格,我将生成-.0048的回报:

#day_2 stock price1030*(1+-0.0048) = 1025

产生随机回报 (Generating random returns)

This is where it gets interesting. To generate returns randomly, you will need to apply the knowledge of PDF (probability distribution functions). Instead of thinking about the returns like the roll of a dice, where a stock movement of 2% can have an equivalent probability of a stock movement of 10% (uniform distribution), I can give my distribution the shape I want. By default, stock returns will follow a normal distribution.

这就是它变得有趣的地方。 要随机产生回报,您将需要应用PDF的知识(概率分布函数)。 我不用考虑骰子掷骰的回报,因为股票变动为2%时,股票变动的概率为10%(均匀分布),我可以给我分配自己想要的形状。 默认情况下,股票收益将遵循正态分布。

Plotting of the returns of many different stocks
绘制许多不同股票的收益

***Notice that stock returns won’t only follow a normal distribution, but can also follow different patterns, such as the Laplace distribution or skewed normal distributions. If you analyze any stock and plug in the returns in a histogram, the most common form you will find is a normal distribution.

***请注意,股票收益不仅会遵循正态分布,而且还会遵循不同的模式,例如拉普拉斯分布或偏态正态分布。 如果您分析任何股票并在直方图中插入收益,则最常见的形式是正态分布。

以正态分布生成数字 (Generating numbers in a normal distribution)

If you are unfamiliar with the math process, once you have a distribution, you will need to use different tools to generate random numbers:

如果您不熟悉数学过程,则在获得分布后,将需要使用其他工具来生成随机数:

  1. Building the PDF (Probability Distribution Function), in this case, a normal distribution.在这种情况下,构建PDF(概率分布函数)为正态分布。
  2. From the PDF, build the CDF (Cumulative Distribution Function)从PDF构建CDF(累积分布函数)
  3. From the CDF, build the ICDF (Inverse Cumulative Distribution Function): only by using the ICDF, you can generate random numbers.从CDF中构建ICDF(逆累积分布函数):仅通过使用ICDF,您可以生成随机数。

For now, I will explain the math process behind generating random returns. Later on, I will also print the code.

现在,我将解释生成随机收益背后的数学过程。 稍后,我还将打印代码。

1.产生股票收益率的正态分布 (1. Generating the Normal Distribution of Stock Returns)

To build the Probability Distribution Function (PDF) which follows the shape of a normal distribution I will need:

要建立遵循正态分布形状的概率分布函数(PDF),我需要:

  • Mean意思
  • Standard Deviation (Sigma)标准差(Sigma)

The mean indicates the center of the distribution, the peak if you wish. In financial mathematics, if the mean is positive (let’s say +0.02), there is a higher chance of all returns to be positive, the opposite if the mean is lower than 0.

平均值表示分布的中心,如果需要,则表示峰值。 在金融数学中,如果均值是正数(例如+0.02),则所有回报率都为正数的可能性更高,如果均值小于0,则相反。

The standard deviation indicates the level of risk. The lower the Sigma, the lower the number of high fluctuations. For example, if you look at the graph above, it has a Sigma of about .03. This means that high fluctuations in price such as .05 or .07 or higher do not happen frequently. On the opposite, you are likely going to find a huge number of fluctuations which will be lower than .03. If the price of a day is only likely to move 3%, then your stock is not volatile, and the risk diminishes.

标准差表示风险级别。 Sigma越低,高波动的数量越少。 例如,如果您查看上面的图形,它的Sigma约为.03。 这意味着价格波动不大,例如.05或.07或更高。 相反,您可能会发现大量的波动,这些波动将小于.03。 如果一天的价格仅可能波动3%,则您的股票不会波动,风险会降低。

I want to create a PDF with a mean of 0 and a Sigma of .02. These numbers indicate a stock with no higher chances of going up or down, and very low volatility: a safe investment with low returns over time.

我想创建一个平均值为0且Sigma为.02的PDF。 这些数字表明,股票涨跌的可能性不大,而且波动性非常低:这是一种安全的投资,随着时间的推移收益率低。

2.生成累积分布函数 (2. Generating the Cumulative Distribution Function)

The transition from PDF to CDF
从PDF到CDF的过渡

While the output of the PDF is not useful to us, the cumulative distribution function shows the % of the population (essentially the probability that a random pick in the distribution will lead there) that is smaller than one value.

尽管PDF的输出对我们没有用,但累积分布函数显示的总体百分比(基本上是分布中的随机选择将导致该百分比)小于一个值。

For example, the probability that one random return is ≤ 0 is 50%. The same, the probability of having a value > 0 is 50%. The input of the function is the return of the stock, its output is the probability.

例如,一个随机回报≤0的概率为50%。 同样,值> 0的概率为50%。 函数的输入是股票的回报,其输出是概率。

3.生成逆累积分布函数 (3. Generating the Inverse Cumulative Distribution Function)

From CDF to ICDF
从CDF到ICDF

By using CDF we can only input returns. Instead, by using the inverse of the CDF, therefore the ICDF, we are inverting input and output. I can input any number between 0 and 1, and as a result, I will have the equivalent amount in the population. In a few words, to generate random returns I will simply need to generate a bunch of random values between 0 and 1 and I will obtain the corresponding values.

通过使用CDF,我们只能输入收益。 相反,通过使用CDF的逆函数(即ICDF),我们可以反转输入和输出。 我可以输入0到1之间的任何数字,结果,我的人口数量将相等。 简而言之,要生成随机回报,我只需要生成一堆介于0和1之间的随机值,我就可以获得相应的值。

By following this process I will make sure that the generated returns follow the correct distribution, and that a return of 2% will have a greater chance of happening than a 5% movement (which for a regular stock is quite rare).

通过执行此过程,我将确保生成的收益遵循正确的分布,并且2%的收益比5%的波动更有可能发生(对于常规股票,这种情况很少见)。

整个算法 (Entire algorithm)

I will now use an algorithm to generate as many simulated stocks I want. I can pass as variables the length of each stock (in days) and the distribution parameters (trend and volatility).

现在,我将使用一种算法来生成所需的任意数量的模拟股票。 我可以将每种股票的长度(以天为单位)和分布参数(趋势和波动率)作为变量传递。

from scipy.stats import skewnormimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt

创建主要功能 (Creating the main function)

def simulate_stock(initial_price, drift, volatility, trend, days):

PDF格式 (PDF)

def create_pdf(sd, mean, alfa):    #invertire il segno di alfa    x = skewnorm.rvs(alfa, size=1000000)     def calc(k, sd, mean):      return (k*sd)+mean    x = calc(x, sd, mean) #standard distribution

国际发展基金 (ICDF)

    #pick one random number from the distribution    #formally I would use icdf, but I just have to pick randomly from the 1000000 samples    #np.random.choice(x)    return x

建立一个空的DataFrame (Building an empty DataFrame)

def create_empty_df(days):    #creare un empty DataFrame con le date    empty = pd.Series(        pd.date_range("2019-01-01", periods=days, freq="D")    )    empty = pd.DataFrame(empty)    #si tagliano ore, minuti, secondi    empty#si tagliano ore, minuti, secondi    empty.index = [str(x)[0:empty.shape[0]] for x in list(empty.pop(0))]    empty#final dataset con values    stock = pd.DataFrame([x for x in range(0, empty.shape[0])])    stock.index = empty.index    return stock

填充数据框 (Filling the DataFrame)

#skeleton  stock = create_empty_df(days)#initial price  stock[0][0] = initial_price#create entire stock DataFramex = create_pdf(volatility, drift, trend)  for _ in range(1, stock.shape[0]):    stock.iloc[_] = stock.iloc[_-1]*(1+np.random.choice(x))return stock

绘制股票 (Graphing Stocks)

def graph_stocks(stock):  #graph all stocks  plt.figure(figsize=(28, 14))  for c in stock.columns.values:    #print(c)    fig = plt.plot(stock.index, stock[c], lw=1, alpha=1)  #plt.legend(loc='upper left', fontsize=12)  #plt.ylabel('price in $')#remove axis labels  plt.gca().axes.get_yaxis().set_visible(False)

产生多只股票 (Generating multiple stocks)

#create multiple stocksstock_list = list()column_name = list()#creating a benchmark stockcolumn_name.append('benchmark')stock_list.append(simulate_stock(1000, 0, 0.0, 0, 100))n_iter = 1n_days = 100for _ in range(n_iter):  #naming the stocks  text = 'stock, '  column_name.append(text + str(_))#creating the simulated stock  stock_list.append(simulate_stock(1000, 0.00, 0.02, 0, n_days))#join the stocks togetherstock = pd.concat([x for x in stock_list], axis=1)stock.columns = column_namestock

图形结果 (Graphing results)

graph_stocks(stock)

Graph of the Benchmark + Randomly Generated Stock, 0
基准图+随机生成的股票,0

导出数据框 (Exporting the DataFrame)

After you have created several random stocks (as many as you wish), you can export the result in a .csv file.

创建几只随机库存(任意数量)后,可以将结果导出到.csv文件中。

stock.to_csv('stock.csv')

100 simulated Stocks using different level of volatility
100种使用不同波动率的模拟股票

翻译自: https://medium.com/towards-artificial-intelligence/random-stock-generator-monte-carlo-simulations-in-finance-b9951a174271

蒙特卡洛方法生成随机数


http://www.taodudu.cc/news/show-5760376.html

相关文章:

  • 动态规划(七):买卖股票发大财
  • python均线选股_GitHub - pkujf/Wind_Python: 量化开发 多因子选股模型
  • 【wencai】一文学会通过wencai包访问同花顺i问财实现AI选股(已修复链接报错问题,并扩展函数功能,修改后源代码亲测可用)
  • [AHK]爬取i问财主动买入前100股票
  • *Directx中应用高度图(转)
  • 基于高度图的三维地形生成算法入门篇 —— 均匀网格地形生成算法
  • image加载图片 ui unity_关于Unity中UI中的Image节点以及它的Image组件
  • C++多态及重载(overload),覆盖(override),隐藏(hide)的区别
  • 一文读懂Java语言方法的重写(覆盖、Override)
  • C++重载(overload)、重写(overwrite,也称隐藏)、覆盖(override)
  • 身份证号码升位
  • 前缀和习题
  • 构建前缀树
  • pro、pre、test、dev环境区别
  • LeetCode -前缀和专题
  • 前缀树的设计与实现
  • 前缀平均值
  • 前缀和专题学习
  • 【重点】前缀树
  • php怎么修改表前缀,php如何设置表前缀
  • C语言基础之操作符详解
  • System Verilog 流操作符
  • 一文让你彻底掌握操作符(超详细教程)
  • Kotlin 协程Flow主要操作符(一)
  • 集合类型的操作符(共10个)
  • c++ 操作符大全-算术操作符、关系操作符、逻辑操作符、位操作符、自增自减操作符、赋值操作符、条件操作符、逗号操作符、操作符优先级
  • JavaScript操作符
  • 操作符(一)(算数操作符,位移操作符,位操作符)
  • new 操作符具体干了什么
  • C语言操作符汇总

蒙特卡洛方法生成随机数_随机股票生成器—财务方面的蒙特卡洛模拟相关推荐

  1. python随机生成列表_随机词生成器-Python

    所以我基本上是在一个项目中,计算机从单词列表中提取一个单词,然后为用户弄乱它. 只有一个问题:我不想继续在列表中写很多单词,所以我想知道是否有一种方法可以导入很多随机单词,所以即使我也不知道它是什么, ...

  2. Java生成随机数并随机输出不重复的值

    一个小Demo,网上有很多类似的代码,测试了一下网上的代码为了让随机输出值不重复,重复循环达到目的的效果,但循环次数过多严重影响性能. 通过ArrayList的remove方法实现了生成随机数并随机输 ...

  3. Linux Shell 生成随机数和随机字符串

    日常生活中,会经常用到随机数,使用场景非常广泛,例如买彩票.丢骰子.抽签.年会抽奖等. Shell 下如何生成随机数呢,米扑博客特意写了本文,总结 Linux Shell 产生随机数的多种方法. 本文 ...

  4. 学习使用js的 random() 方法生成随机数

    学习使用js的 random方法生成随机数 生成随机数1-100 Math.floor用法 Math.random()方法 生成随机数1-100 <!DOCTYPE html> <h ...

  5. R语言使用random包生成随机数或者随机字符串实战:randomNumbers函数创建随机整数的数据集(包含重复项)、randomSequence函数创建不含重复项的随机序列数据集、创建随机字符串

    R语言使用random包生成随机数或者随机字符串实战:randomNumbers函数创建随机整数的数据集(包含重复项).randomSequence函数创建不含重复项的随机序列数据集.创建随机字符串 ...

  6. python随机生成字符串_python生成随机数、随机字符串

    python生成随机数.随机字符串 import random import string # 随机整数: print random.randint(1,50) # 随机选取0到100间的偶数: pr ...

  7. python 随机字符串_python生成随机数、随机字符串

    python生成随机数.随机字符串 import random import string # 随机整数: print random.randint(1,50) # 随机选取0到100间的偶数: pr ...

  8. python生成10个随机数字符串_python生成随机数、随机字符串

    python生成随机数.随机字符串 import random import string # 随机整数: print random.randint(1,50) # 随机选取0到100间的偶数: pr ...

  9. 蒙特卡洛方法生成的电动汽车充电需求曲线 matlab平台建模

    蒙特卡洛方法生成的电动汽车充电需求曲线 matlab平台建模 ID:6919672622070241

最新文章

  1. 华为正式宣布养猪,网友沸腾:支持华为自救!
  2. 【60岁老人年审】老来网app养老保险年审的好伙伴【本地年审】【异地年审】【不参加年审无法领取养老保险金】...
  3. 用java的io做一个代码计数器,如何制作Java页面计数器_java
  4. Py之textrank4zh:textrank4zh的简介、安装、使用方法之详细攻略
  5. 签名程序集密钥文件路径
  6. Web开发如何实现Tomcat等服务器热部署不用重启
  7. 设计灵感|如何让你的海报更具现代感?
  8. ppt转html5 带动画_这组PPT设计,真的太漂亮了!
  9. 还在用tm?你OUT啦!
  10. 通信基站能耗综合管理系统
  11. AutoCAD2012从入门到精通中文视频教程 第41课 建筑绘图1(个人收藏)
  12. UnixC的第十三天
  13. tomcat session过期时间的设置
  14. java 偏向锁的撤销_源码解析-偏向锁撤销流程解读
  15. 由Yardi赞助的报告披露亚太房地产科技投资详情
  16. 基于腾讯地图定位组件实现周边公用厕所远近排序分布图
  17. 2.002 tensorflow做矩阵乘法
  18. 梦幻柔焦(奥顿效果)
  19. 参考行标对云效以及LinKE的“持续交付”及“敏捷开发管理”能力打了下分,大家看肿么样?
  20. 重新做计算机老师的说说,说说我们电脑班老师 ── 刁元清

热门文章

  1. 华为智能门锁 / Pro 评测
  2. Linux内存管理机制(最透彻的一篇)
  3. 栅格化布局的简单示例
  4. 原码、反码、补码运算规则
  5. 抖音短视频实操:抖音热门视频的分类特点,如何选择视频内容并创作(下)
  6. mongodb查询排序
  7. 白杨SEO:公众号、小程序微信服务搜索怎么做?搜一搜服务搜索排名规则解析
  8. Docker学习和安装
  9. VBA中 usedrange和currentregion区别
  10. 由国内的游戏软件的竞争,想到的