Backtrader Framework
๐ฅ Vibe Prompt
"Create a Backtrader strategy with Golden Cross, add commission and slippage, run optimization on MA periods, and output performance metrics."
Basic Backtrader Strategy
import backtrader as bt
import yfinance as yf
import pandas as pd
class GoldenCrossStrategy(bt.Strategy):
params = (('short_period', 5), ('long_period', 20))
def __init__(self):
self.short_ma = bt.indicators.SMA(self.data.close, period=self.params.short_period)
self.long_ma = bt.indicators.SMA(self.data.close, period=self.params.long_period)
self.crossover = bt.indicators.CrossOver(self.short_ma, self.long_ma)
def next(self):
if self.crossover > 0: # Golden Cross
self.buy()
elif self.crossover < 0: # Death Cross
self.sell()
# Download data
df = yf.download('2330.TW', start='2023-01-01', end='2024-12-31')
data = bt.feeds.PandasData(dataname=df)
# Run backtest
cerebro = bt.Cerebro()
cerebro.adddata(data)
cerebro.addstrategy(GoldenCrossStrategy)
cerebro.broker.setcash(1000000.0)
cerebro.broker.setcommission(commission=0.001)
print(f'Starting Portfolio Value: ${cerebro.broker.getvalue():.2f}')
cerebro.run()
print(f'Final Portfolio Value: ${cerebro.broker.getvalue():.2f}')
cerebro.plot()
Performance Metrics
import backtrader.analyzers as btanalyzers
cerebro.addanalyzer(btanalyzers.SharpeRatio, riskfreerate=0.02)
cerebro.addanalyzer(btanalyzers.DrawDown)
cerebro.addanalyzer(btanalyzers.Returns)
results = cerebro.run()
strat = results[0]
print(f"Sharpe Ratio: {strat.analyzers.sharperatio.get_analysis()['sharperatio']:.2f}")
print(f"Max Drawdown: {strat.analyzers.drawdown.get_analysis()['max']['drawdown']:.2f}%")
Parameter Optimization
cerebro.optstrategy(GoldenCrossStrategy, short_period=range(5, 30, 5), long_period=range(20, 60, 10))
optimized_results = cerebro.run()
for result in optimized_results:
params = result[0].params
sharpe = result[0].analyzers.sharperatio.get_analysis().get('sharperatio', 0)
print(f"MA({params.short_period},{params.long_period}) Sharpe: {sharpe:.2f}")
Practice Exercise
๐ก Vibe Practice: Extend the backtest with multiple stocks, add stop-loss, take-profit, and compare optimized parameter sets.
Chapter Summary
- Understand core concepts and principles
- Master implementation methods and techniques
- Familiar with common issues and solutions
- Able to apply in real projects
Further Reading
- Official documentation and API references
- Open source examples on GitHub
- Technical books and online courses
- Community discussions and tech blogs
Implementation Example
Basic Example
# This section provides a complete implementation example
Steps
- Setup: Configure development environment
- Data: Prepare required data
- Implementation: Build core functionality
- Testing: Verify correctness
- Optimization: Improve performance
Common Errors
| Error Type | Cause | Solution | |------------|-------|----------| | Compilation | Syntax | Check code syntax | | Runtime | Environment | Verify dependencies installed | | Logic | Algorithm | Step-by-step debugging | | Performance | Efficiency | Use profilers |
Code Example
import sys
def main():
print("Hello, World!")
if __name__ == "__main__":
main()
References
- Official documentation
- API reference
- Open source examples
- Community discussions