cuốn sách gpt4 ai đã làm

Python 迭代?

In lại Tác giả: Walker 123 更新时间:2023-11-28 17:28:02 29 4
mua khóa gpt4 Nike

我正在尝试在 Python 中运行模拟,由此我绘制了一个数组的随机游走图,给定了两个变量参数的设定水平。

但是,我遇到了一个问题,我不确定如何迭代以便生成 250 个不同的随机数以插入公式。例如我已经定义了一个随机数 x,但由于它只是一个随机数,Python 将生成一条直线图,因为该公式只考虑了一个变量。

对于 250 个数据点,程序需要生成 250 个介于 0 和 1 之间的随机数,以便能够对数据运行随机过程。但是,我不确定从这里到哪里去,如果有任何建议,我将不胜感激。

câu trả lời hay nhất

新:鉴于我对波动率的理解是正确的,它只是平均返回的标准差,对吗?然后,您需要做的就是获得一个均值 mu 和标准差 v 的正态分布随机数。正如 Severin 指出的那样,numpy 中有一个函数可以做到这一点,即 numpy.random.normal(loc,scale) TRONG loc=muscale= v。请参见下面的示例。我试图明确编码每个步骤。一旦您熟悉了 numpy/python,您就可以在 1 或 2 行中完成大部分工作。

import numpy as np
import matplotlib.pylab as plt

# Initial parameters:
#-------------------
# mean return per step
mu = 0.1
# volatility
v = 0.06
# starting stock price
s0 = 500

# Looks like compound annual growth rate, but isn't that exactly what you want
# to determine from the simulation?
k = mu-(v**2)/2

# Iterate random walk, assuming no history within the changes.
stock_price_changes = []
for t in xrange(250):
rnd = np.random.normal(loc=mu,scale=v)
stock_price_changes.append(rnd)

# Add up all stock changes and add the initial stock price
stock_total = np.cumsum(stock_price_changes) + s0

# Plot the whole thing
plt.figure(figsize=(7,7),edgecolor='k',facecolor='w')
plt.plot(np.arange(250),stock_total,c='k')
plt.xlabel('Trading Days')
plt.ylabel('Price')
plt.tight_layout()
plt.show()

旧:也许我没有真正正确地理解这个问题,但你不想编写一个“真正的”随机游走代码吧?它只是为您的指数模型添加随机性?我想最简单的方法是使用您已经导入的 numpy。您可以像这样压缩随机数生成:

...
k = mu-(v**2)/2

t=np.arange(0,250)
s1=s0*np.exp(k*t/250) #+(v*datapoints)*np.sqrt(t/250)

rndScaling = 1.0
s1 += rndScaling * 2.0 * (np.random.rand(250) - 0.5)
...

2.0 * (np.random.rand(250) - 0.5) 表达式生成一个包含 250 个介于 -1 和 +1 之间的随机变量的数组。现在,如果您想要指数模型周围的振幅为 2.0 的“随机性”,您只需将 rndScale 更改为 2.0。

关于Python 迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36986811/

29 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress