09.线性回归算法在金融的应用案例

封装实现计算过程的自动化

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn')
import warnings
warnings.filterwarnings('ignore')
import yfinance as yf
import ta

def lin_reg_trading(symbol):

  def feature_engineering(df):
    """ Create new variables"""

    # We copy the dataframe to avoid interferences in the data
    df_copy = df.dropna().copy()

    # Create the returns
    df_copy['returns'] = df_copy['close'].pct_change(1)

    # Create the SMAs
    df_copy['SMA 15'] = df_copy[['close']].rolling(15).mean().shift(1)
    df_copy['SMA 60'] = df_copy[['close']].rolling(60).mean().shift(1)

    # Create the volatilities
    df_copy['MSD 10'] = df_copy[['returns']].rolling(10).std().shift(1)
    df_copy['MSD 30'] = df_copy[['returns']].rolling(30).std().shift(1)

    # Create the rsi
    RSI = ta.momentum.RSIIndicator(df_copy['close'], window=14, fillna=False)
    df_copy['rsi'] = RSI.rsi()

    return df_copy.dropna()
  
  # Import the data
  df = yf.download(symbol, proxy="http://127.0.0.1:7890")

  # Take adjusted close
  df = df[['Adj Close']]

  # Rename the column
  df.columns = ['close']

  dfc = feature_engineering(df)

  # Percentage train set
  split = int(0.80 * len(dfc))

  # Train set creation
  X_train = dfc[['SMA 15', 'SMA 60', 'MSD 10', 'MSD 30', 'rsi']].iloc[:split]
  Y_train = dfc[['returns']].iloc[:split]

  # Test set creation
  X_test = dfc[['SMA 15', 'SMA 60', 'MSD 10', 'MSD 30', 'rsi']].iloc[split:]
  Y_test = dfc[['returns']].iloc[split:]

  # Import the class
  from sklearn.linear_model import LinearRegression

  # Initialize the class
  reg = LinearRegression()

  # Fit the model
  reg.fit(X_train, Y_train)

  # Create predictions for the whole dataset
  X =np.concatenate((X_train, X_test), axis=0)

  dfc['prediction'] = reg.predict(X)

  # Compute the position
  dfc['position'] = np.sign(dfc['prediction'])

  # Compute the returns
  dfc['strategy'] = dfc['returns'] * dfc['position'].shift(1)

  (dfc['strategy'].iloc[split:].cumsum() * 100).plot()

如果不需要科学上网,可以将proxy="http://127.0.0.1:7890"内容删除;

7890是clash的默认端口,如果你用的是其他科学上网的程序,请修改为你自己实际的端口;

调用该函数即可:

lin_reg_trading('ETH-USD')
09.线性回归算法在金融的应用案例

原创文章,作者:朋远方,如若转载,请注明出处:https://caovan.com/09-xianxinghuiguisuanfazaijinrongdeyingyonganli/.html

(0)
打赏 微信扫一扫 微信扫一扫
朋远方的头像朋远方
上一篇 2022年11月15日 上午10:54
下一篇 2022年11月16日 下午7:51

相关推荐

发表回复

登录后才能评论