You are on page 1of 2

# import libraries

import pandas as pd

import talib

import yfinance as yf

# load crude oil futures data for past year

symbol = 'CL=F' # crude oil futures symbol

data = yf.download(symbol, start='2021-03-31', end='2022-03-31')

# calculate previous day high and low

data['prev_high'] = data['High'].shift(1)

data['prev_low'] = data['Low'].shift(1)

# calculate breakout/breakdown levels for next day

data['breakout_level'] = data['Open'].shift(1) + 0.25 * (data['prev_high'] - data['prev_low'])

data['breakdown_level'] = data['Open'].shift(1) - 0.25 * (data['prev_high'] - data['prev_low'])

# initialize variables

position = 0 # 0 = neutral, 1 = long, -1 = short

returns = [] # list to store returns for each trade

# implement loop to check for breakout/breakdown with good volume

for i in range(1, len(data) - 1):

if data['High'][i] > data['breakout_level'][i] and data['Volume'][i] > 1000:

# long position

if position != 1:

entry_price = data['Open'][i+1]

exit_price = data['Close'][i+1]

returns.append((exit_price - entry_price) / entry_price)

position = 1

elif data['Low'][i] < data['breakdown_level'][i] and data['Volume'][i] > 1000:

# short position

if position != -1:
entry_price = data['Open'][i+1]

exit_price = data['Close'][i+1]

returns.append((entry_price - exit_price) / entry_price)

position = -1

else:

# close position

if position == 1:

entry_price = data['Open'][i+1]

exit_price = data['Close'][i+1]

returns.append((exit_price - entry_price) / entry_price)

position = 0

elif position == -1:

entry_price = data['Open'][i+1]

exit_price = data['Close'][i+1]

returns.append((entry_price - exit_price) / entry_price)

position = 0

# calculate total returns for the year

total_returns = sum(returns)

print(f"Total returns for the year: {total_returns}")

# plot returns

import matplotlib.pyplot as plt

plt.plot(returns)

plt.xlabel('Trades')

plt.ylabel('Returns')

plt.show()

You might also like