Skip to content

Instantly share code, notes, and snippets.

@honake
Last active November 17, 2022 06:54
Show Gist options
  • Save honake/a683e577d8a4caeae5fa419c41b00580 to your computer and use it in GitHub Desktop.
Save honake/a683e577d8a4caeae5fa419c41b00580 to your computer and use it in GitHub Desktop.
Calculate the optimal Ad Stock
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def broadbent_adstock(grp, r):
adstock = np.zeros(len(grp))
adstock[0] = grp[0]
for i in range(1,len(grp)):
adstock[i] = grp[i] + r*adstock[i-1]
return adstock
def optimize_adstock(grp, sales):
corrs = []
rates = np.arange(0, 1.01, 0.01)
rmax = 0
corrmax = -1
for r in rates:
x = broadbent_adstock(grp.copy(), r)
y = sales
corr = np.corrcoef(x, y)[0][1]
corrs.append(corr)
if corr > corrmax:
rmax = r
corrmax = corr
plt.title("Correlation by Decay Rate")
plt.plot(rates, corrs, label="Correlation")
plt.xlabel("Decay Rate")
plt.ylabel("Correlation")
plt.legend()
plt.show()
print('忘却率が{0}のとき相関係数は最大値{1}'.format(rmax, corrmax))
@avinashpriyadarshi
Copy link

Hi Honake, I had been stuck on optimizing the adstock variable for some days. This is brilliant !!

@AlejandroRamirezLopez
Copy link

Thank you so much, this is exactly what I was looking for. Great job, thanks for helping out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment