v1.0.2

Parameter Optimization

The KafalInterpreter includes a native grid-search optimizer (optimize_grid) to evaluate parameter combinations across strategy scripts.

Grid Search Usage

Pass a dictionary of parameter lists to optimize_grid(). The method iterates through Cartesian product combinations, sets script input values, executes backtests in strategy mode, and returns results sorted by the target metric.

from kafal.core.interpreter import KafalInterpreter
import pandas as pd

df = pd.read_csv("market_data.csv", parse_dates=True, index_col=0)

script = """
@input fast_len:int = 10 min=5 max=50
@input slow_len:int = 30 min=20 max=100

fast = ta.sma(close, fast_len)
slow = ta.sma(close, slow_len)

trade.long(crossover(fast, slow))
trade.close(crossunder(fast, slow))
"""

interpreter = KafalInterpreter(
    initial_equity=100_000.0,
    commission_perc=0.0005,
    execution_mode="realistic"
)

# Define grid combinations to evaluate
grid = {
    "fast_len": [5, 10, 15, 20],
    "slow_len": [20, 30, 40, 50]
}

# Run grid search sorted by Sharpe ratio
results = interpreter.optimize_grid(
    code=script,
    df=df,
    grid=grid,
    metric="sharpe"
)

# Print top performing parameter combination
best = results[0]
print("Best Parameters:", best["params"])
print("Best Sharpe Ratio:", best["metric"])
print("Net Profit:", best["stats"]["net_profit"])

Supported Target Metrics

Results can be sorted by any strategy metric returned in performance statistics:

  • "sharpe" (Default): Risk-adjusted return ratio.
  • "net_profit": Total dollar profit or loss.
  • "max_drawdown": Peak-to-trough decline.
  • "win_rate": Ratio of winning trades to total trades.
  • "trades": Total trade execution count.