# Load pandas
import pandas as pd
import talib as ta
import numpy as np
# Read CSV file into DataFrame df
df = pd.read_csv('EURUSD_Data.csv',parse_dates=['time'], index_col="time")
#df=df.loc['2021-11']
# Show dataframe
df.head()
#main strategy
dataframe = df
fee_rate= 0.0001 #0.01%
def rsi_bb(data=df,period_bb=30, period_rsi=9, n_std=2): #needed for optimizing
df['RSI'] = ta.RSI(data['close'], timeperiod=period_rsi)
df['upperbb'], data['middlebb'], data['lowerbb'] = ta.BBANDS(data["close"], timeperiod=period_bb)
df['close_yesterday'] = df.close.shift(1)
df['close_m2'] = df.close.shift(2)
df['lowerbb_y'] = df.lowerbb.shift(1)
df['middlebb_y'] = df.middlebb.shift(1)
df['RSI_y']=df.RSI.shift(1)
def long_position(dataframe):
dataframe.loc[
(
(dataframe['RSI_y'] < 35) &
(dataframe["close"] > dataframe['lowerbb']) &
(dataframe['close_yesterday'] < dataframe['lowerbb_y']) # confirmation
),
'buy'] = 1
return dataframe
def exit(dataframe):
dataframe.loc[
(
((dataframe["close"] > dataframe['middlebb'])&
(dataframe["close_yesterday"] < dataframe['middlebb_y'])) |
(dataframe['RSI'] > 75)
),
'exit_buy'] = 1
dataframe.loc[
(
((dataframe["close"] < dataframe['middlebb'])&
(dataframe["close_yesterday"] > dataframe['middlebb_y']))|
(dataframe['RSI'] > 35)
),
'exit_sell'] = 1
return dataframe
def short_position(dataframe):
dataframe.loc[
(
(dataframe['RSI_y'] > 65) &
(dataframe["close"] < dataframe['upperbb'])&
(dataframe['close_yesterday'] > dataframe['upperbb'])
),
'sell'] = 1
return dataframe
dataframe.fillna(0, inplace=True)
# بعد از بک1 تست و اپتیمایز همین استراتژی میشه یه اندیکاتور دیگه هم اضافه کرد برای بهبود استراتژی
import matplotlib.pyplot as plt
# test
Profit_array=np.array([[0,0,0]])
#for l in [9,14,22,34]:
l=14
for k in range (10):
rsi_bb(df,period_bb=30,period_rsi=14)
long_position(df)
exit(df)
short_position(df)
stoploss=0.0005
df["stoploss_buy"] = df['close'] * (1-stoploss) * df['buy']
df["stoploss_sell"] = df['close'] * (1+stoploss) * df['sell']
riskratio=(k+4) #min
pos_now=False # False: close position, True: open position
pos_type=False # True: there is an open long position, False: there is an open short position
positions=np.array([[0,0]])
stop_pos=0
for i in df.index:
if pos_now == False:
if df.loc[i].buy==1:
reward=(df.loc[i].middlebb-df.loc[i].close)/df.loc[i].close
rr=reward/stoploss
# print("long",rr)
if rr>riskratio:
positions = np.append(positions,[np.array([i,1])],axis= 0)
pos_type=True
pos_now=True
stop_pos=float(df.loc[i].stoploss_buy)
elif df.loc[i].sell==1:
reward=(-df.loc[i].middlebb+df.loc[i].close)/df.loc[i].close
rr=reward/stoploss
# print('short',rr)
if rr>riskratio:
positions = np.append(positions,[np.array([i,2])],axis= 0)
pos_now=True
pos_type=False
stop_pos=float(df.loc[i].stoploss_sell)
elif pos_now == True:
if pos_type==True:
if df.loc[i].close<stop_pos:
positions = np.append(positions,[np.array([i,-1])],axis= 0)
pos_now=False
if df.loc[i].exit_buy ==1:
positions = np.append(positions,[np.array([i,-1])],axis= 0)
pos_now=False
elif pos_type==False:
if df.loc[i].close>stop_pos:
positions = np.append(positions,[np.array([i,-2])],axis= 0)
pos_now=False
if df.loc[i].exit_sell ==1:
positions = np.append(positions,[np.array([i,-2])],axis= 0)
print()
pos_now=False
long_idx=[]
short_idx=[]
end_long_idx=[]
end_short_idx=[]
for i in range(np.shape(positions)[0]):
if positions[i][1]==1:
long_idx=np.append(long_idx,positions[i][0])
elif positions[i][1]==2:
short_idx=np.append(short_idx,positions[i][0])
elif positions[i][1]==-1:
end_long_idx=np.append(end_long_idx,positions[i][0])
elif positions[i][1]==-2:
end_short_idx=np.append(end_short_idx,positions[i][0])
profit = [0] * ((np.shape(long_idx)[0]-1)+np.shape(short_idx)[0])
for i in (range(np.shape(long_idx)[0]-1)):
start_p=df.loc[long_idx[i]].close
close_p=df.loc[end_long_idx[i]].close
prf=-fee_rate+float((1+(close_p-start_p)/start_p))
profit[i]=prf
for i in (range(np.shape(short_idx)[0])):
start_p=df.loc[short_idx[i]].close
close_p=df.loc[end_short_idx[i]].close
prf=-fee_rate+float((1+(-close_p+start_p)/start_p))
profit[i+np.shape(long_idx)[0]-1]=prf
profit_net=np.prod(profit)
Profit_array=np.append(Profit_array,[np.array([l,riskratio,profit_net])],axis= 0)
print("all positions", np.shape(end_long_idx)+ np.shape(end_short_idx))
print("final profit for if min riskratio= ",riskratio,"and rsi_period=",l," = ",profit_net)
if k==4:
plt.figure(figsize = (20,8))
plt.plot(df['close'],alpha=0.25)
plt.scatter(long_idx, df.loc[long_idx]["close"], marker = '^', color='green')
plt.scatter(short_idx, df.loc[short_idx]["close"], marker = 'v', color='red')
plt.scatter(end_long_idx, df.loc[end_long_idx]["close"], marker = '+', color='m')
plt.scatter(end_short_idx, df.loc[end_short_idx]["close"], marker = '+', color='m')
#plt.axis(['2021-05' '2021-07' 1.2 1.3])
plt.show()
print(Profit_array)