Loading

Robin
PythonFitting LTV

Calculate LT using Python fitting

9/7/2020 · 2 min read

When doing ROI calculations, I often need to estimate LTV and check whether the input-output ratio is positive. Sorting retention data and fitting a power function manually was tedious, so I looked for a way to automate LT fitting in Python.

With scipy and sympy, I wrote a script that fits retention and integrates to estimate LT:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from sympy import *
from scipy import integrate
 
# Extract LT for a date range
day_start = 20191220
day_finish = 20191223
 
# Load survival table
csv_path = '/Users/xx/Desktop/python查数据/韩国存活留存.csv'
d = pd.read_csv(csv_path)
 
k = d.loc[(d["first_day"] >= day_start) & (d["first_day"] <= day_finish)]
x_list = []
 
# Average retention over the period
for i in range(2, 21):
    a = (pd.to_numeric(k.iloc[:, i], errors='coerce')).mean()
    if a > 0:
        x_list.append(a)
 
length = len(x_list) + 1
y_list = []
for i in range(1, length):
    y_list.append(i)
 
x_list = [0.34, 0.25, 0.23, 0.21, 0.19, 0.17, 0.15, 0.13]
y_list = [1, 2, 3, 4, 5, 6, 7, 8]
 
dic = {'x': x_list, 'y': y_list}
frame = pd.DataFrame(dic)
x = frame['x']
y = frame['y']
 
def func(x, a, b):
    return a * pow(x, b)
 
popt, pcov = curve_fit(func, y, x)
a = popt[0]
b = popt[1]
 
def f(x):
    return a * x ** b
 
lv, err = integrate.quad(f, 1, 180)
print(lv)

Related posts