{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8e18e9d8",
   "metadata": {},
   "source": [
    "# 客户终身价值建模\n",
    "\n",
    "对应案例: [CLV 建模](/docs/case-studies/marketing/clv-modeling-case/)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "155826e4",
   "metadata": {},
   "source": [
    "## 1. 模拟订阅数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cbc52751",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np, pandas as pd, matplotlib.pyplot as plt\n",
    "from lifetimes import BetaGeoFitter, GammaGammaFitter\n",
    "np.random.seed(42)\n",
    "n=1000\n",
    "df=pd.DataFrame({\n",
    "    'frequency':np.random.poisson(5,n).clip(0,30),\n",
    "    'recency':np.random.exponential(60,n).clip(1,365).astype(int),\n",
    "    'T':np.random.randint(90,365,n),\n",
    "    'monetary_value':np.random.lognormal(4,0.5,n).clip(10,500).round(2)\n",
    "})\n",
    "print(f'Customers: {len(df)}')\n",
    "print(df.describe().round(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80dac7ce",
   "metadata": {},
   "source": [
    "## 2. BG/NBD 模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8663b9e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "bgf=BetaGeoFitter(penalizer_coef=0.01)\n",
    "bgf.fit(df['frequency'],df['recency'],df['T'])\n",
    "print(bgf.summary)\n",
    "# 预测未来 30 天购买\n",
    "df['pred_purchases_30d']=bgf.conditional_expected_number_of_purchases_up_to_time(30,df['frequency'],df['recency'],df['T'])\n",
    "print(f'Avg predicted 30d purchases: {df[\"pred_purchases_30d\"].mean():.2f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4a57e9b",
   "metadata": {},
   "source": [
    "## 3. Gamma-Gamma 模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "da26952a",
   "metadata": {},
   "outputs": [],
   "source": [
    "returning=df[df['frequency']>0]\n",
    "ggf=GammaGammaFitter(penalizer_coef=0.01)\n",
    "ggf.fit(returning['frequency'],returning['monetary_value'])\n",
    "print(ggf.summary)\n",
    "df['pred_monetary']=ggf.conditional_expected_average_profit(df['frequency'],df['monetary_value'])\n",
    "df['CLV']=ggf.customer_lifetime_value(bgf,df['frequency'],df['recency'],df['T'],df['monetary_value'],time=12, discount_rate=0.01)\n",
    "print(f'Avg 12-month CLV: ${df[\"CLV\"].mean():.2f}')\n",
    "# Top/Bottom\n",
    "top=df.nlargest(5,'CLV')[['frequency','recency','T','monetary_value','CLV']]\n",
    "print('\\nTop 5 by CLV:')\n",
    "print(top)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a994229",
   "metadata": {},
   "source": [
    "## 4. CLV 分段"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c0e7be7b",
   "metadata": {},
   "outputs": [],
   "source": [
    "df['segment']=pd.qcut(df['CLV'],q=4,labels=['Low','Mid','High','VIP'])\n",
    "seg=df.groupby('segment',observed=True).agg(count=('CLV','count'),avg_CLV=('CLV','mean'),total_value=('CLV','sum'))\n",
    "print(seg.round(2))\n",
    "seg.plot.pie(y='total_value',labels=seg.index,autopct='%1.1f%%',figsize=(8,8),title='CLV by Segment')\n",
    "plt.ylabel(''); plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85969548",
   "metadata": {},
   "source": [
    "---\n",
    "*更多分析见 [案例文档](/docs/case-studies/marketing/clv-modeling-case/)*"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.10.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
