當RSI < 30 and MACD > Signal買進
當RSI > 70 or MACD < Signal 賣出
def backtest_strategy(df, initial_cash=10000):
cash = initial_cash
position = 0 # 持有幣數
trades = []
for i in range(len(df)):
price = df['close'].iloc[i]
rsi = df['RSI'].iloc[i]
macd = df['MACD'].iloc[i]
signal = df['Signal'].iloc[i]
# Buy Signal
if rsi < 30 and macd > signal and cash > 0:
position = cash / price # 全部資金買入
cash = 0
trades.append((df['timestamp'].iloc[i], "BUY", price))
# Sell Signal
elif (rsi > 70 or macd < signal) and position > 0:
cash = position * price # 全部賣出
position = 0
trades.append((df['timestamp'].iloc[i], "SELL", price))
# 最後持倉換成現金
if position > 0:
cash = position * df['close'].iloc[-1]
total_return = (cash - initial_cash) / initial_cash * 100
return trades, cash, total_return