# How to Simulate Futures Data Backtests in Entropy Alpha Strategy

## Step 5 - Let's long with target

To long the stocks with target. We need to find  –

• Entry – The price of the respective derivatives of April expiry at that time.
• Target – The high of the respective derivatives of April expiry at that time .

First Let’s create an instrument token fetching function –

```				```
instrumentList = pd.DataFrame(kite.instruments())

def get_insToken(tradesymbol,exchange="NFO"):
if(exchange=="NSE"):
if(tradesymbol=="NIFTY"):tradesymbol="NIFTY 50"
if(tradesymbol=="BANKNIFTY"):tradesymbol="NIFTY BANK"
#print(tradesymbol)
#print(exchange)
dataToken = instrumentList[(instrumentList['tradingsymbol'] == tradesymbol)&(instrumentList['exchange']==exchange)]
return dataToken.instrument_token.iloc[0]
```
```

Let’s get the entries –

```				```
#Price At The Particular Time

import datetime

# Create a function to get the price and high of a stock at a specific time
def get_stock_data(symbol, time):

# Define the start and end date
start_date = pd.Timestamp(time)
end_date = start_date + datetime.timedelta(minutes=5)

# Convert start and end date to string format
from_date = start_date.strftime('%Y-%m-%d %H:%M:%S')

# Fetch historical data for the stock
data = kite.historical_data(instrument_token=get_insToken(symbol+"23APRFUT"),
from_date=from_date,
to_date=from_date,
interval='minute')

# Return the price and high of the stock at that time
return data[0]['open']

# Add new columns to the DataFrame
df['price'] = ''

# Iterate over each row of the DataFrame
for index, row in df.iterrows():
# Get the stock symbol and triggered time
symbol = row['Stocks (new stocks are highlighted)']
time = row['Triggered at']

# Get the price and high of the stock at the triggered time
price= get_stock_data(symbol, time)

# Update the price and high columns
df.at[index, 'price'] = price

df
```
```

Note there is a high chance that you will get this following error –

```				```
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[14], line 34
31 time = row['Triggered at']
33 # Get the price and high of the stock at the triggered time
---> 34 price= get_stock_data(symbol, time)
36 # Update the price and high columns
37 df.at[index, 'price'] = price

Cell In[14], line 22, in get_stock_data(symbol, time)
16 data = kite.historical_data(instrument_token=get_insToken(symbol+"23ARFUT"),
17                              from_date=from_date,
18                              to_date=from_date,
19                              interval='minute')
21 # Return the price and high of the stock at that time
---> 22 return data[0]['open']

IndexError: list index out of range
```
```

It means that you may have overlooked the data fine-tuning process.

Specifically, you are currently backtesting intraday futures data for the current month. This is because the Zerodha KiteConnect API does not permit the retrieval of intraday data for derivative instruments from previous months. To rectify this, you should modify the portion of the code where “23APRFUT” is specified to match the current month you are conducting the backtest for.

Additionally, it is advisable to remove data corresponding to other months from the “entropy.csv” file to ensure accurate and relevant results. We did that programitcally in the line –

```				```
df_filtered = df.loc[df['Triggered at'].dt.strftime('%Y-%m') == '2023-04']
```
```

So make sure to change the date there to the current month You’re testing on.

Let’s get the targets –

```				```
def get_high_of_day(kite, df):
high_list = []
for i, row in df.iterrows():
# Get historical data for the trigger date of the stock
symbol = row['Stocks (new stocks are highlighted)']
data = kite.historical_data(instrument_token=get_insToken(symbol+"23APRFUT"),
from_date=row['Trigger Date'],
to_date=row['Trigger Date'],
interval='day')

# Get the high of the day
high = data[0]['high']
high_list.append(high)

df['high'] = high_list
return df

df=get_high_of_day(kite, df)
df
```
```

Now, few cosmetic surgeries.

1. We do not need the column named `Count.`
2. And, Let’s name the `"Stocks (new stocks are highlighted)"` to just `"Stocks"` ?
And, We get our trade log in a neat manner –
```				```
Triggered at	stocks	Trigger Date	Trigger Time	price	high
59	2023-04-03 10:01:00	MARUTI	2023-04-03	10:01:00	8558.15	8634.85
57	2023-04-03 10:04:00	M&M	2023-04-03	10:04:00	1178.5	1187.15
54	2023-04-03 10:10:00	ASHOKLEY	2023-04-03	10:10:00	142.6	143.30
53	2023-04-03 10:16:00	CHAMBLFERT	2023-04-03	10:16:00	270.65	273.90
51	2023-04-03 10:17:00	GMRINFRA	2023-04-03	10:17:00	42.8	43.95
50	2023-04-03 14:48:00	CROMPTON	2023-04-03	14:48:00	300.3	301.80
49	2023-04-05 10:48:00	TATACOMM	2023-04-05	10:48:00	1261.45	1284.40
...	...	...	...	...	...
5	2023-04-20 10:02:00	ICICIBANK	2023-04-20	10:02:00	897.05	901.00
4	2023-04-20 12:49:00	CUB	2023-04-20	12:49:00	132.7	134.35
3	2023-04-20 14:16:00	BAJAJ-AUTO	2023-04-20	14:16:00	4321	4336.60
2	2023-04-20 15:21:00	TATACONSUM	2023-04-20	15:21:00	705.7	706.50
1	2023-04-21 09:58:00	ASIANPAINT	2023-04-21	09:58:00	2854.75	2888.00
0	2023-04-21 10:07:00	APOLLOTYRE	2023-04-21	10:07:00	335.5	337.85
60 rows × 6 columns
```
```

That concludes part 1 of this chapter. In the next chapter,

1. We will simulate the trades in our trade log and,
2. We will checkout the trade performance and,
3. We will analyze that details with various popular trading metrics to get an overview of strength of our strategy.
×Close