Error running Backtest on marubozu lab

# Create dataframe for storing trades
trades = pd.DataFrame(columns = ['Entry_Date', 'Entry_Price', 'Exit_Date', 'Exit_Type', 'Exit_Price'])

# Initialise current position, number of trades, cumulative pnl to 0
current_position = 0
trade_num = 0
cum_pnl = 0

# Set exit flag to False
exit_flag = False

for index in range(len(data)):
    # Check if entry_signal is 1 and there is no open position (Step 3)
    if data['entry_signal'].iloc[index-1] == 1 and current_position == 0:
        
        # Set entry date and entry price (Step 3.1)
        entry_date = data.iloc[index].name
        entry_price = data['Open'].iloc[index]
        
        # Compute SL and TP for the trade (Step 3.2)
        stoploss, take_profit = exit_values(data, index, entry_price, 3)
        
        # Update current position to 1 (Step 3.3)
        current_position = 1
        
        # Increase number of trades by 1
        trade_num += 1   

        # Print trade details
        print("-"*30)
        print(f"Trade No: {trade_num} | Entry Date: {entry_date} | Entry Price: {entry_price}")           
     
    # Check if there is an open position of the given timestamp (Step 4)
    elif current_position == 1:
        
        # Exit the trade if any of the exit condition is met (Step 4.1)
        if data['Close'].iloc[index] < stoploss:
            exit_type = 'SL'
            exit_flag = True
            
        elif data['Close'].iloc[index] > take_profit:
            exit_type = 'TP'
            exit_flag = True         
 
        # Check if exit flag is true (Step 4.2)
        if exit_flag: 
            
            # Set exit date and exit price (Step 4.2.1)
            exit_date = data.iloc[index].name
            exit_price = data['Close'].iloc[index]
            
            # Calculate pnl for the trade (Step 4.2.2)
            trade_pnl = round(exit_price - entry_price,2)
            
            # Calculate cumulative pnl 
            cum_pnl = round(cum_pnl,2) + trade_pnl
            
            # Append the trade to trades dataframe (Step 4.2.3)
            trades = trades.append({'Entry_Date': entry_date, 'Entry_Price': entry_price, 
                                    'Exit_Date': exit_date, 'Exit_Type': exit_type, 
                                    'Exit_Price': exit_price, 'PnL': trade_pnl}, ignore_index=True)
            
            # Update current position to 0 and set exit flag to False (Step 4.2.4)
            current_position = 0
            exit_flag = False
            
            # Print trade details
            print(f"Trade No: {trade_num} | Exit Type: {exit_type} | Date: {exit_date} | Exit Price: {exit_price} | PnL: {trade_pnl} | Cum PnL: {round(cum_pnl,2)}")                              
            

=========
Errore code:"---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[6], line 10
      7 entry_price = data['Open'].iloc[index]
      9 # Compute SL and TP for the trade (Step 3.2)
---> 10 stoploss, take_profit = exit_values(data, index, entry_price, 3)
     12 # Update current position to 1 (Step 3.3)
     13 current_position = 1

NameError: name 'exit_values' is not defined"

 

Hello Pierre,



It seems that 'exit_values' is a function which has not been defined or called incorrectly. If you are running the notebook on local system, one alternative is to download the zip file at the end of the course. Unzip the file and run the required notebook. I believe then it should not give you any error.



Hope this helps.

Thank you. I was able to detect the issue( The function  def exit_values was not defined). After i defined it correctly  and ran, i am getting new error related to the .append. After some researches, it seems like append is deprecated. the suggestion is to use concat instead. Can you please help to fix the code?

Note: I am running it from my local machine. (It runs great from quantinsti cloud environment).

 

AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_16376\2877305305.py in ?()
     44             # Calculate cumulative pnl
     45             cum_pnl = round(cum_pnl,2) + trade_pnl
     46 
     47             # Append the trade to trades dataframe (Step 4.2.3)
---> 48             trades = trades.append({'Entry_Date': entry_date, 'Entry_Price': entry_price, 
     49                                     'Exit_Date': exit_date, 'Exit_Type': exit_type,
     50                                     'Exit_Price': exit_price, 'PnL': trade_pnl}, ignore_index=True)
     51 

D:\Anaconda\Lib\site-packages\pandas\core\generic.py in ?(self, name)
   5985             and name not in self._accessors
   5986             and self._info_axis._can_hold_identifiers_and_holds_name(name)
   5987         ):
   5988             return self[name]
-> 5989         return object.__getattribute__(self, name)

AttributeError: 'DataFrame' object has no attribute 'append'

Hello Pierre,



You are right as recent versions of Pandas library might not allow a dataframe to be "appended".



You could try to declare a new datframe as trades = pd.DataFrame() and then use the append function. That might work.



Or you can use the contact function in the following manner



trades_list =

trades_list.append({'Entry_Date': entry_date, 'Entry_Price': entry_price, 

                    'Exit_Date': exit_date, 'Exit_Type': exit_type,

                    'Exit_Price': exit_price, 'PnL': trade_pnl})



trades = pd.concat([trades, pd.DataFrame(trades_list)], ignore_index=True)



Of course, you will have to modify the arguments passed in the append function. 



Thanks for mentioning that the notebook runs in the QuantInsti cloud environment. If you want to set up a virtual environment which is similar to the QuantInsti cloud environment, you can set it up by following the steps mentioned in the following blog: Setting Up Python On Your System. The reason I mentioned is that if the local environment is same, then you might not have to debug the code as much and focus on the strategy more. Just thought of sharing it.



Hope this helps.

Thank you for your support. The second options worked and solved the issue. Please update the code  for future students who may have the same issue.

 

Hello Pierre,



Thank you for the confirmation. You are right when you say the code should be updated. However, we have seen that sometimes when certain libraries get updated, incompatibilities arise and we will run into the same issues again. This is why we created a virtual environment with specific versions of various libraries so that everything works in harmony.



But we will definitely take a look at the feasibility of updating the code and work on it accordingly.



In the meantime, happy learning.