pandas 数据框中的循环依赖

2024-03-14

以下代码对硬币翻转结果进行投注。您从 100 英镑开始,每次翻转的风险为 5%,但由于我的代码根据您的起始余额计算赌注大小,因此赌注始终为 5 英镑。

import pandas
import matplotlib.pyplot as plt

start_bal = 100.0 #start off with £100
risk = 0.05 # risk 5% on each bet

#create an empty data frame.
a = pandas.DataFrame()

#create a list of coin toss results, 1 is win, -1 is lose
a['Result'] = [1,1,1,1,-1,-1,1,1,1,-1,-1,1,1,-1,-1,-1,1,1]

#your bet size is a % of your starting balance
a['bet'] = start_bal*risk
#record profit or loss based on coin toss
a['pnl'] = a.Result * a.bet
#increase/decrease balance
a['bal'] = start_bal + a.pnl.cumsum()

#plot balance
plt.plot(a.bal)

我想做的是在每次下注后根据您当时的余额重新计算下注大小,这样当您的余额增加时您下注更多,而当余额减少时您下注更少。这意味着“bal”取决于“bet”,而“bet”又取决于“bal”,所以我最终得到了循环关系。

这可以吗?我是否需要一次一行地迭代数据帧,重新计算该特定索引处的“bal”和“bet”?

Thanks.


一个简单的单衬:

results = start_bal * (1 + risk * a.Result).cumprod()
>>> results
0     105.000000
1     110.250000
2     115.762500
3     121.550625
4     115.473094
5     109.699439
6     115.184411
7     120.943632
8     126.990813
9     120.641272
10    114.609209
11    120.339669
12    126.356653
13    120.038820
14    114.036879
15    108.335035
16    113.751787
17    119.439376
Name: Result, dtype: float64

results.plot()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pandas 数据框中的循环依赖 的相关文章

随机推荐