I want to implement a classic martingale using Python and Pandas in a betting system.
Let’s say that this DataFrame is defined like this
df = pd.DataFrame(np.random.randint(0,2,100)*2-1, columns=['TossResults'])
so it contains toss results (-1=lose 1=win)
I would like to change stake (the amount I bet every bet) using classic martingale.
Initial stake is 1.
If I lose stake will be 2 times previous stake (multiplier=2).
If I win stake will be stake_initial
I did a function
def stake_martingale_classical(stake_previous, result_previous, multiplier, stake_initial):
if (result_previous==-1): # lose
stake = stake_previous*multiplier
elif (result_previous==1):
stake = stake_initial
else:
raise(Exception('Error result_previous must be equal to 1 (win) or -1 (lose)'))
return(stake)
but I don’t know how to implement it efficiently using Pandas.
I tried this :
initial_stake = 1
df['Stake'] = None
df['Stake'][0] = initial_stake
df['TossResultsPrevious'] = self.df['TossResults'].shift(1) # shifting-lagging
df['StakePrevious'] = self.df['Stake'].shift(1) # shifting-lagging
but now, I need to apply this (multiparameters) function along 0-axis.
I don’t know how to proceed !
I ever saw pandas.DataFrame.applymap function but it seems to be 1 parameter function only.
Maybe I’m wrong and using shift function is not a good idea
One slight interpretation change is you need to mark a loss as a
1and a win as a0.The first step is to find the edges of the losing runs, (
steps+edges). You then need to take the difference of the sizes of the steps and shove those values back into the original data. When you take acumsumoftoss2it gives you the current length of your losing streak. Your bet is then2 ** cumsum(toss2).The
numpyversion is faster than thepandasversion, but the factor depends onN(~8 forN=100and ~2 forN > 10000).pandas
Using
pandas.Series:numpy
This is the pure
numpyversion (my native language is it were). There is a bit of fineagling to get the arrays to line up thatpandasdoes for youpandas output
numpy output
(different seed than panadas results)