python - 在 Python 中利用蒙特卡洛预测收入

标签 python python-3.x montecarlo

我正在尝试在我的 Python 代码中实现蒙特卡罗模拟,这将帮助我确定实现与收入目标相关的各种阈值的可能性。例如,我们每个财年达到 6,000 美元、7,000 美元或 8,000 美元的可能性有多大。我能够计算预期值,但还没有编写模拟代码。我尝试创建一个运行 1000 次模拟的函数,但未能实现(这要归功于我的新手编码能力)。理想情况下,我能够返回总数和每个合约的平均值和标准差,可用于将它们绘制在正态曲线上。

import pandas as pd

ID = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Revenue = [1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800, 1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800]
odds = [0.5, 0.6, 0.33, 0.1, 0.9, 0.87, 0.37, 0.55, 0.97, 0.09, 0.5, 0.6, 0.33, 0.1, 0.9, 0.87, 0.37, 0.55, 0.97, 0.09]
FY = [2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019]
d = {'ID': ID, 'Revenue': Revenue, 'Odds': odds, 'Fiscal Year': FY}
df = pd.DataFrame(d)
df['Expected Value'] = df['Revenue']*df['Odds']

print(df)

这是我一直在编写的一小段代码,但我一路上迷失了。

import pandas_montecarlo
mc = OtisPrediction_df['Realization Rate'].montecarlo(sims = 100)
mc.plot()
print(mc.stats)

或者

def win_loss_func(iterator):
    odds = random.randint(1,100)/100
    X = []
    Y = []
    i = 1
    while i <= iterator:
        if df['Odds'] >= odds:
            i+=1
            X.append(i)
            Y.append(OtisPrediction_df[''])
    print(odds)

我需要能够为每个会计年度的每个 ID 运行蒙特卡罗。有没有办法做到这一点?我创建了一个函数,为每个条目创建一个数组,但我仍然需要根据 ID 和 Filter 字段进行过滤,以使用 10,000 个模拟填充每个数组。 def monte_carlo_array(df): for _ in range(len(df)): yield []

最佳答案

此解决方案效率不高,因为没有并行执行任何操作,但您可以清楚地看到模拟是如何执行的。

num_samples = 10000
revenue_2018 = []
revenue_2019 = []

filter_2018 = (df['Fiscal Year'] == 2018)
filter_2019 = (df['Fiscal Year'] == 2019)

for _ in range(num_samples):
    sample = df['Revenue'] * ( np.random.rand(20) < df['Odds'] )
    revenue_2018.append(sample.loc[filter_2018].sum())
    revenue_2019.append(sample.loc[filter_2019].sum())

# Plot simulation results.
n_bins = 10
plt.hist([revenue_2018, revenue_2019], bins=n_bins, label=["Revenue 2018", "Revenue 2019"])
plt.legend()
plt.title("{} simulations of yearly revenue".format(num_samples))

# Print statistics.
print("Mean for 2018 is {}. Standard Deviation is {}".format(np.mean(revenue_2018), np.std(revenue_2018)))
print("Mean for 2019 is {}. Standard Deviation is {}".format(np.mean(revenue_2019), np.std(revenue_2019)))

关于python - 在 Python 中利用蒙特卡洛预测收入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52173863/

相关文章:

python - 使用 python 2.7 查询 sqlite3 数据库并获取 "sqlite3 operational error no such table"

python - 通过自省(introspection)解析命令行参数

python - 合并具有限制的公共(public)整数对

python - 使用正则表达式验证用户输入

python - 其中哪些在 Python 中是不可变的?

python - 如何为 langchain 向量存储提供嵌入功能

c++ - int 到 unsigned int 的无效转换

python - 对于相关分布采样,是否有 scipy _norm_pdf 的快速替代方案?

python - 尝试用特定值填充整个行/列时形状不匹配值错误

c++ - 与蒙特卡洛的定积分没有可接受的误差