기본 콘텐츠로 건너뛰기

라벨이 regression인 게시물 표시

[matplotlib]quiver()함수

[stock]선형회귀 모델에 의한 주가 예측

선형회귀 모델에 의한 주가 예측 sklearn.linear_model.LinearRegression() 클래스를 사용합니다. import numpy as np import pandas as pd import pandas_ta as ta import matplotlib.pyplot as plt import FinanceDataReader as fdr import matplotlib.pyplot as plt from scipy import stats from sklearn.model_selection import GridSearchCV from sklearn.linear_model import LinearRegression from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, mean_squared_error, r2_score st=pd.Timestamp(2023, 1,1) et=pd.Timestamp(2025, 5,20) trgnme="000660" trg=fdr.DataReader(trgnme, st, et) df=trg[["Open", "High", "Low", "Close", "Volume"]] df.tail(1) Open High Low Close Volume Date 2025-05-20 202500 208000 201500 202000 ...

Statistical analysis results graph code

The following graphs are the codes for the figures included in Chapters 6 and 7 of the e-book Statistics with Python . import numpy as np import pandas as pd from scipy import stats from sklearn.preprocessing import StandardScaler import FinanceDataReader as fdr import yfinance as yf import statsmodels.api as sm from statsmodels.formula.api import ols from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt import seaborn as sns sns.set_style("darkgrid") #fig 611 st=pd.Timestamp(2024,1, 1) et=pd.Timestamp(2024, 5, 30) code=["^KS11", "^KQ11", "^DJI", "KRW=X"] nme=['kos','kq','dj','WonDol'] da=pd.DataFrame() for i in code: x=yf.download(i,st, et)['Close'] x1=x.pct_change() da=pd.concat([da, x1], axis=1) da.columns=nme da1=da.dropna() da1.index=range(len(da1)) da2=pd.melt(da1, value_vars=['kos', 'kq', 'dj', 'WonDol'], var_name=...

[data analysis] 단순회귀분석(Simple regression)

단순회귀분석(Simple regression) 전형적인 회귀 모형은 y = ax + b와 같은 형태이며 변수 x를 y로 선형변환 하는 것으로 정의할 수 있습니다. 선형변환은 x의 변화 정도에 따라 y의 변화 정도가 같습니다. x를 설명변수 또는 독립변수 , y를 반응변수 또는 종속변수 라고 하며 x는 1개 이상일 수 있으며 단변수일 경우를 단순회귀 모형이라고 합니다. 위 식과 같이 x를 y로 이동시키는 과정에서 가장 적합한 a와 b를 결정하는 것이 회귀분석의 목적이 됩니다. 예 1) kospi 지수의 일일 주가 자료중 시가(Open)을 설명변수로 하여 종가(Close)를 추정하는 회귀모델을 작성합니다. Open Close 0 2874.50 2944.45 1 2943.67 2990.57 2 2993.34 2968.21 ⋮ ⋮ ⋮ 다음 코드는 분석을 위한 자료를 호출하기 위한 것입니다. st=pd.Timestamp(2021,1, 1) et=pd.Timestamp(2024, 5, 10) kos=fdr.DataReader('KS11',st, et)[["Open","Close"]] kos.index=range(len(kos)) kos.head(3).round(2) Open Close 0 2201.21 2175.17 1 2192.58 2176.46 2 2154.97 2155.07 통계분석을 위해 다음의 이유로 자료의 표준화(Standardization) 가 필요합니다. 데이터의 규모(scale) 축소 여러변수가 사용될 경우 변수간 발생되는 데이터의 규모를 일정하게 조정 반응변수의 표준화는 필수적이지...

softmax 모델(Softmax Regression)

내용 Softmax 회귀 모델 비용함수 모델 생성 Softmax Regression Softmax 회귀 모델 데이터를 두 개의 클래스로 구분하기 위한 예측 방법인 로지스틱 회귀는 2개 이상의 클래스로 분류하기 위해 softmax 방법으로 일반화 할 수 있습니다. 이 방법을 softmax 회귀 또는 다중 로지스틱 회귀 (multinomial Losgistic regression)이라고 합니다. 이 모델은 우선적으로 각 인스턴스에 대해 식 1을 적용합니다. 이것은 그 인스턴스의 각 클래스에 대한 점수를 나타냅니다. 다음으로 식 2의 softmax 함수를 사용하여 각 클래스에 포함될 확률을 추정합니다. $$\begin{equation}\tag{1}s_k(x)=x^T\theta^{(k)}\end{equation}$$ 각 클래스 k는 자신의 가중치벡터 θ (k) 를 가집니다. 예를 들어 3개의 특성(독립변수)과 3개의 클래스들(A, B, C)를 가진 라벨(반응변수)에 대해 다음과 같이 각 인스턴스(샘플)의 점수를 계산할 수 있습니다. $$\begin{align}&\text{- A or not}\\ &\begin{bmatrix} W_{A1} &W_{A2}&W_{A3} \end{bmatrix}\begin{bmatrix} x_1\\x_2\\x_3 \end{bmatrix} = \begin{bmatrix} W_{A1}x_1+W_{A2}x_2+W_{A3}x_3 \end{bmatrix}=s(x)_A \\ &\text{- B or not}\\ &\begin{bmatrix} W_{B1} &W_{B2}&W_{B3} \end{bmatrix} \begin{bmatrix} x_1\\x_2\\x_3 \end{bmatrix} = \begin{bmatrix} W_{B1}x_1+W_{B2}x_2+W_{B3}x_3 \end{bmatrix}=s(x)_B\\ &\text{-...

[ML]로지스틱회귀(Logistic Regression)

내용 로지스틱회귀 비용함수 LogisticRegression() 결정경계 주가 자료에 적용 로지스틱회귀(Logistic Regression) 로지스틱회귀 로지스틱 회귀분석은 독립변수(특성, 설명변수)에 대해 2개의 클래스를 가진 반응변수(라벨)를 로짓변수(logit variavble) 즉, 반응변수의 발생 확률의 자연로그로 변환한 후 특정한 클래스에 속하는 확률(최대우도)을 추정 하기 위해 사용됩니다. 그러므로 이 회귀 모델은 이진분류기(binary classificatier)를 구축하게 됩니다. 선형회귀와 유사하게 로지스틱회귀 역시 입력 변수들과 가중치들의 곱이 계산됩니다. 그러나 선형회귀의 경우 이 곱의 결과가 직접적으로 사용되는 것에 비해 로지스틱 회귀의 경우는 시그모이드 함수(sigmoid function) 을 통해 [0, 1] 사이의 값으로 변환시킵니다. 즉, 식 1과 같은 연산에 의해 인스턴스의 결과(확률)가 계산됩니다. \begin{align} \hat{p}&=h_\beta(x)=\sigma\left(x^T\beta\right)\\ \tag{식1} t&=x^T\beta\\ \sigma(t)&=\frac{1}{1+\exp(-t)}\end{align} 식 1의 시그모이드 함수(σ())는 변수와 가중치의 곱의 결과를 0과 1사이의 값으로 변환합니다. import numpy as np import pandas as pd import yfinance as yf import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline font1={"size":11, 'weight': "bold"} sns.set_style("darkgrid") def sigmoid(x): return 1/(1+np.exp(-x)) t=np.li...

Multiple Perception Lyers: Regression

Multiple Perception Lyers: Regression tensorflow.keras를 적용하여 kospi 주가의 회귀모형을 구축합니다. > colab 에서 실행한 코드로 주식자료를 호출하기 위해 다음 패키지 설치가 필요합니다. !pip install -U finance-datareader import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold import tensorflow as tf from tensorflow.keras import models, layers import FinanceDataReader as fdr 주가 데이터의 이동평균을 계산하고 원시데이터에 연결하기 위한 함수를 작성합니다. #이동평균을 원시데이터에 연결 def addMa(data, window=[3,5]): for i in window: y=data.rolling(i).mean() y.columns=[f"{j}_{i}" for j in y.columns] data=pd.concat([data, y], axis=1).dropna() return(data) def maDataMake(da, window=[3, 5]): x=addMa(da, window) x1=x.replace(0, method='ffill') x1=x1.replace(np.inf, method='ffill') x1=x1.dropna() return(x1) 주가 자료를 호출합니다. st=pd.Ti...

Autocorrelation & Mean of Square Error

Contents Autocorrelation analysis Mean of Square Error Residual(Error) The generated regression model needs to be statistically tested, and the main object in the test is an error, the difference between the observations and estimates calculated by Equation 1. $$\begin{align}\tag{1}\text{e}&=y-(b_0+b_1x)\\&=y-\hat{y} \end{align}$$ Errors in the regression model have the following prerequisites: Probability variables that follow a normal distribution Because independent variables are probabilities that follow a normal distribution, the error between the response and the estimate is also a probability variable that follows a normal distribution. This means that the error cannot be artificially adjusted. Homoscedastic of error terms Various regression models are possible, as shown in Figure 1. This means that you can configure the probability distribution for the regression coefficients. This distribution has means and variances. The mean of this distrib...

Regression Analysis: simple regression & regression coefficient

Contents What is Regression? Simple regression Regression Coefficient What is Regression? Regression is a statistical method of setting up a model for the relationship between variables and estimating new values through that model. Figure 1 is a graph of the force (y) corresponding to a constant height (x), showing the exact direct proportional relationship in which y increases as x increases. This relationship is based on data from generalized laws of physics, which can fully predict the forces applied at a certain height within the Earth where gravity acts. plt.figure(figsize=(7,5)) h=range(7) w=40 F=[w*9.8*i for i in h] plt.plot(h, F, "o-") plt.xlabel("Height(m)", size=13, weight="bold") plt.ylabel("Force(N)", size=13, weight="bold") plt.text(2.5, 1500, 'F=Wgh', color="blue", size=13, weight="bold") plt.text(2, -600, r'w:weight (kg), g: Gravity Acceleration($m/sec^2$)', color="...