-5
import backtrader as bt

class TestStrategy(bt.Strategy):

    def log(self, txt, dt=None):
        ''' Logging function fot this strategy'''
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        self.dataclose = self.datas[0].close
        self.sma50 = bt.indicators.SimpleMovingAverage(self.datas[0], period=50)
        self.sma200 = bt.indicators.SimpleMovingAverage(self.datas[0], period=200)
        self.macd = bt.indicators.MACD(self.data[0])
        self.bb = bt.indicators.BollingerBands(self.data[0])
        self.tema = bt.indicators.TripleExponentialMovingAverage(self.datas[0],period = 9)
        self.adx = bt.indicators.AverageDirectionalMovementIndex(self.datas[0])
        self.order = None



    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return

        # Check if an order has been completed
        # Attention: broker could reject order if not enough cash
        if order.status in [order.Completed]:
            if order.isbuy():
                self.log('BUY EXECUTED, %.2f' % order.executed.price)
            elif order.issell():
                self.log('SELL EXECUTED, %.2f' % order.executed.price)

            self.bar_executed = len(self)

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')

        # Write down: no pending order
        self.order = None

    def next(self):
        if self.order:  # Check for open order
            return

        if not self.position:  # Check for existing position
            if  self.adx[0] > 30 and  self.tema[0] > self.tema[-1] and self.sma200[0] > self.dataclose[0]:

                
                self.order = self.buy()
                self.curratr = self.atr

        else:
                    # Already in the market... we might sell
                    if self.adx[0] > 70  and self.tema[0] < self.tema[-1]:

                        # Keep track of the created order to avoid a 2nd order
                        self.order = self.sell()

import backtrader as bt
import matplotlib
import datetime
from stradegy import TestStrategy
import pandas as pd

cerebro = bt.Cerebro()                                                    
cerebro.broker.set_cash(100000)
df = pd.read_csv("nifty50.csv")
df['date'] = df['date'].str[:10]
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')


start_date = '2022-10-21'
end_date = '2022-10-21'
filtered_df = df[(df['date'] >= start_date) & (df['date'] <= end_date)]

# Convert the filtered DataFrame to a PandasData feed
data = bt.feeds.PandasData(
    dataname=filtered_df,
    datetime='date'
)
cerebro.adddata(data)
cerebro.addstrategy(TestStrategy)


print('starting value of the portfolio is %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('final portfolio value is as follows: %.2f'%cerebro.broker.getvalue())
cerebro.plot()

Output:

chaitanyasachdeva@chaitanyas-MacBook-Air-2 japenese candle stick % /Users/chaitanyasachdeva/opt/anaconda3/bin/python "/Users/chaitan yasachdeva/Desktop/japenese candle stick/Test_momenyum.py" starting value of the portfolio is 100000.00

However, after this point, the code is not functioning as expected. I am anticipating an output graph, but it is not being displayed.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • If you could focus your code in what you think is not working, that would be a great improvement. Check [how to ask a good question](https://stackoverflow.com/help/how-to-ask) for more info in how to help us help you – David Siret Marqués Jun 30 '23 at 08:39
  • 1
    I have removed from this question "Could you please provide more details about the code so that I can better assist you?". Who are you offering to assist? Is this not your code, and thus you need to provide your readers with more details? – halfer Jun 30 '23 at 21:58

1 Answers1

0

The code you provided is an implementation of a trading strategy using the backtrader library in Python. It defines a class called TestStrategy which inherits from bt.Strategy, the base class for creating trading strategies in backtrader.

The strategy uses various technical indicators such as Simple Moving Average (SMA), Moving Average Convergence Divergence (MACD), Bollinger Bands (BB), Triple Exponential Moving Average (TEMA), and Average Directional Movement Index (ADX) to make trading decisions.

Here's a breakdown of the key components of the code:

The log method is a helper function for logging messages during the strategy execution.

The init method is the initialization method where you define and initialize the indicators and other variables used in the strategy. In this case, it initializes indicators like sma50, sma200, macd, bb, tema, and adx.

The notify_order method is a callback function that is called whenever an order's status changes. It logs information about executed orders and handles order cancellations or rejections.

The next method is the main logic of the strategy and is called for each new trading bar or data point. It checks for open orders, existing positions, and executes buy or sell orders based on certain conditions. If there is an open position, it checks for conditions to sell.

Now, regarding the issue you mentioned about not seeing an output graph, it seems that you have only defined the strategy but haven't actually executed it. In order to see the output graph, you need to create a Cerebro instance, add the data feed (price data) to it, add your strategy to the Cerebro, and run the backtest.

dr dev
  • 11
  • 2