【问题标题】:How to simulate stock prices with impact of news如何模拟受新闻影响的股价
【发布时间】:2020-11-05 16:07:16
【问题描述】:

我正在编写一个生成模拟股票市场价格的函数,部分代码包含了几天内新闻(例如政治动荡、自然灾害)对股价的影响。

# Set up the default_rng from Numpy
rng = np.random.default_rng()

def news(chance, volatility):
    '''
    Simulate the impact of news on stock prices with %chance
    '''
    # Choose whether there's news today
    news_today = rng.choice([0,1], p=chance)
    if news_today:
        # Calculate m and drift
        m = rng.normal(0,0.3)
        drift = m * volatility
        # Randomly choose the duration
        duration = rng.integers(7,7*12)
        final = np.zeros(duration)
        for i in range(duration):
            final[i] = drift
        return final
    else:
        return np.zeros(duration)

我收到了几条错误消息,其中之一是:

news_today = rng.choice([0,1], p=chance)
TypeError: object of type 'int' has no len()

【问题讨论】:

    标签: python function numpy random simulation


    【解决方案1】:

    看起来p 参数需要一个与选项列表长度相匹配的长度。也就是说,您需要与每个选择相关联的机会。试试:

    news_today = rng.choice([0,1], p=[chance, 1 - chance])
    

    【讨论】:

    • 在实现这个之后,我在return np.zeros(duration)UnboundLocalError: local variable 'duration' referenced before assignment这一行收到一条错误消息
    • @codemachine98 通过将持续时间从函数中取出并将其置于其上方,从而使持续时间成为全局变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多