2025-05-28 22:37:53 +08:00

273 lines
9.2 KiB
Python

#!/usr/bin/env python3
"""
Basic Usage Example for IncrementalTrader
This example demonstrates the basic usage of the IncrementalTrader framework
for testing trading strategies.
"""
import pandas as pd
from IncrementalTrader import (
MetaTrendStrategy, BBRSStrategy, RandomStrategy,
IncTrader, IncBacktester, BacktestConfig
)
def basic_strategy_usage():
"""Demonstrate basic strategy usage with live data processing."""
print("=== Basic Strategy Usage ===")
# Create a strategy
strategy = MetaTrendStrategy("metatrend", params={
"timeframe": "15min",
"supertrend_periods": [10, 20, 30],
"supertrend_multipliers": [2.0, 3.0, 4.0],
"min_trend_agreement": 0.6
})
# Create trader
trader = IncTrader(
strategy=strategy,
initial_usd=10000,
stop_loss_pct=0.03,
take_profit_pct=0.06,
fee_pct=0.001
)
# Simulate some price data (in real usage, this would come from your data source)
sample_data = [
(1640995200000, (46000, 46500, 45800, 46200, 1000)), # timestamp, (O,H,L,C,V)
(1640995260000, (46200, 46800, 46100, 46600, 1200)),
(1640995320000, (46600, 47000, 46400, 46800, 1100)),
(1640995380000, (46800, 47200, 46700, 47000, 1300)),
(1640995440000, (47000, 47400, 46900, 47200, 1150)),
# Add more data points as needed...
]
print(f"Processing {len(sample_data)} data points...")
# Process data points
for timestamp, ohlcv in sample_data:
signal = trader.process_data_point(timestamp, ohlcv)
# Log significant signals
if signal.signal_type != 'HOLD':
print(f"Signal: {signal.signal_type} at price {ohlcv[3]} (confidence: {signal.confidence:.2f})")
# Get results
results = trader.get_results()
print(f"\nFinal Portfolio Value: ${results['final_portfolio_value']:.2f}")
print(f"Total Return: {results['total_return_pct']:.2f}%")
print(f"Number of Trades: {len(results['trades'])}")
def basic_backtesting():
"""Demonstrate basic backtesting functionality."""
print("\n=== Basic Backtesting ===")
# Note: In real usage, you would have a CSV file with historical data
# For this example, we'll create sample data
create_sample_data_file()
# Configure backtest
config = BacktestConfig(
initial_usd=10000,
stop_loss_pct=0.03,
take_profit_pct=0.06,
start_date="2024-01-01",
end_date="2024-01-31",
fee_pct=0.001,
slippage_pct=0.0005
)
# Create backtester
backtester = IncBacktester()
# Test MetaTrend strategy
print("Testing MetaTrend Strategy...")
results = backtester.run_single_strategy(
strategy_class=MetaTrendStrategy,
strategy_params={"timeframe": "15min"},
config=config,
data_file="sample_data.csv"
)
# Print results
performance = results['performance_metrics']
print(f"Total Return: {performance['total_return_pct']:.2f}%")
print(f"Sharpe Ratio: {performance['sharpe_ratio']:.2f}")
print(f"Max Drawdown: {performance['max_drawdown_pct']:.2f}%")
print(f"Win Rate: {performance['win_rate']:.2f}%")
print(f"Total Trades: {performance['total_trades']}")
def compare_strategies():
"""Compare different strategies on the same data."""
print("\n=== Strategy Comparison ===")
# Ensure we have sample data
create_sample_data_file()
# Configure backtest
config = BacktestConfig(
initial_usd=10000,
start_date="2024-01-01",
end_date="2024-01-31"
)
# Strategies to compare
strategies = [
(MetaTrendStrategy, {"timeframe": "15min"}, "MetaTrend"),
(BBRSStrategy, {"timeframe": "15min"}, "BBRS"),
(RandomStrategy, {"timeframe": "15min", "seed": 42}, "Random")
]
backtester = IncBacktester()
results_comparison = {}
for strategy_class, params, name in strategies:
print(f"Testing {name} strategy...")
results = backtester.run_single_strategy(
strategy_class=strategy_class,
strategy_params=params,
config=config,
data_file="sample_data.csv"
)
results_comparison[name] = results['performance_metrics']
# Print comparison
print("\n--- Strategy Comparison Results ---")
print(f"{'Strategy':<12} {'Return %':<10} {'Sharpe':<8} {'Max DD %':<10} {'Trades':<8}")
print("-" * 50)
for name, performance in results_comparison.items():
print(f"{name:<12} {performance['total_return_pct']:<10.2f} "
f"{performance['sharpe_ratio']:<8.2f} {performance['max_drawdown_pct']:<10.2f} "
f"{performance['total_trades']:<8}")
def create_sample_data_file():
"""Create a sample data file for backtesting examples."""
import numpy as np
from datetime import datetime, timedelta
# Generate sample OHLCV data
start_date = datetime(2024, 1, 1)
end_date = datetime(2024, 1, 31)
# Generate timestamps (1-minute intervals)
timestamps = []
current_time = start_date
while current_time <= end_date:
timestamps.append(int(current_time.timestamp() * 1000))
current_time += timedelta(minutes=1)
# Generate realistic price data with some trend
np.random.seed(42) # For reproducible results
initial_price = 45000
prices = [initial_price]
for i in range(1, len(timestamps)):
# Add some trend and random walk
trend = 0.0001 * i # Slight upward trend
random_change = np.random.normal(0, 0.002) # 0.2% volatility
new_price = prices[-1] * (1 + trend + random_change)
prices.append(new_price)
# Generate OHLCV data
data = []
for i, (timestamp, close) in enumerate(zip(timestamps, prices)):
# Generate realistic OHLC from close price
volatility = close * 0.001 # 0.1% intrabar volatility
high = close + np.random.uniform(0, volatility)
low = close - np.random.uniform(0, volatility)
open_price = low + np.random.uniform(0, high - low)
# Ensure OHLC consistency
high = max(high, open_price, close)
low = min(low, open_price, close)
volume = np.random.uniform(800, 1500) # Random volume
data.append({
'timestamp': timestamp,
'open': round(open_price, 2),
'high': round(high, 2),
'low': round(low, 2),
'close': round(close, 2),
'volume': round(volume, 2)
})
# Save to CSV
df = pd.DataFrame(data)
df.to_csv("sample_data.csv", index=False)
print(f"Created sample data file with {len(data)} data points")
def indicator_usage_example():
"""Demonstrate how to use indicators directly."""
print("\n=== Direct Indicator Usage ===")
from IncrementalTrader.strategies.indicators import (
MovingAverageState, RSIState, SupertrendState, BollingerBandsState
)
# Initialize indicators
sma_20 = MovingAverageState(period=20)
rsi_14 = RSIState(period=14)
supertrend = SupertrendState(period=10, multiplier=3.0)
bb = BollingerBandsState(period=20, std_dev=2.0)
# Sample price data
prices = [100, 101, 99, 102, 98, 103, 97, 104, 96, 105,
94, 106, 93, 107, 92, 108, 91, 109, 90, 110]
print("Processing price data with indicators...")
print(f"{'Price':<8} {'SMA20':<8} {'RSI14':<8} {'ST Signal':<10} {'BB %B':<8}")
print("-" * 50)
for i, price in enumerate(prices):
# Update indicators
sma_20.update(price)
rsi_14.update(price)
# For Supertrend, we need OHLC data (using price as close, with small spread)
high = price * 1.001
low = price * 0.999
supertrend.update_ohlc(high, low, price)
bb.update(price)
# Print values when indicators are ready
if i >= 19: # After warmup period
sma_val = sma_20.get_value() if sma_20.is_ready() else "N/A"
rsi_val = rsi_14.get_value() if rsi_14.is_ready() else "N/A"
st_signal = supertrend.get_signal() if supertrend.is_ready() else "N/A"
bb_percent_b = bb.get_percent_b(price) if bb.is_ready() else "N/A"
print(f"{price:<8.2f} {sma_val:<8.2f} {rsi_val:<8.2f} "
f"{st_signal:<10} {bb_percent_b:<8.2f}")
if __name__ == "__main__":
"""Run all examples."""
print("IncrementalTrader - Basic Usage Examples")
print("=" * 50)
try:
# Run examples
basic_strategy_usage()
basic_backtesting()
compare_strategies()
indicator_usage_example()
print("\n" + "=" * 50)
print("All examples completed successfully!")
print("\nNext steps:")
print("1. Replace sample data with your own historical data")
print("2. Experiment with different strategy parameters")
print("3. Create your own custom strategies")
print("4. Use parameter optimization for better results")
except Exception as e:
print(f"Error running examples: {e}")
print("Make sure you have the IncrementalTrader module properly installed.")