Skip to content

Instantly share code, notes, and snippets.

@brockmanmatt
Created October 13, 2019 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brockmanmatt/f6e7a9be50a7490d466b2aa3a86115bc to your computer and use it in GitHub Desktop.
Save brockmanmatt/f6e7a9be50a7490d466b2aa3a86115bc to your computer and use it in GitHub Desktop.
fig, axs = plt.subplots(1, 5, sharey=True, gridspec_kw={'wspace': 0})
fig.set_size_inches(16,6)
x = y = 0
for issue in myCountries:
train_l = len(time_series)-5
selected_series = time_series.copy()
s_model = SARIMAX(endog = selected_series[[issue]][:train_l],
exog = selected_series[[x for x in selected_series.columns if x != issue]][:train_l],
order=(3,1,1), seasonal_order=(1,0,1,7)).fit()
f_ru = selected_series[[issue]].copy()[1:]
f_ru.columns = ["actual"]
f_ru["predicted"] = s_model.predict(end=datetime.datetime(2019, 10, 6), endog = selected_series[[issue]][-5:],exog = selected_series[[x for x in selected_series.columns if x != issue]][-5:],
dynamic= False)
testing = f_ru.copy()
testing["error"] = np.abs((testing["actual"] - testing["predicted"]) / testing["actual"])
fit = round(testing[testing["actual"] != 0].error.mean()*100)
testing2 = testing[-5:]
fit_p = round(testing2[testing2["actual"] != 0].error.mean()*100)
search_df.loc[issue, "all_topic_model"] = fit
search_df.loc[issue, "all_topic_predicted"] = fit_p
f_ru["actual"].plot(title="{}\nMAPE: test: {}% model: {}%".format(issue, fit_p, fit), ax=axs[x])
f_ru["predicted"][:-5].plot(color="orange", label="predicted: Train", ax=axs[x])
f_ru["predicted"][-6:].plot(color="red", label="predicted: Test", ax=axs[x])
#Not plotting the rest of the series; too much noise
#selected_series[[x for x in selected_series.columns if x != issue]].plot(style=":",ax=axs[x])
if x ==0:
handles, labels = axs[0].get_legend_handles_labels()
#axs[x].get_legend().remove()
x+=1
#Pandas is a pain with legends outside the main image
#This extends the fig by .2 to the right, fills in everything to the left
#then sticks the legend outside the center right box (I think)
fig.subplots_adjust(right=.2)
fig.tight_layout()
lgd = fig.legend(handles, labels, loc='center right', bbox_to_anchor=(1.05,.5))
axs[0].set_ylabel("% Search or # Articles")
fig.suptitle("Model and Predicted Google Search Results", y=1.05)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment