Skip to content

Instantly share code, notes, and snippets.

@marcosan93
Last active April 25, 2022 16:28
Show Gist options
  • Select an option

  • Save marcosan93/cc04bd899f220a1ccdd3be165bae2a42 to your computer and use it in GitHub Desktop.

Select an option

Save marcosan93/cc04bd899f220a1ccdd3be165bae2a42 to your computer and use it in GitHub Desktop.
def backtestStock(stock, pred_df, prices, price_history, interval_width):
# Adding positions to the forecast DF
positions = pred_df
# Getting forecast prophet positions
positions['fbp_positions'] = positions.apply(
lambda x: fbpPositions(x, short=True),
axis=1
)
# Buy and hold position
positions['buy_hold'] = 1
# Getting daily returns
log_returns = prices[['ds', 'Close']].set_index(
'ds'
).loc[positions.index].apply(np.log).diff()
# The positions to backtest (shifted ahead by 1 to prevent lookahead bias)
bt_positions = positions[[
'buy_hold',
'fbp_positions'
]].shift(1)
# The returns during the backtest
returns = bt_positions.multiply(
log_returns['Close'],
axis=0
)
# Inversing the log returns to get daily portfolio balance
performance = returns.cumsum().apply(
np.exp
).dropna().fillna(
method='ffill'
)
# Performing risk analysis
risk = riskAnalysis(performance, prices, price_history, interval_width)
return risk, performance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment