Files
strategy-lab/research/test1.ipynb

83 lines
2.5 KiB
Plaintext

{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import statsmodels.api as sm\n",
"\n",
"# Example time series data\n",
"np.random.seed(0)\n",
"dates = pd.date_range('2023-01-01', periods=100)\n",
"data = pd.Series(np.random.randn(100).cumsum(), index=dates)\n",
"\n",
"# Parameters\n",
"window_size = 20\n",
"\n",
"# Function to calculate rolling window linear regression\n",
"def rolling_linreg(series, window):\n",
" intercepts = []\n",
" slopes = []\n",
" for i in range(len(series) - window + 1):\n",
" y = series[i:i + window]\n",
" x = np.arange(window)\n",
" x = sm.add_constant(x)\n",
" model = sm.OLS(y, x).fit()\n",
" intercepts.append(model.params[0])\n",
" slopes.append(model.params[1])\n",
" return intercepts, slopes\n",
"\n",
"# Calculate rolling linear regression parameters\n",
"intercepts, slopes = rolling_linreg(data, window_size)\n",
"\n",
"# Create a DataFrame for plotting\n",
"rolling_dates = dates[window_size - 1:]\n",
"rolling_intercepts = pd.Series(intercepts, index=rolling_dates)\n",
"rolling_slopes = pd.Series(slopes, index=rolling_dates)\n",
"\n",
"# Plot the original data and the rolling linear regression\n",
"plt.figure(figsize=(14, 7))\n",
"plt.plot(data, label='Original Data')\n",
"for i in range(len(rolling_intercepts)):\n",
" start_date = rolling_dates[i] - pd.DateOffset(days=window_size-1)\n",
" end_date = rolling_dates[i]\n",
" plt.plot([start_date, end_date],\n",
" [rolling_intercepts[i], rolling_intercepts[i] + rolling_slopes[i] * (window_size - 1)],\n",
" color='red', alpha=0.5)\n",
"\n",
"plt.legend()\n",
"plt.title('Rolling Window Linear Regression')\n",
"plt.xlabel('Date')\n",
"plt.ylabel('Value')\n",
"plt.show()\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.11"
}
},
"nbformat": 4,
"nbformat_minor": 2
}