Quickstart

Quickstart

Get started with alphabench in minutes. These examples show how to transform natural language into production-ready trading strategies.

Natural Language Strategy Research

Describe your trading strategy in plain English and get backtested results instantly:

import alphabench
 
# Describe your strategy in plain English
result, error = alphabench.chat(
    "Create a mean reversion strategy for large-cap Indian stocks. "
    "Buy when price drops 10% below 50-day MA with RSI < 30. "
    "Exit at 5% profit or 3% loss. 10 lakh starting capital."
)
 
if error:
    print(f"Error: {error}")
else:
    print(f"Strategy ID: {result['strategy_id']}")
    print(f"Total Return: {result['metadata']['backtest_results']['total_return']}")
    print(f"Sharpe Ratio: {result['metadata']['backtest_results']['sharpe_ratio']}")
    print(f"\nGenerated Code:\n{result['code']}")

Programmatic Backtesting

Execute backtests with your own signals for complete control:

import alphabench
 
# Execute backtest with your own signals
result = alphabench.execute_backtest(
    backtest_id="momentum_reliance_001",
    identifiers=["NSE:RELIANCE:738561", "NSE:TCS:694273"],
    from_date="2025-01-01T09:15:00Z",
    to_date="2025-01-31T15:30:00Z",
    signals=[
        {
            "identifier": "NSE:RELIANCE:738561",
            "action": "BUY",
            "quantity": 100,
            "order_type": "MARKET",
            "price": 2450.50,
            "timestamp": "2025-01-02T10:30:00Z"
        },
        {
            "identifier": "NSE:RELIANCE:738561",
            "action": "SELL",
            "quantity": 100,
            "order_type": "MARKET",
            "price": 2650.75,
            "timestamp": "2025-01-20T14:30:00Z"
        }
    ],
    configuration={
        "initial_capital": 1000000.00,
        "commission_per_trade": 10.00,
        "commission_pct": 0.001
    }
)
 
print(f"Total P&L: ₹{result['portfolio']['total_pnl']}")
print(f"Win Rate: {result['metrics']['win_rate']}")

Retrieve Results

Get the status and complete results of your backtests:

# Get backtest status
status = alphabench.get_backtest_status("momentum_reliance_001")
print(f"Status: {status['status']}")
 
# Get complete results with metrics
results = alphabench.get_backtest_results("momentum_reliance_001")
print(f"Final P&L: ₹{results['portfolio']['total_pnl']}")
print(f"Total Trades: {results['metrics']['total_trades']}")

Advanced Strategy Examples

Momentum Strategy

result, error = alphabench.chat(
    "Create a momentum strategy on Nifty 50 stocks. "
    "Buy top 5 performers over 20-day period. "
    "Hold for 10 days, then rebalance. "
    "Stop loss at 5%, take profit at 15%. "
    "5 lakh capital, equal weight allocation."
)

Mean Reversion Strategy

result, error = alphabench.chat(
    "Build a pairs trading strategy between Infosys and TCS. "
    "Enter when spread > 2 standard deviations. "
    "Exit when spread returns to mean. "
    "Maximum holding period 30 days. "
    "2 lakh capital per pair."
)

RSI-Based Strategy

result, error = alphabench.chat(
    "RSI divergence strategy on mid-cap stocks. "
    "Buy when RSI < 30 and price makes higher low. "
    "Sell when RSI > 70 and price makes lower high. "
    "Use 14-period RSI, 3 lakh capital."
)

Custom Configuration

Fine-tune your backtests with custom parameters:

# Custom backtest with advanced settings
result = alphabench.execute_backtest(
    backtest_id="custom_strategy_001",
    identifiers=["NSE:HDFC:738560", "NSE:ICICI:738561"],
    from_date="2024-01-01T09:15:00Z",
    to_date="2024-12-31T15:30:00Z",
    signals=[
        {
            "identifier": "NSE:HDFC:738560",
            "action": "BUY",
            "quantity": 50,
            "order_type": "LIMIT",
            "price": 1600.00,
            "timestamp": "2024-01-02T10:00:00Z"
        }
    ],
    configuration={
        "initial_capital": 500000.00,
        "commission_per_trade": 20.00,
        "commission_pct": 0.002,
        "slippage_pct": 0.001,
        "benchmark": "NSE:NIFTY50:INDEX",
        "risk_free_rate": 0.06
    }
)

Working with Multiple Strategies

Compare and analyze multiple strategies:

strategies = [
    "Simple MA crossover on Nifty 50",
    "RSI momentum strategy",
    "Mean reversion on banking stocks"
]
 
results = []
for strategy_desc in strategies:
    result, error = alphabench.chat(
        f"{strategy_desc}. 1 lakh capital, standard settings."
    )
    if not error:
        results.append({
            'description': strategy_desc,
            'strategy_id': result['strategy_id'],
            'total_return': result['metadata']['backtest_results']['total_return'],
            'sharpe_ratio': result['metadata']['backtest_results']['sharpe_ratio']
        })
 
# Sort by Sharpe ratio
results.sort(key=lambda x: x['sharpe_ratio'], reverse=True)
 
for result in results:
    print(f"{result['description']}: Sharpe {result['sharpe_ratio']:.2f}")

Error Handling

Always handle errors gracefully:

from alphabench.exceptions import (
    AuthenticationError,
    InsufficientCreditsError,
    BacktestNotFoundError
)
 
try:
    result, error = alphabench.chat("my trading strategy")
    if error:
        print(f"Strategy error: {error}")
    else:
        print(f"Strategy created: {result['strategy_id']}")
 
except AuthenticationError:
    print("Invalid API key - check your ALPHABENCH_API_KEY")
except InsufficientCreditsError as e:
    print(f"Need {e.required - e.available} more credits")
except BacktestNotFoundError:
    print("Backtest not found - check the ID")

Next Steps

Now that you've seen alphabench in action:

  1. Installation - Set up your development environment
  2. Features - Learn about all capabilities
  3. Advanced Usage - Error handling and custom configurations
  4. About - Philosophy and roadmap

Visit alphabench.in (opens in a new tab) to get your API key and start building strategies.