Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

import backtrader as bt

from datetime import datetime

# Define the strategy


class IchimokuStrategy(bt.Strategy):
params = (("stop_loss", 0.02), ("take_profit", 0.05))

def __init__(self):
self.ichimoku = bt.indicators.Ichimoku()
self.stop_loss_price = 0
self.take_profit_price = 0
self.take_profit_count = 0

def next(self):
if not self.position:
if self.ichimoku.tenkan > self.ichimoku.kijun:
self.buy()
self.stop_loss_price = self.data.close[0] * (1 -
self.params.stop_loss)
self.take_profit_price = self.data.close[0] * (1 +
self.params.take_profit)
self.take_profit_count = 0
else:
if self.ichimoku.tenkan < self.ichimoku.kijun:
self.sell()
elif self.data.close[0] < self.stop_loss_price:
self.sell()
elif self.data.close[0] > self.take_profit_price:
self.take_profit_count += 1
if self.take_profit_count >= 10:
self.sell()

# Define the data feed


data = bt.feeds.YahooFinanceData(dataname='GBPUSD', fromdate=datetime(2019,1,1),
todate=datetime(2020,1,1))

# Backtest the strategy


cerebro = bt.Cerebro()
cerebro.addstrategy(IchimokuStrategy)
cerebro.adddata(data)
cerebro.run()

# Print the final portfolio value


print("Final Portfolio Value:", cerebro.broker.getvalue())

You might also like