Skip to content

Instantly share code, notes, and snippets.

@marcosan93
Last active April 25, 2022 16:30
Show Gist options
  • Save marcosan93/09c20cbbfd90b01a2036a2a0f4b6b518 to your computer and use it in GitHub Desktop.
Save marcosan93/09c20cbbfd90b01a2036a2a0f4b6b518 to your computer and use it in GitHub Desktop.
def backtestStockAndPredict(stock, n_days_lst, training_days_lst, mov_avg_lst,
forecast_period_lst, fbp_intervals,stop_early=True, visualize=True):
# Printing the stock
print(f"\nBacktesting {stock}. . .")
# Tuning parameters for stock
results = parameterTuning(
stock,
n_days_lst,
training_days_lst,
mov_avg_lst,
forecast_period_lst,
fbp_intervals,
stop_early=stop_early
)
if results['optimumResultFound']==False:
print(f"\t***No optimum params found for {stock}***")
# Optimum Parameters
opt_params = results['optimumParamLst'][-1]
# Visualizing last (best) result
if visualize:
# Getting the performance DF
performance = opt_params['bt_performance']
# Visual of the backtest
fig = px.line(
performance,
x=performance.index,
y=performance.columns,
title=f'FBProphet vs Buy&Hold for {stock}',
labels={"value": "Portfolio Balance",
"index": "Date"}
)
fig.show()
# Retrieving prices with the given parameters
prices, price_history = getStockPrices(
stock,
n_days=opt_params['n_days'],
training_days=opt_params['training_days'],
mov_avg=opt_params['mov_avg']
)
# Run Prophet for current prediction
preds = fbpTrainPredict(
prices.tail(opt_params['training_days']),
opt_params['forecast_period'],
opt_params['interval_width']
).tail(1)
preds['Open'] = prices.tail(1)['Open'].values
# Getting forecast prophet positions
trade_decision = fbpPositions(preds.to_dict('records')[0], short=True)
trade_dict = {
1 : f"Buy {stock}",
0 : f"Exit {stock}/Do nothing",
-1: f"Short {stock}"
}
# Printing trade decision
print(trade_dict[trade_decision])
# Printing the optimum params
print("Best Optimum Parameters Found:\n", opt_params)
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment