Created
February 26, 2022 04:26
-
-
Save marcosan93/72c33f95822767d42f4ae9cd749d98da to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fbpTrainPredict(df, forecast_period): | |
""" | |
Uses FB Prophet and fits to a appropriately formatted DF. Makes a prediction N days into | |
the future based on given forecast period. Returns predicted values as a DF. | |
""" | |
# Setting up prophet | |
m = Prophet( | |
daily_seasonality=True, | |
yearly_seasonality=True, | |
weekly_seasonality=True | |
) | |
# Fitting to the prices | |
m.fit(df[['ds', 'y']]) | |
# Future DF | |
future = m.make_future_dataframe(periods=forecast_period) | |
# Predicting values | |
forecast = m.predict(future) | |
# Returning a set of predicted values | |
return forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']] | |
def runningFBP(prices, forecast_period, training_days): | |
""" | |
Runs Facebook Prophet to get predictions over a set period | |
of time. Uses FBP to train and predict every N days and gets the | |
price forecasts. | |
""" | |
# DF for the predicted values | |
pred_df = pd.DataFrame() | |
# Running the model each day | |
for i in tqdm(range(training_days, len(prices)+1)): | |
# Training and Predicting the last day on the forecast | |
forecast = fbpTrainPredict( | |
prices[i-training_days:i], | |
forecast_period | |
).tail(1) | |
# Adding the forecast predicted | |
pred_df = pred_df.append(forecast, ignore_index=True) | |
# Prepping for merge by converting date values to be the same type | |
pred_df['ds'] = pred_df['ds'].apply(lambda x: str(x)[:10]) | |
prices['ds'] = prices['ds'].apply(lambda x: str(x)[:10]) | |
# Shifting the forecasts back in order to compare it to the 'current' open values | |
pred_df[['yhat', 'yhat_lower', 'yhat_upper']] = pred_df[['yhat', 'yhat_lower', 'yhat_upper']].shift(-forecast_period) | |
# Merging with the prices DF in order to compare values for positions later | |
merge_df = prices[['ds', 'open']].merge( | |
pred_df, | |
on='ds', | |
how='outer' | |
).dropna().set_index('ds') | |
return merge_df |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment