{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "033fbade",
   "metadata": {},
   "source": [
    "# 定价策略与价格弹性\n",
    "\n",
    "对应案例: [定价谈判](/docs/case-studies/marketing/pricing-negotiation-case/)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "308bd4df",
   "metadata": {},
   "source": [
    "## 1. 模拟价格实验数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9b1623e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np, pandas as pd, matplotlib.pyplot as plt\n",
    "from sklearn.linear_model import LinearRegression\n",
    "np.random.seed(42)\n",
    "n=500\n",
    "prices=np.linspace(9.9,49.9,5)\n",
    "demand_base=1000-np.linspace(0,600,5)\n",
    "price_expand=np.repeat(prices,100)+np.random.normal(0,2,500)\n",
    "demand=np.repeat(demand_base,100)+np.random.normal(0,50,500)\n",
    "demand=np.maximum(demand,10)\n",
    "df=pd.DataFrame({'price':price_expand,'quantity':demand})\n",
    "df['revenue']=df['price']*df['quantity']\n",
    "print(f'Price range: {df.price.min():.1f}-{df.price.max():.1f}')\n",
    "print(f'Quantity range: {df.quantity.min():.0f}-{df.quantity.max():.0f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00cc6270",
   "metadata": {},
   "source": [
    "## 2. 价格弹性估计"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a139b24b",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_log=np.log(df[['price']]); y_log=np.log(df['quantity'])\n",
    "lr=LinearRegression().fit(X_log,y_log)\n",
    "elasticity=lr.coef_[0]\n",
    "print(f'Price elasticity: {elasticity:.3f}')\n",
    "print(f'Revenue-max price (guess): ${df.price.mean()*(1-1/elasticity):.2f}')\n",
    "# Plot\n",
    "plt.figure(figsize=(10,5))\n",
    "for p in [9.9,19.9,29.9,39.9,49.9]:\n",
    "    m=abs(df['price']-p)<3\n",
    "    plt.scatter(df.loc[m,'price'],df.loc[m,'quantity'],alpha=0.5,label=f'${p:.0f}')\n",
    "plt.xlabel('Price'); plt.ylabel('Quantity'); plt.legend(); plt.title('Demand Curve')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0abddf71",
   "metadata": {},
   "source": [
    "## 3. 收入优化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9eaf2e98",
   "metadata": {},
   "outputs": [],
   "source": [
    "p_range=np.linspace(5,60,200)\n",
    "q_pred=np.exp(lr.predict(np.log(p_range.reshape(-1,1))))\n",
    "rev=p_range*q_pred\n",
    "opt_idx=np.argmax(rev)\n",
    "print(f'Optimal price: ${p_range[opt_idx]:.2f}')\n",
    "print(f'Expected quantity: {q_pred[opt_idx]:.0f}')\n",
    "print(f'Expected revenue: ${rev[opt_idx]:.0f}')\n",
    "# Plot\n",
    "fig,ax1=plt.subplots(figsize=(10,5))\n",
    "ax1.plot(p_range,q_pred,'b-',label='Demand')\n",
    "ax1.set_xlabel('Price'); ax1.set_ylabel('Quantity',color='b')\n",
    "ax2=ax1.twinx()\n",
    "ax2.plot(p_range,rev,'r-',label='Revenue')\n",
    "ax2.set_ylabel('Revenue',color='r')\n",
    "ax2.axvline(p_range[opt_idx],color='gray',ls='--',label=f'Opt=${p_range[opt_idx]:.2f}')\n",
    "ax1.legend(loc=2); ax2.legend(loc=1); plt.title('Price Optimization')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b444a101",
   "metadata": {},
   "source": [
    "---\n",
    "*更多分析见 [案例文档](/docs/case-studies/marketing/pricing-negotiation-case/)*"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.10.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
