Skip to content

Instantly share code, notes, and snippets.

@flare9x
Last active July 17, 2021 22:26
Show Gist options
  • Save flare9x/a3ff26c1ed90b98871931bc3da2455b9 to your computer and use it in GitHub Desktop.
Save flare9x/a3ff26c1ed90b98871931bc3da2455b9 to your computer and use it in GitHub Desktop.
Risk management iterations
# Risk management simulations
using CSV, DataFrames, StatsBase, Random
##############################
## Trades to double
##############################
winPerc = .46
AvgWin = .14
AvgLoss = .07
WorstLoss = 0.1
PercInvest = winPerc*(((AvgWin/AvgLoss)-(1/winPerc)+1)/(AvgWin/AvgLoss)) # optimal
#=
s = 1-(AvgLoss/WorstLoss)*PercInvest
n = 1+(AvgWin/WorstLoss)*PercInvest
trades2Double = log(2.0)/log((n^winPerc)*s^(1-winPerc))
=#
# calcualte trades to double at any given distribution / win loss ration / win %
# to do
###############################
## Case 1
## 1. 2:1 win loss ratio
## 2. 50% win rate
## 3. Even distribution of win,loss
###############################
bet_fractions = collect(0:.01:1)
win_loss_distribution = reshape([1,0,1,0,1,0,1,0,1,0],1,10) # 1 = head, 0 = tails
win_loss_dist_m = repeat(win_loss_distribution, 101)
win_loss_dist_m = hcat(zeros(size(m,1)),zeros(size(m,1)),win_loss_dist_m)
# maintain 2:1 win ratio
# set bet fraction sizes at starting capital $1000
start_capital = fill(1000,size(bet_fractions,1))
m = hcat(bet_fractions,start_capital,Array{Float64}(undef, size(bet_fractions,1), size(win_loss_distribution,2)))
debugger_m = fill("test",size(m))
i=2
j=3
pos_size = []
for i = 1:size(m,1) # row loop
let pos_size = pos_size
for j = 3:size(m,2) # column loop
debugger_m[i,j] = string([i,j])
#print("iteration k ", k)
pos_size = m[i,1] * m[i,(j-1)] # fraction % size of total equity
#debugger_m[i,j] = string([pos_size])
if win_loss_dist_m[i,j] == 1
#debugger_m[i,j] = string([i,j])
m[i,j] = m[i,(j-1)] + (pos_size * 2) # 2:1 ratio
elseif win_loss_dist_m[i,j] == 0
m[i,j] = m[i,(j-1)] - pos_size # lose
end
end
end
end
# find maximum winning proceeds after 1 win / loss cycle
max_one = m[findmax(m[:,4])[2],1] # considering an even distribution of win,lose for 5 cycles at 2:1 win ratio with win,loss resutling in 50% win rate. 25% is the optimal betting fraction of account
# find maximum winning proceeds end of 5 win,loss cycles
max_end = m[findmax(m[:,12])[2],1] # considering an even distribution of win,lose for 5 cycles at 2:1 win ratio with win,loss resutling in 50% win rate. 25% is the optimal betting fraction of account
# Kelly formula:: K = W - (1-W)/R
# K = Fraction of Capital for Next Trade
# W = Historical Winning probability
# R = Win loss ratio
InitialCapital = 10000.00
W = .5
AvgPercGain = .06 # percent
AvgPercLoss = .03 # percent
R = AvgPercGain / AvgPercLoss
K = W - (1-W)/R
OptimalDollarInvest = K * InitialCapital
AvgDollarGain = AvgPercGain * OptimalDollarInvest # average dollar gain
AvgDollarLoss = AvgPercLoss * OptimalDollarInvest # average dollar loss
edge = (AvgDollarGain/InitialCapital)*W-(AvgDollarLoss/InitialCapital)*(1-W)
expectednetgain = (W*AvgDollarGain)-((1-W)*AvgDollarLoss) # expected dollar gain amount
expectednetpercgain = expectednetgain / OptimalDollarInvest # expected % gain amount
trades_to_double = InitialCapital / expectednetgain # trades needed to double
n_trades = trades_to_double
InitialCapital+(InitialCapital*edge *n_trades) #account balance after n trades
min_perc_to_be_profitable = 1 / (R+1) # minimum win percent to be profitable
max_avg_loss = (AvgDollarGain/InitialCapital*W)/(1-W) * 100 # Maximum Average Loss to Be Profitable
min_avg_win = (AvgDollarLoss/InitialCapital)*(1-W)/(1-(1-W)) * 100 # Minimum Average Win to Be Profitable%
# optimal_f
optimal_f = (((1+w_l_ratio)*winPerc)-1)/(w_l_ratio)
# minervini expectancy
# PWT (percentage of winning trades)*AG (average gain) / PLT (percentage of losing trades)*AL (average loss) = Expectancy
win_perc = .5
avg_gain = .06
loss_perc = (1-win_perc)
avg_loss = .03
expectancy = (win_perc * avg_gain) / (loss_perc * avg_loss)
# export data to .csv
out = DataFrame(m)
CSV.write("C:/Users/Andrew.Bannerman/OneDrive - Shell/Documents/Model Book/Paper trade charts/optimal_out.csv", out;delim=',')
####################################
## Case 2
## 1. n win loss ratio
## 2. 50% win rate
## 3. Uneven distribution of win,loss
## Set Additions
## 1. n sample of trades
## 2. varying win/loss % (set probability of win as variable and set 1,0 dist. accordingly)
## 3. for a given win/loss ratio and varying random distribution of W,L - find the optimal betting fraction - iterate - cross check to kelly
## 4. Calculate
#####################################
n = 50
win_prob = .50
w_l_ratio = 2
wins = fill(1,(Int64.(round(win_prob*n,digits=0))))
loss = fill(0,(Int64.(round((1-win_prob)*n,digits=0))))
prob = vcat(wins,loss)
bet_fractions = collect(0:.01:1)
win_loss_distribution = reshape(sample(prob, n, replace = false),1,n) # 1 = head, 0 = tails
perc_correct = sum(win_loss_distribution)/n
win_loss_dist_m = repeat(win_loss_distribution, size(bet_fractions,1))
#win_loss_dist_m = hcat(zeros(size(win_loss_dist_m,1)),zeros(size(win_loss_dist_m,1)),win_loss_dist_m)
# maintain 2:1 win ratio
# set bet fraction sizes at starting capital $1000
start_capital = fill(1000.0,size(bet_fractions,1))
m = hcat(bet_fractions,start_capital,Array{Float64}(undef, size(bet_fractions,1), size(win_loss_distribution,2)))
win_loss_dist_m = hcat(zeros(size(m,1)),zeros(size(m,1)),win_loss_dist_m)
debugger_m = fill("test",size(m))
pos_size = []
for i = 1:size(m,1) # row loop
let pos_size = pos_size
for j = 3:size(m,2) # column loop
debugger_m[i,j] = string([i,j])
#print("iteration k ", k)
pos_size = m[i,1] * m[i,(j-1)]
#debugger_m[i,j] = string([pos_size])
if win_loss_dist_m[i,j] == 1.0
#debugger_m[i,j] = string([i,j])
m[i,j] = m[i,(j-1)] + (pos_size * w_l_ratio) # win to loss ratio, see var w_l_ratio
elseif win_loss_dist_m[i,j] == 0.0
m[i,j] = m[i,(j-1)] - pos_size # lose
end
end
end
end
# find maximum winning proceeds after 1 win / loss cycle
max_one = m[findmax(m[:,4])[2],1]
# find maximum winning proceeds end of 5 win,loss cycles
max_end = m[findmax(m[:,size(m,2)])[2],1]
# iterate to find the maximum bet fraction along the uneven distribution of win,loss
optimal_bet_fraction = zeros(size(m,2))
i=1
for i = 4:size(m,2)
optimal_bet_fraction[i] = m[findmax(m[:,i])[2],1]
end
optimal_bet_fraction = optimal_bet_fraction[3:size(optimal_bet_fraction,1)]
# calcuate rolling win loss percent probs
i=1
rolling_win_loss_perc = zeros(size(win_loss_distribution,2))
for i = 1:size(win_loss_distribution,2)
rolling_win_loss_perc[i] = sum(win_loss_distribution[1:i]) / i
end
rolling_optimal_fraction = hcat(rolling_win_loss_perc,optimal_bet_fraction,reshape(win_loss_distribution,n,1))
rolling_optimal_fraction = DataFrame(rolling_optimal_fraction)
# Calculate rolling equity on the optimal betting fraction which is re-calculated at the end of each trade
o_m = hcat(optimal_bet_fraction,reshape(win_loss_distribution,n,1),zeros(size(win_loss_distribution,2)),rolling_win_loss_perc,zeros(size(win_loss_distribution,2)),zeros(size(win_loss_distribution,2)))
optimal_size_equity = zeros(size(o_m,1))
o_m[1,3] = 1000.00 # initialize starting
i = 5
for i = 2:size(o_m,1)
# calculate kelly formula for optimal bet size K = W - (1-W)/R
o_m[i,5] = o_m[i,4] - (1-o_m[i,4])/w_l_ratio
# calculate optimal_f
#o_m[i,6] = (((1+w_l_ratio)*o_m[i,4])-1)/(w_l_ratio)
if o_m[i,1] == 0.0
o_m[i,3] = 1000.00
end
pos_size = o_m[i,1] * o_m[i-1,3] # fraction % size of total equity
if o_m[i,2] == 1.0
#debugger_m[i,j] = string([i,j])
o_m[i,3] = o_m[i-1,3] + (pos_size * w_l_ratio) # win to loss ratio, see var w_l_ratio
elseif o_m[i,2] == 0.0
o_m[i,3] = o_m[i-1,3] - pos_size # lose
end
end
# Kelly formula:: K = W - (1-W)/R
# K = Fraction of Capital for Next Trade
# W = Historical Winning probability
# R = Win loss ratio
W = .50
R = 5/1
K = W - (1-W)/R
# export data to .csv
# add on win loss distribution to the final output
out = DataFrame(m)
out = DataFrame(o_m)
CSV.write("C:/Users/Andrew.Bannerman/OneDrive - Shell/Documents/Model Book/Paper trade charts/uneven_dist_optimal_fraction.csv", out;delim=',')
####################################
## Case 3
## 1. 2:1 win loss ratio
## 2. random win rate %
## 3. Uneven distribution of win,loss
## Additions
## 1. n sample of trades
## 2. for varying win/loss ratioand varying random distribution of W,L - find the optimal betting fraction - iterate - cross check to kelly
#####################################
n = 1000
win_prob = .50
w_l_ratio = 5
wins = fill(1,(Int64.(round(win_prob*n,digits=0))))
loss = fill(0,(Int64.(round((1-win_prob)*n,digits=0))))
prob = vcat(wins,loss)
bet_fractions = collect(0:.01:1)
win_loss_distribution = reshape(sample(prob, n, replace = false),1,n) # 1 = head, 0 = tails
perc_correct = sum(win_loss_distribution)/n
win_loss_dist_m = repeat(win_loss_distribution, size(bet_fractions,1))
win_loss_dist_m = hcat(zeros(size(m,1)),zeros(size(m,1)),win_loss_dist_m)
# maintain 2:1 win ratio
# set bet fraction sizes at starting capital $1000
start_capital = fill(1000,size(bet_fractions,1))
m = hcat(bet_fractions,start_capital,Array{Float64}(undef, size(bet_fractions,1), size(win_loss_distribution,2)))
win_loss_dist_m = hcat(zeros(size(m,1)),zeros(size(m,1)),win_loss_dist_m)
debugger_m = fill("test",size(m))
pos_size = []
for i = 1:size(m,1) # row loop
let pos_size = pos_size
for j = 3:size(m,2) # column loop
debugger_m[i,j] = string([i,j])
#print("iteration k ", k)
pos_size = m[i,1] * m[i,(j-1)]
#debugger_m[i,j] = string([pos_size])
if win_loss_dist_m[i,j] == 1
#debugger_m[i,j] = string([i,j])
m[i,j] = m[i,(j-1)] + (pos_size * w_l_ratio) # win to loss ratio, see var w_l_ratio
elseif win_loss_dist_m[i,j] == 0
m[i,j] = m[i,(j-1)] - pos_size # lose
end
end
end
end
# find maximum winning proceeds after 1 win / loss cycle
max_one = m[findmax(m[:,4])[2],1]
# find maximum winning proceeds end of 5 win,loss cycles
max_end = m[findmax(m[:,size(m,2)])[2],1]
# iterate to find the maximum bet fraction along the uneven distribution of win,loss
optimal_bet_fraction = zeros(size(m,2))
i=1
for i = 4:size(m,2)
optimal_bet_fraction[i] = m[findmax(m[:,i])[2],1]
end
optimal_bet_fraction = optimal_bet_fraction[3:size(optimal_bet_fraction,1)]
# calcuate rolling % gain
rolling_win_loss_perc = zeros(size(win_loss_distribution,2))
for i = 1:size(win_loss_distribution,2)
rolling_win_loss_perc[i] = sum(win_loss_distribution[1:i]) / i
end
rolling_optimal_fraction = hcat(rolling_win_loss_perc,optimal_bet_fraction,reshape(win_loss_distribution,n,1))
rolling_optimal_fraction = DataFrame(rolling_optimal_fraction)
# Calculate rolling equity on the optimal betting fraction which is re-calculated at the end of each trade
o_m = hcat(optimal_bet_fraction,reshape(win_loss_distribution,n,1),zeros(size(win_loss_distribution,2)),rolling_win_loss_ratio,zeros(size(win_loss_distribution,2)))
optimal_size_equity = zeros(size(o_m,1))
o_m[1,3] = 1000.00 # initialize starting
i = 5
for i = 2:size(o_m,1)
# calculate kelly formula for optimal bet size K = W - (1-W)/R
o_m[i,5] = o_m[i,4] - (1-o_m[i,4])/w_l_ratio
if o_m[i,1] == 0.0
o_m[i,3] = 1000.00
end
pos_size = o_m[i,1] * o_m[i-1,3] # fraction % size of total equity
if o_m[i,2] == 1.0
#debugger_m[i,j] = string([i,j])
o_m[i,3] = o_m[i-1,3] + (pos_size * w_l_ratio) # win to loss ratio, see var w_l_ratio
elseif o_m[i,2] == 0.0
o_m[i,3] = o_m[i-1,3] - pos_size # lose
end
end
# Kelly formula:: K = W - (1-W)/R
# K = Fraction of Capital for Next Trade
# W = Historical Winning probability
# R = Win loss ratio
W = .50
R = 5/1
K = W - (1-W)/R
# export data to .csv
out = DataFrame(m)
CSV.write("C:/Users/Andrew.Bannerman/OneDrive - Shell/Documents/Model Book/Paper trade charts/uneven_dist_rolling_optimal_fraction.csv", rolling_optimal_fraction;delim=',')
####################################
# Optimal Compunding
# 1. Compound over n trades
# 2. Compare to finding 1x stock going up same percentage
##
# Results
# 2x 40% gains = 96%
# 4x 20% gains = 107%
# 12x 10% gains = 214%
# 20x 5% gains = 152%
#####################################
n = 20
capital = 1000.00
perc_gain = .05
benchmark_gain = 1.0 # 50 %
compound_gain = zeros(n)
compound_gain[1] = capital
for i = 2:size(compound_gain,1)
compound_gain[i] = compound_gain[i-1] + (compound_gain[i-1] * perc_gain)
end
perc_increase = (compound_gain[size(compound_gain,1)] - compound_gain[1]) / compound_gain[1] *100
# Compounding Formula
P = 1.0 # principal balance
i = .3 # % return (rate) per period
n = 10 # trials / event / years / months / trades etc...
(P*(1+i)^n)-1
##########################
## Worst Loss of a System
## $100,000 account 25% size - worst loss limit to 10% - losing 10% on 25% position size = 2.5% total loss of capital
#########################
capital = 100000.00
perc_invest = .125
trade_size = perc_invest * capital
worst_loss = .1
total_loss_to_account = (worst_loss * trade_size) / capital
#######
# Drawdown table - % needed to get back to even
######
percs = collect(0:.001:1)
gain_needed_for_even = zeros(size(percs,1))
for i=1:size(percs,1)
gain_needed_for_even[i] = abs(((1000.0-(1000.0*percs[i]))-1000.0)/(1000.0-(1000.0*percs[i])))
end
out = hcat(percs,gain_needed_for_even)
############################
## Risk management strategy
# 1. Nothing is known 100%
# 2. Stack probabilities
# 3. Anticipate setups with 6% position sizes
# 4. Prune the garden - add to stocks acting well and sell the or reduce in size those not acting well
# 5. On breakout bump up the position sizes
############################
n = 100
win_prob = .50
w_l_ratio = 2
wins = fill(1,(Int64.(round(win_prob*n,digits=0))))
loss = fill(0,(Int64.(round((1-win_prob)*n,digits=0))))
prob = vcat(wins,loss)
bet_fractions = collect(0:.01:1)
win_loss_distribution = reshape(sample(prob, n, replace = false),n,1) # 1 = head, 0 = tails
perc_correct = sum(win_loss_distribution)/n
# 0 = loss a d 1 = win
# wins at 25% of account
# loss at 6% of account
rolling_capital = zeros(size(win_loss_distribution,1))
rolling_capital_comp = zeros(size(win_loss_distribution,1))
rolling_capital[1] = 1000.0
rolling_capital_comp[1] = 1000.0
win_perc_size = .25
loss_perc_size = .06
i = 1
for i = 2:size(rolling_capital,1)
if win_loss_distribution[i] == 1
rolling_capital[i] = (win_perc_size*rolling_capital[i-1] * w_l_ratio) + rolling_capital[i-1] # gain at the win loss ratio
rolling_capital_comp[i] = (win_perc_size*rolling_capital_comp[i-1] * w_l_ratio) + rolling_capital_comp[i-1] # duplicate the above as same
elseif win_loss_distribution[i] == 0
rolling_capital[i] = rolling_capital[i-1] - (loss_perc_size*rolling_capital[i-1]) # loss at the one part
rolling_capital_comp[i] = rolling_capital_comp[i-1] - (win_perc_size*rolling_capital_comp[i-1]) # loss at the one part
end
end
# check comparisons
end_losing_less = rolling_capital[size(rolling_capital,1)]
end_losing_more = rolling_capital_comp[size(rolling_capital_comp,1)]
ratio = end_losing_less / end_losing_more
difference = end_losing_less - end_losing_more,digits
out = DataFrame(hcat(win_loss_distribution,rolling_capital,rolling_capital_comp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment