import pandas as pd
import numpy as np
from scipy import stats
import logging
import matplotlib.pyplot as plt
from pathlib import Path
from dataclasses import dataclass
from openpyxl import Workbook
def calculate_rsi(df, period):
delta = df['close'].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
rs = gain / loss
df[f'rsi_{period}'] = 100 - (100 / (1 + rs))
return df
def load_data(timeframe):
df = pd.DataFrame()
filename = CONFIG['DATA_DIR'] / f"data_volatility_{timeframe}.csv"
if filename.exists():
try:
df = pd.read_csv(
filename, encoding='utf-16',
names=["date", "open", "high", "low", "close", "volume", "adj_close"]
)
df['date'] = pd.to_datetime(df['date'].str.strip(), format='%Y.%m.%d %H:%M', errors='coerce')
df.set_index('date', inplace=True)
df.drop_duplicates(inplace=True)
df.sort_index(inplace=True)
print(f"Fichier chargé avec succès: {filename}")
except Exception as e:
print(f"Erreur lors de la lecture du fichier {filename}: {str(e)}")
logging.error(f"Erreur lors de la lecture du fichier {filename}: {str(e)}")
else:
print(f"Fichier non trouvé: {filename}")
logging.error(f"Fichier non trouvé: {filename}")
return df
def backtest_strategy(df):
df = calculate_rsi(df, CONFIG['RSI_PERIOD'])
trades = []
capital = CONFIG['CAPITAL']
position = None
entry_price = None
code
Assistant
User
écris tout le code complet et ecris en francais
Assistant
for index, row in df.iterrows():
# Ouvrir une position si aucune n'est détenue
if position is None:
if row[f'rsi_{CONFIG["RSI_PERIOD"]}'] <= CONFIG['BUY_RSI']:
position = "long"
entry_price = row['close']
trades.append({"Type": "Buy", "Entry Price": entry_price, "Date": index})
elif row[f'rsi_{CONFIG["RSI_PERIOD"]}'] >= CONFIG['SELL_RSI']:
position = "short"
entry_price = row['close']
trades.append({"Type": "Sell", "Entry Price": entry_price, "Date": index})
# Fermer la position lorsque le RSI atteint le niveau de Take Profit
if position == "long" and row[f'rsi_{CONFIG["RSI_PERIOD"]}'] >= CONFIG['TP_RSI']:
profit = (row['close'] - entry_price) * CONFIG['LOT_SIZE']
capital += profit
trades.append({"Type": "Close Long", "Exit Price": row['close'], "Profit": profit, "Capital": capital, "Date": index})
position = None
elif position == "short" and row[f'rsi_{CONFIG["RSI_PERIOD"]}'] <= CONFIG['TP_RSI']:
profit = (entry_price - row['close']) * CONFIG['LOT_SIZE']
capital += profit
trades.append({"Type": "Close Short", "Exit Price": row['close'], "Profit": profit, "Capital": capital, "Date": index})
position = None
return trades, capital
headers = ["Date", "Type", "Entry Price", "Exit Price", "Profit", "Capital"]
ws.append(headers)
for trade in trades:
ws.append([trade.get(header) for header in headers])
wb.save(filename)
print(f"Rapport de trading sauvegardé dans '{filename}'")
def print_summary(trades, capital):
initial_capital = CONFIG['CAPITAL']
print("\n=== Résultats du Backtesting ===")
print(f"Capital initial: initialcapital:.2f")print(f"Capitalfinal:{capital:.2f}")
print(f"Profit/Perte total: ${(capital - initial_capital):.2f}")
print(f"\nDerniers 5 trades:")
for trade in trades[-5:]:
print(trade)
if name == "main":
main();;;;;;;;;;;;;;;;;;;;;;;;;;je veux qu'il sajuste automatiquement afin de savoir le meilleur tp et le meilleur sl;;
To have your script automatically adjust and find the best Take Profit (TP) and Stop Loss (SL) levels for your trading strategy, you will need to implement a grid search or optimization method. This involves iterating over a range of values for both TP and SL, running the backtest for each combination, and evaluating the performance based on specific metrics (like total profit, Sharpe ratio, etc.).
Below is a simple implementation of such a strategy using grid search over predefined ranges for TP and SL levels:
python
def backtest_strategy_with_tp_sl(df, tp_rsi, sl_rsi):
df = calculate_rsi(df, CONFIG['RSI_PERIOD'])
trades = []
capital = CONFIG['CAPITAL']
position = None
entry_price = None
for index, row in df.iterrows():
if position is None:
if row[f'rsi_{CONFIG["RSI_PERIOD"]}'] <= CONFIG['BUY_RSI']:
position = "long"
entry_price = row['close']
trades.append({"Type": "Buy", "Entry Price": entry_price, "Date": index})
elif row[f'rsi_{CONFIG["RSI_PERIOD"]}'] >= CONFIG['SELL_RSI']:
position = "short"
entry_price = row['close']
trades.append({"Type": "Sell", "Entry Price": entry_price, "Date": index})
# Determine if trade should be closed due to TP or SL
if position == "long":
if row[f'rsi_{CONFIG["RSI_PERIOD"]}'] >= tp_rsi or row[f'rsi_{CONFIG["RSI_PERIOD"]}'] >= sl_rsi:
profit = (row['close'] - entry_price) * CONFIG['LOT_SIZE']
capital += profit
trades.append({"Type": "Close Long", "Exit Price": row['close'], "Profit": profit, "Capital": capital, "Date": index})
position = None
elif position == "short":
if row[f'rsi_{CONFIG["RSI_PERIOD"]}'] <= tp_rsi or row[f'rsi_{CONFIG["RSI_PERIOD"]}'] <= sl_rsi:
profit = (entry_price - row['close']) * CONFIG['LOT_SIZE']
capital += profit
trades.append({"Type": "Close Short", "Exit Price": row['close'], "Profit": profit, "Capital": capital, "Date": index})
position = None
return trades, capital
def optimize_strategy(df):
best_profit = -np.inf
best_tp = None
best_sl = None
best_trades = None
for tp_rsi in range(40, 80, 5): # Example values, adjust as necessary
for sl_rsi in range(10, 50, 5):
trades, capital = backtest_strategy_with_tp_sl(df, tp_rsi, sl_rsi)
profit = capital - CONFIG['CAPITAL']
if profit > best_profit:
best_profit = profit
best_tp = tp_rsi
best_sl = sl_rsi
best_trades = trades
print(f"Optimal TP RSI: {best_tp}, Optimal SL RSI: {best_sl}, Max Profit: {best_profit:.2f}")
return best_trades, best_profit
def main():
df = load_data("1H")
best_trades, best_profit = optimize_strategy(df)
generate_excel_report(best_trades, "optimal_trade_report.xlsx")
print_summary(best_trades, best_profit)
if __name__ == "__main__":
main()
Key Adjustments:
Function Modifications:
backtest_strategy_with_tp_sl() now accepts tp_rsi and sl_rsi as parameters for RSi levels where the position would be closed for take profit or stop loss.
The function checks both TP and SL conditions to decide on closing trades.
Optimization Function:
optimize_strategy() iterates over a range of tp_rsi and sl_rsi, performing backtests for each and comparing the results.
Stores and prints the best TP and SL combination along with the maximum profit achieved.
Main Function:
Calls optimize_strategy to determine the best parameters and generates an Excel report accordingly.
Customization:
Adjust the range and step sizes in the for loops within optimize_strategy() to better explore the parameter space.
You might want to include additional performance metrics (e.g., Sharpe ratio) for a more comprehensive evaluation of strategy performance.
Bien sûr! Voici le code complet en français, incluant l'optimisation des niveaux de Take Profit (TP) et de Stop Loss (SL) basés sur le RSI :
python
import pandas as pd
import numpy as np
from scipy import stats
import logging
import matplotlib.pyplot as plt
from pathlib import Path
from dataclasses import dataclass
from openpyxl import Workbook
# Configuration globale
CONFIG = {
'DATA_DIR': Path('data'),
'LOG_DIR': Path('logs'),
'SEQ_LENGTH': 120,
'CAPITAL': 100.0,
'LOT_SIZE': 0.5,
'RSI_PERIOD': 14,
'BUY_RSI': 30,
'SELL_RSI': 70,
}
# Création du répertoire de logs si nécessaire
CONFIG['LOG_DIR'].mkdir(exist_ok=True)
logging.basicConfig(
filename=CONFIG['LOG_DIR'] / 'trading_predictor.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def calculer_rsi(df, periode):
delta = df['close'].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=periode).mean()
perte = (-delta.where(delta < 0, 0)).rolling(window=periode).mean()
rs = gain / perte
df[f'rsi_{periode}'] = 100 - (100 / (1 + rs))
return df
def charger_donnees(echelle_temps):
df = pd.DataFrame()
fichier = CONFIG['DATA_DIR'] / f"données_volatilité_{echelle_temps}.csv"
if fichier.exists():
try:
df = pd.read_csv(
fichier, encoding='utf-16',
names=["date", "open", "high", "low", "close", "volume", "adj_close"]
)
df['date'] = pd.to_datetime(df['date'].str.strip(), format='%Y.%m.%d %H:%M', errors='coerce')
df.set_index('date', inplace=True)
df.drop_duplicates(inplace=True)
df.sort_index(inplace=True)
print(f"Fichier chargé avec succès: {fichier}")
except Exception as e:
print(f"Erreur lors de la lecture du fichier {fichier}: {str(e)}")
logging.error(f"Erreur lors de la lecture du fichier {fichier}: {str(e)}")
else:
print(f"Fichier non trouvé: {fichier}")
logging.error(f"Fichier non trouvé: {fichier}")
return df
def backtester_strategie_avec_tp_sl(df, rsi_tp, rsi_sl):
df = calculer_rsi(df, CONFIG['RSI_PERIOD'])
trades = []
capital = CONFIG['CAPITAL']
position = None
prix_entree = None
for index, row in df.iterrows():
if position is None:
if row[f'rsi_{CONFIG["RSI_PERIOD"]}'] <= CONFIG['BUY_RSI']:
position = "long"
prix_entree = row['close']
trades.append({"Type": "Achat", "Prix d'Entrée": prix_entree, "Date": index})
elif row[f'rsi_{CONFIG["RSI_PERIOD"]}'] >= CONFIG['SELL_RSI']:
position = "short"
prix_entree = row['close']
trades.append({"Type": "Vente", "Prix d'Entrée": prix_entree, "Date": index})
if position == "long":
if row[f'rsi_{CONFIG["RSI_PERIOD"]}'] >= rsi_tp or row[f'rsi_{CONFIG["RSI_PERIOD"]}'] <= rsi_sl:
profit = (row['close'] - prix_entree) * CONFIG['LOT_SIZE']
capital += profit
trades.append({"Type": "Fermer Long", "Prix de Sortie": row['close'], "Profit": profit, "Capital": capital, "Date": index})
position = None
elif position == "short":
if row[f'rsi_{CONFIG["RSI_PERIOD"]}'] <= rsi_tp or row[f'rsi_{CONFIG["RSI_PERIOD"]}'] >= rsi_sl:
profit = (prix_entree - row['close']) * CONFIG['LOT_SIZE']
capital += profit
trades.append({"Type": "Fermer Short", "Prix de Sortie": row['close'], "Profit": profit, "Capital": capital, "Date": index})
position = None
return trades, capital
def optimiser_strategie(df):
meilleur_profit = -np.inf
meilleur_rsi_tp = None
meilleur_rsi_sl = None
meilleurs_trades = None
for rsi_tp in range(40, 80, 5):
for rsi_sl in range(10, 50, 5):
trades, capital = backtester_strategie_avec_tp_sl(df, rsi_tp, rsi_sl)
profit = capital - CONFIG['CAPITAL']
if profit > meilleur_profit:
meilleur_profit = profit
meilleur_rsi_tp = rsi_tp
meilleur_rsi_sl = rsi_sl
meilleurs_trades = trades
print(f"RSI TP Optimal: {meilleur_rsi_tp}, RSI SL Optimal: {meilleur_rsi_sl}, Profit Max: {meilleur_profit:.2f}")
return meilleurs_trades, meilleur_profit
def generer_rapport_excel(trades, fichier="rapport_trading_optimal.xlsx"):
wb = Workbook()
ws = wb.active
ws.title = "Rapport de Trading"
en_tetes = ["Date", "Type", "Prix d'Entrée", "Prix de Sortie", "Profit", "Capital"]
ws.append(en_tetes)
for trade in trades:
ws.append([trade.get(en_tete) for en_tete in en_tetes])
wb.save(fichier)
print(f"Rapport de trading sauvegardé dans '{fichier}'")
def imprimer_resume(trades, capital):
capital_initial = CONFIG['CAPITAL']
print("\n=== Résultats du Backtesting ===")
print(f"Capital initial: ${capital_initial:.2f}")
print(f"Capital final: ${capital:.2f}")
print(f"Profit/Perte total: ${(capital - capital_initial):.2f}")
print(f"\nDerniers 5 trades:")
for trade in trades[-5:]:
print(trade)
def main():
df = charger_donnees("1H")
meilleurs_trades, meilleur_profit = optimiser_strategie(df)
generer_rapport_excel(meilleurs_trades)
imprimer_resume(meilleurs_trades, meilleur_profit)
if __name__ == "__main__":
main()
Explications
Fonction backtester_strategie_avec_tp_sl : Elle prend en compte les niveaux RSITP et RSISL pour clôturer les positions en fonction des conditions définies.
Fonction optimiser_strategie : Teste diverses combinaisons de RSI TP et SL pour trouver la meilleure stratégie en termes de profit total.
Rapports et résumé : Exporte un rapport Excel et affiche un résumé des résultats, aidant à évaluer la performance de la stratégie optimisée.
Remarques
Vous pouvez ajuster les plages et les incréments de RSI TP et SL dans la fonction optimiser_strategie.
Assurez-vous que les fichiers de données correspondent aux attentes du script (nom des fichiers, encoding, columns).