Skip to content

Instantly share code, notes, and snippets.

@marcosan93
Created January 14, 2022 17:23
Show Gist options
  • Save marcosan93/d387964d2550c68bdc280adacc67d9a2 to your computer and use it in GitHub Desktop.
Save marcosan93/d387964d2550c68bdc280adacc67d9a2 to your computer and use it in GitHub Desktop.
def backtestPerformanceVis(ticker, n_hours, training_hours, mov_avg, forecast_hours):
"""
Consolidates the previous functions that support the backtesting process.
"""
# Getting Price data
print("Getting price data...")
prices = getIntradayPrices(
crypto=ticker,
n_hours=n_hours,
training_hours=training_hours,
mov_avg=mov_avg
)
# Predicting over time
print("Running predictions...")
pred_df = runningFBP(
prices,
forecast_hours=forecast_hours,
training_hours=training_hours
)
# Adding sentiment positions to the prediction DF
print("Getting positions...")
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
# Random positions
positions['random_positions'] = random.choices(
[1,0,-1], k=len(positions)
)
# Getting returns each hour
print("Performing the backtest...")
log_returns = prices[['ds', 'open']].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',
'random_positions',
'fbp_positions'
]].shift(1)
# The returns during the backtest
returns = bt_positions.multiply(
log_returns['open'],
axis=0
)
# Inversing the log returns to get daily portfolio balance
performance = returns.cumsum().apply(
np.exp
).dropna().fillna(
method='ffill'
)
# Displaying the final balance of the portfolio
print("Final Performance:")
display(performance.tail(1))
# Visualizing results
fig = px.line(
performance,
x=performance.index,
y=performance.columns,
title='FBProphet, Buy&Hold, Random Positions',
labels={"value": "Portfolio Balance",
"index": "Date"}
)
return fig.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment