Skip to main content
Glama

walk_forward_analysis

Optimizes moving average crossover strategies using walk-forward analysis to validate trading parameters across training and testing periods.

Instructions

Performs Walk Forward Analysis on MA Crossover. Optimizes (Fast, Slow) on Train, tests on Test.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYes
start_dateNo2020-01-01
end_dateNo2023-12-31
train_monthsNo
test_monthsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main handler function implementing walk-forward analysis for MA crossover strategy. Fetches data, creates rolling train/test windows, optimizes MA parameters on train data, evaluates on test data, and compiles results.
    def walk_forward_analysis(symbol: str, start_date: str = "2020-01-01", end_date: str = "2023-12-31", train_months: int = 12, test_months: int = 3) -> str:
        """
        Performs Walk Forward Analysis on MA Crossover.
        Optimizes (Fast, Slow) on Train, tests on Test.
        """
        df = _fetch_data(symbol, start_date, end_date)
        if df.empty:
            return "No data found."
        
        close = df['Close']
        if isinstance(close, pd.DataFrame):
            close = close.iloc[:, 0]
            
        # Generate windows
        # Simplified: Iterate by index assuming daily data
        # 21 days/month
        train_len = train_months * 21
        test_len = test_months * 21
        step = test_len
        
        results = []
        
        # Parameter Grid
        fast_params = [10, 20, 50]
        slow_params = [50, 100, 200]
        
        current_idx = 0
        while current_idx + train_len + test_len < len(df):
            train_data = close.iloc[current_idx : current_idx + train_len]
            test_data = close.iloc[current_idx + train_len : current_idx + train_len + test_len]
            
            # Optimize on Train
            best_perf = -np.inf
            best_params = (0, 0)
            
            for f in fast_params:
                for s in slow_params:
                    if f >= s: continue
                    # Vectorized backtest on train
                    fast_ma = train_data.rolling(window=f).mean()
                    slow_ma = train_data.rolling(window=s).mean()
                    signal = (fast_ma > slow_ma).astype(int).shift(1)
                    ret = train_data.pct_change() * signal
                    perf = ret.sum() # Simple sum of returns
                    
                    if perf > best_perf:
                        best_perf = perf
                        best_params = (f, s)
            
            # Test on Test Data
            f, s = best_params
            fast_ma_test = test_data.rolling(window=f).mean()
            slow_ma_test = test_data.rolling(window=s).mean()
            signal_test = (fast_ma_test > slow_ma_test).astype(int).shift(1)
            ret_test = test_data.pct_change() * signal_test
            test_perf = ret_test.sum()
            
            results.append({
                "Period": f"{test_data.index[0].date()} to {test_data.index[-1].date()}",
                "Best Params": best_params,
                "Test Return": test_perf
            })
            
            current_idx += step
            
        # Format Output
        output = ["Walk Forward Analysis Results:"]
        total_ret = 0
        for r in results:
            output.append(f"[{r['Period']}] Params: {r['Best Params']}, Return: {r['Test Return']:.2%}")
            total_ret += r['Test Return']
            
        output.append(f"Total Walk Forward Return: {total_ret:.2%}")
        return "\n".join(output)
  • server.py:384-388 (registration)
    MCP tool registration of walk_forward_analysis (with run_backtest) in the 'Backtesting' category via register_tools function.
    register_tools(
        [run_backtest, walk_forward_analysis],
        "Backtesting"
    )
  • app.py:289-291 (registration)
    Inclusion of walk_forward_analysis in the Gradio UI toolbox under 'Backtesting' category (supports MCP server mode).
    "Risk Management": [portfolio_risk, var, max_drawdown, monte_carlo_simulation],
    "Backtesting": [run_backtest, walk_forward_analysis],
    "Technical Analysis": [compute_indicators, rolling_stats, get_technical_summary],
  • Type hints and docstring defining input parameters (symbol, dates, train/test months) and str output for the tool.
    def walk_forward_analysis(symbol: str, start_date: str = "2020-01-01", end_date: str = "2023-12-31", train_months: int = 12, test_months: int = 3) -> str:
        """
        Performs Walk Forward Analysis on MA Crossover.
        Optimizes (Fast, Slow) on Train, tests on Test.
        """
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions optimization and testing phases but lacks critical details: whether this is a read-only or mutating operation, computational intensity, rate limits, authentication needs, or what the output contains. The phrase 'Optimizes (Fast, Slow) on Train, tests on Test' implies a computational process but doesn't specify behavioral traits beyond the basic workflow.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise at just two sentences with zero wasted words. It's front-loaded with the main purpose and follows with implementation details. However, the brevity comes at the cost of completeness, making it somewhat under-specified rather than optimally concise.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of walk-forward analysis (a sophisticated financial modeling technique), 5 parameters with 0% schema coverage, no annotations, and an output schema (which helps but doesn't compensate for missing behavioral context), the description is inadequate. It mentions the analysis type and phases but omits critical context about parameters, behavioral characteristics, and usage guidance that would be essential for proper tool selection and invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, meaning none of the 5 parameters have descriptions in the schema. The tool description provides no information about any parameters - it doesn't mention 'symbol', date ranges, or train/test month parameters. With 0% coverage and 5 parameters, the description fails to compensate for the complete lack of parameter documentation in the structured schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool performs 'Walk Forward Analysis on MA Crossover' with optimization of 'Fast, Slow' parameters on training data and testing on test data. This specifies both the action ('Performs Walk Forward Analysis') and the resource/algorithm ('MA Crossover'), though it doesn't explicitly differentiate from sibling tools like 'run_backtest' or 'monte_carlo_simulation' beyond the specific analysis type.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'run_backtest' or 'monte_carlo_simulation' for similar financial analysis tasks. It mentions the optimization and testing phases but offers no context about prerequisites, appropriate scenarios, or exclusions for this specific analysis method.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/N-lia/MonteWalk'

If you have feedback or need assistance with the MCP directory API, please join our Discord server