Skip to content

Instantly share code, notes, and snippets.

@quantra-go-algo
Created May 13, 2025 07:46
Show Gist options
  • Save quantra-go-algo/f4d19210967d10c7440acf5cfd71be99 to your computer and use it in GitHub Desktop.
Save quantra-go-algo/f4d19210967d10c7440acf5cfd71be99 to your computer and use it in GitHub Desktop.
# Trading strategy formulation and backtesting
def backtest_strategy(final_data, initial_capital=10000, capital_deployed=0.2):
trade_log = []
for i in range(len(final_data) - 5):
prediction = final_data.iloc[i]['Predictions']
if prediction == 0 or np.isnan(prediction):
continue
direction = 'Long' if prediction > 0 else 'Short'
entry_price = final_data.iloc[i + 1]['Open']
exit_price = final_data.iloc[i + 5]['Close']
trade_return = (exit_price - entry_price) / entry_price if direction == 'Long' else (entry_price - exit_price) / entry_price
capital_change = capital_deployed * trade_return
trade_log.append({
'Signal_Day': i,
'Entry_Day': i + 1,
'Exit_Day': i + 5,
'Direction': direction,
'Entry_Price': entry_price,
'Exit_Price': exit_price,
'Return': trade_return,
'Capital_Change': capital_change
})
return pd.DataFrame(trade_log)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment