# 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"