import pandas as pd import numpy as np from scipy import stats import logging import…
- User
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, 'TP_RSI': 50, }
Création du répertoire de logs si non existant
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 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
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 - Assistant
- User
=== Résultats du Backtesting === Capital initial: -1563.44 Profit/Perte total: $-1663.44
Derniers 5 trades: {'Type': 'Sell', 'Entry Price': np.float64(1016.33), 'Date': Timestamp('2024-11-11 16:00:00')} {'Type': 'Close Short', 'Exit Price': np.float64(989.33), 'Profit': np.float64(13.5), 'Capital': np.float64(-1572.5600000000018), 'Date': Timestamp('2024-11-12 17:00:00')} {'Type': 'Buy', 'Entry Price': np.float64(1016.44), 'Date': Timestamp('2024-11-12 18:00:00')} {'Type': 'Close Long', 'Exit Price': np.float64(1034.69), 'Profit': np.float64(9.125), 'Capital': np.float64(-1563.4350000000018), 'Date': Timestamp('2024-11-14 06:00:00')} {'Type': 'Sell', 'Entry Price': np.float64(1033.04), 'Date': Timestamp('2024-11-14 09:00:00')} PS C:\Users\fchabi\Downloads\projet new> ;;;;;;;;;;;;;;;;;;ichimoku je pense tas rater un truc inh;;;; les entree cest la cassure du nuage; et la sortir cest cassure du tekan et kinjoun
- Assistant