Hello traders,

Most DMs I get from subscribers and twitter followers fall in three categories.

1) Thanks Algo for XYZ trade

2) Algo I blew up again.

3) I was in the right trade but did not hold it long enough

Saddest part is that the intersection set of all three groups have an uncomfortably large overlap.

How do we fix this?

1) Find edge

2) Manage risk

Today we will focus on automating risk management to the point where only extreme bad luck can blow you up (if you have a positive expectancy strategy. If you do not, this will slowly drain your account to zero)

Here is the code, I will also link a colab notebook so you can run it on the cloud.

If you are not a coder, just scroll down and I will walk you through the inputs and outputs

import pandas as pd

import numpy as np

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LinearRegression

from sklearn.metrics import mean_squared_error

import matplotlib.pyplot as plt

from ipywidgets import interact, widgets, HBox, VBox

# Step 1: Load the data

# Load your own trading data here from your broker/trading software. I added dummy data here

data = {

'risk_reward_ratio': [1.5, 2.0, 2.5, 1.8, 3.0, 2.2, 1.3, 2.7, 1.9, 2.5],

'win_rate': [0.6, 0.7, 0.5, 0.65, 0.8, 0.55, 0.45, 0.75, 0.68, 0.5],

'account_balance': [10000, 15000, 12000, 18000, 20000, 16000, 14000, 17000, 15500, 19000],

'dollars_to_risk': [150, 300, 200, 270, 500, 220, 180, 400, 250, 320]

}

df = pd.DataFrame(data)

# Step 2: Define features and target

X = df[['risk_reward_ratio', 'win_rate', 'account_balance']]

y = df['dollars_to_risk']

# Step 3: Split the data into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Step 4: Train a machine learning model

model = LinearRegression()

model.fit(X_train, y_train)

# Step 5: Evaluate the model

y_pred = model.predict(X_test)

mse = mean_squared_error(y_test, y_pred)

print(f'Mean Squared Error: {mse}')

# Function to predict dollars to risk per trade

def predict_dollars_to_risk(risk_reward_ratio, win_rate, account_balance):

input_data = pd.DataFrame({

'risk_reward_ratio': [risk_reward_ratio],

'win_rate': [win_rate],

'account_balance': [account_balance]

})

predicted_risk = model.predict(input_data)[0]

return max(predicted_risk, 0) # Ensure the predicted risk is not negative

# Function to calculate Kelly criterion

def calculate_kelly(win_rate, risk_reward_ratio):

b = risk_reward_ratio

p = win_rate

q = 1 - p

full_kelly = (b * p - q) / b

return full_kelly

# Function to simulate performance over 10,000 trades

def simulate_performance(account_balance, risk_per_trade, win_rate, risk_reward_ratio, num_trades=10000):

balance_history = [account_balance]

for _ in range(num_trades):

if np.random.rand() < win_rate:

account_balance += risk_per_trade * risk_reward_ratio

else:

account_balance -= risk_per_trade

balance_history.append(account_balance)

return balance_history

# Interactive function to get user input, plot the result, and run simulations

def interactive_plot(risk_reward_ratio, win_rate, account_balance):

dollars_to_risk = predict_dollars_to_risk(risk_reward_ratio, win_rate, account_balance)

if dollars_to_risk == 0:

print("shitty strategy dude, find edge")

return

# Calculate Kelly criterion

full_kelly = calculate_kelly(win_rate, risk_reward_ratio)

half_kelly = full_kelly / 2

quarter_kelly = full_kelly / 4

full_kelly_risk = full_kelly * account_balance

half_kelly_risk = half_kelly * account_balance

quarter_kelly_risk = quarter_kelly * account_balance

# Run simulations

predicted_risk_balance = simulate_performance(account_balance, dollars_to_risk, win_rate, risk_reward_ratio)

full_kelly_balance = simulate_performance(account_balance, full_kelly_risk, win_rate, risk_reward_ratio)

half_kelly_balance = simulate_performance(account_balance, half_kelly_risk, win_rate, risk_reward_ratio)

quarter_kelly_balance = simulate_performance(account_balance, quarter_kelly_risk, win_rate, risk_reward_ratio)

# Plot the simulated performance

plt.figure(figsize=(12, 6))

plt.plot(predicted_risk_balance, label='Predicted Risk')

plt.plot(full_kelly_balance, label='Full Kelly')

plt.plot(half_kelly_balance, label='Half Kelly')

plt.plot(quarter_kelly_balance, label='Quarter Kelly')

plt.xlabel('Number of Trades')

plt.ylabel('Account Balance')

plt.title('Simulated Performance over 10,000 Trades')

plt.legend()

plt.grid(True)

plt.show()

print(f'Dollars to risk per trade: ${dollars_to_risk:.2f}')

print(f'Full Kelly risk per trade: ${full_kelly_risk:.2f}')

print(f'Half Kelly risk per trade: ${half_kelly_risk:.2f}')

print(f'Quarter Kelly risk per trade: ${quarter_kelly_risk:.2f}')

# Create interactive widgets for user input

risk_reward_slider = widgets.FloatSlider(value=2.0, min=0.0, max=20.0, step=0.1, description='Risk/Reward:')

win_rate_slider = widgets.FloatSlider(value=0.6, min=0.4, max=0.9, step=0.01, description='Win Rate:')

account_balance_slider = widgets.FloatSlider(value=15000, min=0.0, max=100000000, step=1000, description='Account Balance:')

risk_reward_text = widgets.FloatText(value=2.0, description='Risk/Reward:')

win_rate_text = widgets.FloatText(value=0.6, description='Win Rate:')

account_balance_text = widgets.FloatText(value=15000, description='Account Balance:')

# Link sliders and text inputs

widgets.jslink((risk_reward_slider, 'value'), (risk_reward_text, 'value'))

widgets.jslink((win_rate_slider, 'value'), (win_rate_text, 'value'))

widgets.jslink((account_balance_slider, 'value'), (account_balance_text, 'value'))

# Combine sliders and text inputs in an interactive box

ui = VBox([

HBox([risk_reward_slider, risk_reward_text]),

HBox([win_rate_slider, win_rate_text]),

HBox([account_balance_slider, account_balance_text])

])

out = widgets.interactive_output(interactive_plot, {

'risk_reward_ratio': risk_reward_slider,

'win_rate': win_rate_slider,

'account_balance': account_balance_slider

})

# Display the interactive widgets and output

display(ui, out)

In the first part of the code, you export your trading data(*sans tilt, exclude tilt trades)*and paste them in the area.

Then we do the usual train/test steps and run the simulations.

After that, we get the dollars to risk per our trades and compare it with kelly, half kelly and full kelly.

If you do not have an edge, this is what the output would look like.

If you have an edge, this is how the output will look like.

Well, then comes the hard part.

**It is to stick to your dollars risked per trade and not martingaling or overbetting unless there is a very good reason to bet exponential size.**

Prop firms are a good way to hone your strategy and risking little actual dollars compared to the rewards you can reap if you have a good strategy.

Speaking of which

*Take advantage of APEX’s 90% promo code and pass account in one day. Also $40 resets on your accounts. Use code MGUOHAIU or alternatively just click the button below*

*Paid subscribers are requested to join the telegram at their earliest convenience. Link is in your welcome email.*

If you do not want to load test data you can simply Kelly/half kelly bet and see the simulations, there is something for everyone.

There are a few things missing in this code and eager traders can optimize it in the following way.

**Data Preprocessing**:

There is no data preprocessing step. In real-world scenarios, data often requires cleaning, normalization, or transformation before use.

**Model Validation**:

The model evaluation is limited to calculating the Mean Squared Error (MSE). Additional validation techniques, such as cross-validation or checking other metrics, should be included to assess the model's performance comprehensively.

**Model Complexity**:

The Linear Regression model might be too simplistic for predicting 'dollars_to_risk'. More complex models could provide better predictions depending on the dataset's complexity and size.

**Random Seed for Simulations**:

There is no control over the random seed for simulations, leading to non-reproducible results. Setting a seed would ensure consistent simulation results for debugging and analysis.

**Simulation Logic**:

The simulation function for performance does not account for trading costs, slippage, or other real-world factors that can affect trading performance.

Well, that’s about it from me and trade safe folks.

-Fin