当前位置: 首页 > news >正文

量化交易 - Simple Regression 简单线性回归(机器学习)

目录

一、准备

二、导入包

三、构建数据

四、拟合

五、模型效果说明

六、手动公式计算验证

七、作图展示


一、准备

先安装一些库

# ! pip install matplotlib

# ! pip install statsmodels

二、导入包

import warnings
warnings.filterwarnings('ignore')
%matplotlib inlineimport numpy as np
import pandas as pdimport matplotlib.pyplot as plt
import seaborn as snsimport statsmodels.api as sm
from sklearn.linear_model import SGDRegressor
from sklearn.preprocessing import StandardScalersns.set_style('whitegrid')
pd.options.display.float_format = '{:,.2f}'.format

三、构建数据

x = np.linspace(-5, 50, 100)
y = 50 + 2 * x + np.random.normal(0, 20, size=len(x))
data = pd.DataFrame({'X': x, 'Y': y})
ax = data.plot.scatter(x='X', y='Y', figsize=(14, 6))
sns.despine()
plt.tight_layout()

四、拟合

$y = \beta_{0} + \beta_{1} X + \epsilon$

# OLS: Ordinary Least Squares
X = sm.add_constant(data['X'])
model = sm.OLS(data['Y'], X).fit()
print(model.summary())

打印模型结果:

                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      Y   R-squared:                       0.742
Model:                            OLS   Adj. R-squared:                  0.739
Method:                 Least Squares   F-statistic:                     281.8
Date:                Wed, 17 Sep 2025   Prob (F-statistic):           1.39e-30
Time:                        16:28:00   Log-Likelihood:                -435.02
No. Observations:                 100   AIC:                             874.0
Df Residuals:                      98   BIC:                             879.2
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const         53.8536      3.263     16.503      0.000      47.378      60.330
X              1.9826      0.118     16.786      0.000       1.748       2.217
==============================================================================
Omnibus:                        0.934   Durbin-Watson:                   2.030
Prob(Omnibus):                  0.627   Jarque-Bera (JB):                1.024
Skew:                          -0.213   Prob(JB):                        0.599
Kurtosis:                       2.746   Cond. No.                         47.6
==============================================================================Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

五、模型效果说明

R-squared (coefficient of determination)

0.8: The fitting is very good

0.5~0.8: Medium

< 0.5: Poor fitting

Adj-R ² is almost equal to R ² → no overfitting

Prob (F-statistic) < 0.05, good

A p-value less than 0.05 indicates statistical significance

六、手动公式计算验证

# β̂ = (XᵀX)⁻¹Xᵀy
# Calculate by hand using the OLS formula
beta = np.linalg.inv(X.T.dot(X)).dot(X.T.dot(y))
pd.Series(beta, index=X.columns)

const 53.85

X 1.98

dtype: float64

可以发现,和模型计算出来的差不多。(详细可见我的视频讲解)

七、作图展示

data['y-hat'] = model.predict()
data['residuals'] = model.resid
ax = data.plot.scatter(x='X', y='Y', c='darkgrey', figsize=(14,6))
data.plot.line(x='X', y='y-hat', ax=ax);
# for _, row in data.iterrows():
#     plt.plot((row.X, row.X), (row.Y, row['y-hat']), 'k-')    
sns.despine()
plt.tight_layout()

可以发现,基本上是和数据拟合一致的。

# Reference: https://github.com/stefan-jansen/machine-learning-for-trading/blob/main/07_linear_models/01_linear_regression_intro.ipynb


文章转载自:

http://AyEN0o9a.hjjfp.cn
http://XcVy1J2N.hjjfp.cn
http://PpXnD2Bp.hjjfp.cn
http://Pw1NZOa1.hjjfp.cn
http://c2zxDAAe.hjjfp.cn
http://mnHl9uJA.hjjfp.cn
http://JsgcxzwO.hjjfp.cn
http://7B7gfaes.hjjfp.cn
http://KjhOWb8x.hjjfp.cn
http://mnODc8Rs.hjjfp.cn
http://6viRMprg.hjjfp.cn
http://pD4qjWhM.hjjfp.cn
http://81qM22S6.hjjfp.cn
http://EbSNUNYk.hjjfp.cn
http://oCosLhZx.hjjfp.cn
http://qpcPrSRu.hjjfp.cn
http://38nQBZKg.hjjfp.cn
http://dWq8riVW.hjjfp.cn
http://pA6WlmlR.hjjfp.cn
http://1ADfNTCU.hjjfp.cn
http://klqcl2W1.hjjfp.cn
http://lVOi0ZnW.hjjfp.cn
http://8FlPPzS9.hjjfp.cn
http://wrfxzYRK.hjjfp.cn
http://QCxPhQjv.hjjfp.cn
http://lPhY7Ulj.hjjfp.cn
http://achxdu5g.hjjfp.cn
http://xxX2fWT6.hjjfp.cn
http://YTNNRsM1.hjjfp.cn
http://5IIh57FE.hjjfp.cn
http://www.dtcms.com/a/388622.html

相关文章:

  • Kubernetes控制器详解:从Deployment到CronJob
  • python 架构技术50
  • 第九周文件上传
  • MCP大白话理解
  • 【Qt】QJsonValue存储 int64 类型的大整数时,数值出现莫名其妙的变化
  • 【C语言】冒泡排序算法解析与实现
  • [GESP202309 三级] 进制判断
  • 【C++】const和static的用法
  • 箭头函数{}规则,以及隐式返回
  • brain.js构建训练神经网络
  • 开学季高效学习与知识管理技术
  • C++STL与字符串探秘
  • 【面试题】- 使用CompletableFuture实现多线程统计策略工厂模式
  • 打工人日报#20250917
  • LeetCode:12.最小覆盖字串
  • 【C++】 深入理解C++虚函数表与对象析构机制
  • C++ 中 ->和 . 操作符的区别
  • SQL CTE (Common Table Expression) 详解
  • 解决windows更新之后亮度条消失无法调节的问题
  • FPGA学习篇——Verilog学习译码器的实现
  • JavaScript Promise 终极指南 解决回调地狱的异步神器 99% 开发者都在用
  • AI智能体开发实战:从提示工程转向上下文工程的完整指南
  • jtag协议处理流程
  • 【LeetCode 每日一题】2749. 得到整数零需要执行的最少操作数
  • 《饿殍:明末千里行》Switch版试玩发布 3月13日发售
  • LeetCode:9.找到字符串中所有的字母异位词
  • Java获取淘宝商品详情数据的详细说明
  • PyTorch张量运算、索引与自动微分详解
  • Simulink变量优先级与管理策略
  • 大模型学习:什么是FastText工具