Circular dependency in pandas data

The following code places bets on the results of flipping coins. You start at £ 100 and risk 5% on each flip, but because my code calculates the size of the bet based on your starting balance, the bet is always 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)

What I would like to do is recalculate the size of the bet after each bet depending on your balance while you bet more when your balance increases and less when it decreases. This will mean that "bal" depends on the "bet", which, in turn, depends on the "bal", so I end up in a circular relationship.

Can this be done? Do I need to iterate over data one row at a time, recounting the “score” and “bid” in this particular index?

Thank.

+4
1

:

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()

enter image description here

+3

All Articles