python - 如何模拟受新闻影响的股价
问题描述
我正在编写一个生成模拟股票市场价格的函数,部分代码包含了几天内新闻(例如政治动荡、自然灾害)对股价的影响。
# 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()
解决方案
看起来p
参数需要一个与选择列表的长度相匹配的长度。也就是说,您需要与每个选择相关联的机会。尝试:
news_today = rng.choice([0,1], p=[chance, 1 - chance])
推荐阅读
- android - 如何仅为我的库模块/包获取包特定的崩溃报告/数据(通过 gradle 依赖项在某些应用程序中实现)
- react-native - 如何在本机反应中以 hh:mm:ss 格式获取两个日期之间的时间?
- excel - Excel 公式在两列中查找多个条件
- python - 无法将对象数据类型转换为日期时间格式
- javascript - WEBPACK - 如何从 javascript 导入中获取单个构建文件
- android - 当俯仰接近 90 度时,为什么滚动是不可预测的?
- node.js - 节点猫鼬不插入
- python - 从 nse 网站抓取即期汇率
- python - Python 最佳实践:如何给模块起别名
- r - 如何在R中绘图的左上角添加绘图名称?