Python

时间:2016-01-06 21:07:51

标签: python while-loop finance montecarlo

我尝试对股票投资进行简单的蒙特卡罗模拟,其中包括一些投资价值,投资期(以年为单位)以及股票共同基金的均值和标准。我还想为股市崩盘实施一个简单的方法 - 我这样做是为了每当新的计算值比前一个高出40%时,新值应该下降90% - 就像某种崩溃一样。我设法让它工作,这是代码,但我认为它不能正常工作。问题可能隐藏在我调用之前的值的地方。你能尝试让它运作吗?

import matplotlib
import matplotlib.pyplot as plt
import random
import numpy as np

mean = 7.0 #mean for stock mutual fund
std = 19.0 #std for stock mutual fund

def investment_return(): #random normal distribution of returns
    investment_return = (np.random.normal(mean,std))/100
    return investment_return

def investor(A, B):
    investment_value = A
    investment_period = B

    wX = []
    vY = []

    x = 1

    while x <= investment_period:
        value = A + A*investment_return()
        if value > value * 1.4: #if new value is 1.4x bigger than previous
            A = value * 0.1 #than make -90 percent adjustment
        else:
            A = value #else use new value
        wX.append(x)
        vY.append(value)
        x += 1
    #print(value)

    plt.plot(wX,vY)

i = 0
while i < 10: #number of investors
    investor(100,20) #starting value and investment period
    i += 1

plt.ylabel('Investment_value')
plt.xlabel('Investment_period')
plt.show()

1 个答案:

答案 0 :(得分:2)

好吧,我尽力解释你的意思。它帮助您为以下工作提供了坚实的基础:)。

好的,我们走了:显然,凯文的评论value > value * 1.4永远不会评估为True是一个坚实的评论。我确实重命名了一些变量(例如,通常我们将股票比较为indices,因此我将A重命名为index)。时间通常称为t,而不是xwhile循环有点古怪,所以我摆脱了那些。

import matplotlib.pyplot as plt
import numpy as np


mean = 7.0
std = 19.0


def investment_return():
    return (np.random.normal(mean, std)) / 100


def investor(index, period):
    wT = []
    vY = []

    for t in range(1, period + 1):
        new_index = index + index * investment_return()
        if new_index > index * 1.4:
            index = new_index * 0.1
        else:
            index = new_index
        wT.append(t)
        vY.append(index)
    return wT, vY


for i in range(0, 10):
    wT, vY = investor(100, 20)

    # do something with your data

    plt.plot(wT, vY)

plt.ylabel('Investment_value')
plt.xlabel('Investment_period')
plt.show()

这有时会发生股票崩盘,可以清楚地看到(请记住,这需要您从>40发行版中对N(7,19)进行抽样:这不应该发生在95%以上{在所有情况下{1}}。