在今天的帖子中,我将提供另一个示例,展示numba如何加快数值模拟。我将该模块应用于股票价格随机游走的蒙特卡罗模拟。这是一个流行的蒙特卡罗模拟示例,我在几年前的博客文章中也提供了这个示例。
在 Python 中使用 numba 进行蒙特卡罗模拟
在下面的代码段中,我导入了相关模块和模块的一部分。正如我在之前的一篇文章中指出的那样,例如,numba与numpy的效果很好,但与pandas的效果不佳。我实现了价格随机游走蒙特卡罗模拟的两个版本。两种模拟都重复 n 次随机游走,持续时间为 365 天。每天的价格变动按照具有指定的平均每日收益和指定的每日收益标准差的随机正态分布随机分布。
import numpy as np
from matplotlib import pyplot as plt
import random
import time
from numba import njit
def random_walker(n: int, length: int) -> np.ndarray:
arr = np.zeros((n, length), dtype = float)
for i in range(n):
idx = 100
for j in range(length):
idx += idx*random.gauss(0.00015, 0.02)
arr[i, j] = idx
return arr
@njit
def nb_random_walker(n: int, length: int) -> np.ndarray:
arr = np.zeros((n, length), dtype = float)
for i in range(n):
idx = 100
for j in range(length):
idx += idx*random.gauss(0.00015, 0.02)
arr[i, j] = idx
return arr
我现在一个接一个地执行随机模拟运行,并计算两次运行的模拟持续时间。您可以在下面的代码中看到这一点。
# --- monte carlo run without numba ------------------
starttime = time.time()
arr = random_walker(10000, 365)
endtime = time.time()
print("monte carlo random walk without NUMBA: ")
print(endtime-starttime)
# --- monte carlo run with numba --------------------
starttime = time.time()
arr = nb_random_walker(10000, 365)
endtime = time.time()
print("monte carlo random walk with NUMBA: ")
print(endtime-starttime)
输出如下:
monte carlo random walk without NUMBA:
1.9181511402130127
monte carlo random walk with NUMBA:
0.6535243988037109
在这种情况下, numba将 monte-carlo 模拟运行时间几乎提高了3 倍。顺便说一下,这就是随机游走的样子:

结语及相关内容
在本文中,我演示了Python 中的模块numba如何显着加快蒙特卡罗模拟。但是,您必须了解此模块附带的限制。正如我所指出的,如果你有一个数字框架,你将能够充分利用numba 。此外,请注意适用于 numba 的模块和包 – 以及不适用的模块和包。例如,numpy与 numba 配合得很好,而pandas则不行。
你可以在这里阅读更多:
您还可以 在此处查看 Pyhton 中的另一个示例:

专业领域为优化和仿真的工业工程师(R,Python,SQL,VBA)
Leave a Reply