[Python] I think i found "Holly Grail" or I'm wrong? [closed]

Discussão em 'Python' iniciado por Stack, Abril 8, 2025.

  1. Stack

    Stack Membro Participativo

    This python code backtests simple forex trading strategy using 1h candlesticks data from 2009 to present.

    Strategy:just open long after bullish candlesticks and open short after bearish candlesticks.

    Initial balance: $100

    Risk: $1

    Stoploss: -5pips

    Take profit: +15pips

    The result shocked me if code outputs correct result there is 20000% profit.

    Does this code outputs correct backtest results?

    import pandas as pd

    # === 1. Load Data ===
    file_path = "/storage/emulated/0/Download/EURUSD_H1.csv"
    column_names = ['Time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Extra']
    df = pd.read_csv(file_path, sep="\t", names=column_names, skiprows=1)

    # === 2. Prepare Data ===
    df['Time'] = pd.to_datetime(df['Time'])
    for col in ['Open', 'High', 'Low', 'Close']:
    df[col] = pd.to_numeric(df[col], errors='coerce')
    df = df.dropna(subset=['Open', 'High', 'Low', 'Close']).sort_values('Time').reset_index(drop=True)

    # === 3. Trade Parameters ===
    pip = 0.0001
    take_profit = 15 * pip
    stop_loss = 5 * pip
    holding_period = 1 # <-- Only 1 hour
    risk_per_trade = 1
    pip_value = risk_per_trade / (stop_loss / pip)

    initial_balance = 100
    balance = initial_balance

    # === 4. Backtest ===
    trades = []
    i = 1

    while i < len(df) - holding_period:
    row = df.loc
    signal = 0
    if row['Close'] > row['Open']:
    signal = 1 # Buy
    elif row['Close'] < row['Open']:
    signal = -1 # Sell

    if signal != 0:
    entry_price = df.loc[i + 1, 'Open']
    entry_time = df.loc[i + 1, 'Time']
    j = i + 1
    high = df.loc[j, 'High']
    low = df.loc[j, 'Low']
    close = df.loc[j, 'Close']
    exit_time = df.loc[j, 'Time']

    if signal == 1: # Buy
    if high - entry_price >= take_profit:
    trade_result = take_profit
    elif entry_price - low >= stop_loss:
    trade_result = -stop_loss
    else:
    trade_result = close - entry_price

    elif signal == -1: # Sell
    if entry_price - low >= take_profit:
    trade_result = take_profit
    elif high - entry_price >= stop_loss:
    trade_result = -stop_loss
    else:
    trade_result = entry_price - close

    pnl_pips = round(trade_result / pip, 1)
    pnl_dollars = round(pnl_pips * pip_value, 2)
    balance += pnl_dollars

    trades.append({
    "Entry Time": entry_time,
    "Exit Time": exit_time,
    "Direction": "Buy" if signal == 1 else "Sell",
    "PnL (pips)": pnl_pips,
    "PnL ($)": pnl_dollars,
    "Balance After": round(balance, 2)
    })

    i += holding_period # move to next bar
    else:
    i += 1

    # === 5. Summary ===
    total_profit = round(balance - initial_balance, 2)
    total_trades = len(trades)
    wins = sum(1 for t in trades if t["PnL ($)"] > 0)
    win_rate = round(wins / total_trades * 100, 2) if total_trades > 0 else 0

    # === 6. Print Results ===
    print("Backtest Summary (1h Hold, Bullish = Buy, Bearish = Sell):")
    print(f"Initial Balance: $100")
    print(f"Final Balance: ${round(balance, 2)}")
    print(f"Total Profit: ${total_profit}")
    print(f"Total Trades: {total_trades}")
    print(f"Win Rate: {win_rate}%")
    print("\nSample Trades:")
    for t in trades[:5]:
    print(t)


    [​IMG]

    Continue reading...

Compartilhe esta Página