Certainly!
To make the trading strategy better and include ways to avert risk for small profit, I've made several modifications to your code:
-
Introduced Transaction Costs: Real-world trading involves fees. I've added a transaction fee to each buy and sell action to simulate a more realistic trading environment.
-
Minimum Expected Profit Threshold: We now only enter a trade if the predicted profit exceeds a certain percentage, avoiding trades that might result in negligible gains after fees.
-
Implemented Stop-Loss Mechanism: To limit potential losses, a stop-loss is triggered if the price drops by a certain percentage from the buying price.
-
Maximum Holding Period: This ensures that we don't hold onto a position indefinitely if neither the target profit nor the stop-loss conditions are met.
-
Adjusted Trading Logic: Used actual units of assets for buying and selling rather than percentage changes, providing a more accurate simulation.
-
Enhanced Logging: Added print statements to trace the trading actions, making it easier to debug and understand the trading decisions.
Below is the revised code:
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from keras.models import load_model
from keras.optimizers import Adam
import matplotlib.pyplot as plt
def simulate_trading_smart_retrain():
model_path = 'retrain_model.h5'
# Load the model
model = load_model(model_path, compile=False)
model.compile(optimizer=Adam(learning_rate=0.001), loss='mse', run_eagerly=True)
window_num = 48
# Constants for trading strategy
TRANSACTION_FEE_RATE = 0.0005 # 0.05% per trade
MINIMUM_EXPECTED_PROFIT_RATE = 0.01 # Minimum 1% expected profit to enter a trade
STOP_LOSS_RATE = 0.02 # 2% stop-loss
MAX_HOLDING_PERIOD = 24 * 5 # Max holding period of 5 days
# Load and normalize the data
ds = pd.read_csv('price_data2.csv')
ds = ds.assign(Date=pd.to_datetime(ds['Date']))
ds.loc[ds['Volume']=="-",'Volume']=0
ds['Volume'] = ds['Volume'].astype('int64')
ds=ds[['Date','Close','Open','High','Low','Volume','Market Cap']]
scaler = MinMaxScaler()
ds.drop(['Date'],inplace=True,axis=1)
ds_normalized = scaler.fit_transform(ds.values[-2232:])
balance = 10000 # Starting balance in currency
units = 0 # Units of asset currently holding
holding = False
buy_time = None
sell_time = None
wanted_sell_price = None
prediction_data = []
timestamps = [] # Store timestamps for predictions
balance_over_time = []
actual_prices = [x[0] for x in scaler.inverse_transform(ds_normalized).tolist()]
buy_points = []
sell_points = []
def process_entries(data):
X = []
y = []
for i in range(window_num, len(data)):
X.append(data[i - window_num:i])
y.append(data[i][0])
return np.array(X), np.array(y)
# Loop through the data for trading simulation
for i in range(window_num, len(ds_normalized)):
current_window = ds_normalized[i - window_num:i]
pred = model.predict(np.array([current_window]), verbose=0)
pred = np.concatenate((pred[0], current_window[-1][1:]))
pred = scaler.inverse_transform([pred])
pred = pred[0][0]
current_price_scaled = current_window[-1]
current_price = scaler.inverse_transform([current_price_scaled])[0][0]
if not holding:
expected_profit_rate = (pred - current_price) / current_price
if expected_profit_rate >= MINIMUM_EXPECTED_PROFIT_RATE:
# Calculate number of units to buy
units = balance / current_price
# Account for transaction fee
units -= units * TRANSACTION_FEE_RATE
balance = 0
holding = True
buy_time = i
buy_price = current_price
wanted_sell_price = pred
buy_points.append((i, current_price))
print(f"Bought {units:.4f} units at {current_price:.2f} on day {i//24}")
else:
# When holding, check for stop-loss, target price, or max holding period
time_held = i - buy_time
# Check for stop loss
if current_price <= buy_price * (1 - STOP_LOSS_RATE):
# Stop-loss triggered
proceeds = units * current_price
# Account for transaction fee
proceeds -= proceeds * TRANSACTION_FEE_RATE
balance = proceeds
units = 0
holding = False
sell_points.append((i, current_price))
print(f"Stop-loss triggered. Sold at {current_price:.2f} on day {i//24}. New balance: {balance:.2f}")
balance_over_time.append(balance)
# Check if target price reached
elif current_price >= wanted_sell_price:
proceeds = units * current_price
# Account for transaction fee
proceeds -= proceeds * TRANSACTION_FEE_RATE
balance = proceeds
units = 0
holding = False
sell_points.append((i, current_price))
print(f"Target price reached. Sold at {current_price:.2f} on day {i//24}. New balance: {balance:.2f}")
balance_over_time.append(balance)
# Check if holding period exceeded
elif time_held >= MAX_HOLDING_PERIOD:
proceeds = units * current_price
# Account for transaction fee
proceeds -= proceeds * TRANSACTION_FEE_RATE
balance = proceeds
units = 0
holding = False
sell_points.append((i, current_price))
print(f"Max holding period exceeded. Sold at {current_price:.2f} on day {i//24}. New balance: {balance:.2f}")
balance_over_time.append(balance)
# Else, keep holding
timestamps.append(i)
prediction_data.append(pred)
# Periodically retrain the model
if i % (24 * 4) == 0 and i != 0:
# Retrain model on the last 8 days
data = ds_normalized[i - (8 * 24):i]
if len(data) >= window_num:
X_train, y_train = process_entries(data)
model.fit(X_train, y_train, epochs=5, batch_size=32, verbose=0, shuffle=False)
# Save the updated model
model.save('retrain_model.h5')
print(f"Model retrained at step {i}")
# If still holding at the end, sell all
if holding:
current_price_scaled = ds_normalized[-1]
current_price = scaler.inverse_transform([current_price_scaled])[0][0]
proceeds = units * current_price
# Account for transaction fee
proceeds -= proceeds * TRANSACTION_FEE_RATE
balance = proceeds
units = 0
holding = False
sell_points.append((len(ds_normalized)-1, current_price))
print(f"End of data. Sold at {current_price:.2f}. Final balance: {balance:.2f}")
balance_over_time.append(balance)
print(f"Final Balance: {balance:.2f}")
# Plot actual prices and trades
plt.figure(figsize=(14, 7))
actual_prices = [x[0] for x in scaler.inverse_transform(ds_normalized).tolist()]
plt.plot(actual_prices, label="Actual Prices", color='blue')
plt.plot(timestamps, prediction_data[:len(timestamps)], label="Predicted Prices", color='orange', alpha=0.6)
for t, price in buy_points:
plt.scatter(t, price, marker='^', color='green', label='Buy' if t == buy_points[0][0] else "")
for t, price in sell_points:
plt.scatter(t, price, marker='v', color='red', label='Sell' if t == sell_points[0][0] else "")
plt.xlabel("Time")
plt.ylabel("Price")
plt.title("AI Trading Simulation")
plt.legend()
plt.grid()
plt.show()
# Plot balance over time
plt.figure(figsize=(14, 5))
time_steps_balance = list(range(len(balance_over_time)))
plt.plot(time_steps_balance, balance_over_time, label="Balance Over Time", color='purple')
plt.xlabel("Trades")
plt.ylabel("Balance")
plt.title("Balance Changes During Simulation")
plt.legend()
plt.grid()
plt.show()
# Call the function
simulate_trading_smart_retrain()
Key Changes Explained:
-
Transaction Costs:
-
Minimum Expected Profit Threshold:
-
Stop-Loss Mechanism:
-
Maximum Holding Period:
-
Adjusted Trading Logic with Units:
-
Enhanced Logging:
Additional Notes:
-
Retraining the Model: The model retrains every 4 days using the previous 8 days of data, ensuring it adapts to recent market conditions.
if i % (24 * 4) == 0 and i != 0:
# Retrain model
-
Final Sell-Off: If we're still holding a position at the end of the dataset, we sell all remaining units.
if holding:
# Sell all units
-
Balance Plotting: The balance over time is plotted against the number of trades executed, giving a clearer picture of performance after each trade.
By incorporating these risk management strategies, the revised trading algorithm aims to improve profitability while minimizing potential losses due to unfavorable market movements or small profit margins that could be negated by transaction costs. Remember to adjust the constants (TRANSACTION_FEE_RATE, MINIMUM_EXPECTED_PROFIT_RATE, STOP_LOSS_RATE, and MAX_HOLDING_PERIOD) to suit the specific characteristics of the market or asset you're simulating.