Circular dependency in pandas dataframe

RussH

The following code places bets on coin flip results. You start with £100 and risk 5% on each flip, but because my code calculates bet size 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 re-calculate bet size after each bet depending on your balance at that time so you're betting more when your balance increases and less when it decreases. This would mean that 'bal' depends on the 'bet', which in turn depends on 'bal' so I end up with a circular relationship.

Is this possible to do? Would I need to iterate through the dataframe one row at a time, re-calculating the 'bal' and 'bet' at that particular index?

Thanks.

Alexander

A simple one liner:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related