【问题标题】:How to forecast future dataframe using sklearn python?如何使用 sklearn python 预测未来的数据帧?
【发布时间】:2018-07-30 18:53:16
【问题描述】:

我正在从this 链接运行示例。

经过几次修改,我已经成功运行了代码。以下是修改后的代码:

import quandl, math
import numpy as np
import pandas as pd
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from matplotlib import style
import datetime

style.use('ggplot')

df = quandl.get("WIKI/GOOGL")
df = df[['Adj. Open',  'Adj. High',  'Adj. Low',  'Adj. Close', 'Adj. Volume']]
df['HL_PCT'] = (df['Adj. High'] - df['Adj. Low']) / df['Adj. Close'] * 100.0
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0

df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']]
forecast_col = 'Adj. Close'
df.fillna(value=-99999, inplace=True)
forecast_out = int(math.ceil(0.01 * len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)

X = np.array(df.drop(['label'], 1))
X = preprocessing.scale(X)
X_lately = X[-forecast_out:]
X = X[:-forecast_out]

df.dropna(inplace=True)

y = np.array(df['label'])

X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.2)
clf = LinearRegression(n_jobs=-1)
clf.fit(X_train, y_train)
confidence = clf.score(X_test, y_test)

forecast_set = clf.predict(X_lately)
df['Forecast'] = np.nan

last_date = df.iloc[-1].name
last_unix = last_date.timestamp()
one_day = 86400
next_unix = last_unix + one_day

for i in forecast_set:
    next_date = datetime.datetime.fromtimestamp(next_unix)
    next_unix += 86400
    df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i]

df['Adj. Close'].plot()
df['Forecast'].plot()
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()

但我面临的问题是对未来数据框的预测。这是输出图像:

如图所示,我要到 2017-2018 年。从现在起如何进一步移动到 2019 年、2020 年或 5 年?

【问题讨论】:

    标签: python python-2.7 scikit-learn forecasting sklearn-pandas


    【解决方案1】:

    您的代码使用此 DataFrame 作为 X 来生成预测:

    df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']]
    

    这意味着,如果您想预测五年后的价格,您需要这些 ['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume'] 数据点来获取未来值,以便继续预测更远的距离。

    请注意,您图像中的预测是根据在此处作为测试集分离的历史数据创建的:X_lately = X[-forecast_out:]。所以它预测的每个点都使用历史数据来预测未来的某个点。

    如果您真的想使用此模型预测 5 年的未来,您首先需要预测/计算所有这些变量:predicted_X = ['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume'],并在内部使用clf.predict(predicted_X) 继续运行一些循环。

    我相信这个Machine Learning Course for Trading at Udacity 对您来说可能是一个很好的资源,它将为您提供更好的框架和思维方式来解决此类问题。

    希望我的回答清晰明了,对你有帮助,如果不只是让我知道,我会澄清或回答其他问题。

    按照我所说的更新您的模型:

    import quandl
    import numpy as np
    from sklearn import preprocessing, model_selection
    from sklearn.ensemble import RandomForestRegressor
    from sklearn.linear_model import LinearRegression
    import matplotlib.pyplot as plt
    from matplotlib import style
    import datetime
    
    style.use('ggplot')
    
    df = quandl.get("WIKI/GOOGL")
    df = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']]
    df['HL_PCT'] = (df['Adj. High'] - df['Adj. Low']) / df['Adj. Close'] * 100.0
    df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0
    
    df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']]
    forecast_col = 'Adj. Close'
    df.fillna(value=-99999, inplace=True)
    forecast_out = 1
    df['label'] = df[forecast_col].shift(-forecast_out)
    
    X = np.array(df.drop(['label'], 1))
    X = preprocessing.scale(X)
    X_lately = X[-forecast_out:]
    X = X[:-forecast_out]
    
    df.dropna(inplace=True)
    
    y = np.array(df['label'])
    
    X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.2)
    
    # Instantiate regressors
    reg_close = LinearRegression(n_jobs=-1)
    reg_close.fit(X_train, y_train)
    
    reg_hl = LinearRegression(n_jobs=-1)
    reg_hl.fit(X_train, y_train)
    
    reg_pct = LinearRegression(n_jobs=-1)
    reg_pct.fit(X_train, y_train)
    
    reg_vol = LinearRegression(n_jobs=-1)
    reg_vol.fit(X_train, y_train)
    
    # Prepare variables for loop
    last_close = df['Adj. Close'][-1]
    last_date = df.iloc[-1].name.timestamp()
    df['Forecast'] = np.nan
    predictions_arr = X_lately
    
    for i in range(100):
        # Predict next point in time
        last_close_prediction = reg_close.predict(predictions_arr)
        last_hl_prediction = reg_hl.predict(predictions_arr)
        last_pct_prediction = reg_pct.predict(predictions_arr)
        last_vol_prediction = reg_vol.predict(predictions_arr)
    
        # Create np.Array of current predictions to serve as input for future predictions
        predictions_arr = np.array((last_close_prediction, last_hl_prediction, last_pct_prediction, last_vol_prediction)).T
        next_date = datetime.datetime.fromtimestamp(last_date)
        last_date += 86400
    
        # Outputs data into DataFrame to enable plotting
        df.loc[next_date] = [np.nan, np.nan, np.nan, np.nan, np.nan, float(last_close_prediction)]
    
    df['Adj. Close'].plot()
    df['Forecast'].plot()
    plt.legend(loc=4)
    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.show()
    

    这个模型不是很有用,因为它很快就会向上爆发,但是在它的实现中存在一些有趣和不寻常的事情。

    为了更真实地预测未来价格,您还需要实施某种随机游走。

    您也可以使用不同的模型来代替 LinearRegression,例如 RandomForestRegressor,这会产生非常不同的结果。

    from sklearn.ensemble import RandomForestRegressor
    
    clf_close = RandomForestRegressor(n_jobs=-1)
    clf_close.fit(X_train, y_train)
    
    clf_hl = RandomForestRegressor(n_jobs=-1)
    clf_hl.fit(X_train, y_train)
    
    clf_pct = RandomForestRegressor(n_jobs=-1)
    clf_pct.fit(X_train, y_train)
    
    clf_vol = RandomForestRegressor(n_jobs=-1)
    clf_vol.fit(X_train, y_train)
    

    在给定特定入场参数和出场参数的情况下,预测特定头寸(买入或卖出)是否有利可图通常是一种更好的方法,而不是预测价格。 Udacity course 涵盖了这种方法。

    随机游走模型:

    import quandl
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import style
    import datetime
    import random
    
    style.use('ggplot')
    
    df = quandl.get("WIKI/GOOGL")
    df = df[['Adj. Close']]
    
    df.dropna(inplace=True)
    
    # Prepare variables for loop
    
    last_close = df['Adj. Close'][-1]
    last_date = df.iloc[-1].name.timestamp()
    df['Forecast'] = np.nan
    
    for i in range(1000):
        # Create np.Array of current predictions to serve as input for future predictions
        modifier = random.randint(-100, 105) / 10000 + 1
        last_close *= modifier
        next_date = datetime.datetime.fromtimestamp(last_date)
        last_date += 86400
    
        # Outputs data into DataFrame to enable plotting
        df.loc[next_date] = [np.nan, last_close]
    
    df['Adj. Close'].plot()
    df['Forecast'].plot()
    plt.legend(loc=4)
    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.show()
    

    随机游走输出图像

    【讨论】:

    • 有点帮助。我正在尝试通过您给出的答案和参考来解决这个问题,如果没有,那么我一定会寻求帮助,希望您能帮助我。
    • 我无法正确理解这个概念。我猜是由于财务术语。请您帮助我对我的代码进行必要的改进,好吗?
    • @Jaffer,我已按要求在您的代码中发布了必要的改进。我稍后会评论它。如果您有任何疑问,请告诉我,我会解决的。
    • 抱歉,该解决方案对我不起作用...在这里我发布了 jupyter notebook。你可以自己检查一下是什么问题。我的程序没有正确预测,因为图表始终是线性的,没有起伏:github.com/JafferWilson/test/blob/master/CodeForcast.ipynb 使用这两种逻辑..请帮助我。
    • 我正在使用 Python 2.7.... 但我不认为这会是一个问题.. 我会尝试使用 python 3.5 或 3.6
    【解决方案2】:
    1. 使用所有数据来估计模型(因此无需训练和测试集)
    2. 使用估计模型预测 T+1 时刻。
    3. 在数据中插入 T+1 时刻
    4. 回到 1,直到您提前 5 年。

    或者更好,学习时间序列统计。

    【讨论】:

    • 你能编辑一下代码让我明白吗?
    • 无法编辑,因为它不是预测算法。代码首先削减了最近观察的 10%。然后它估计一个具有 80% 剩余观测值的模型。它使用 20% 进行验证,但在我看来,这只是信息的丢失。接下来,它将前 10% 的观测值插入估计模型中,并为每个观测值提前一天预测。但是由于您已经拥有所有这些点的数据,因此它基本上只预测未来的某一天。谷歌滚动窗口、时间序列和python,你会发现更好的算法
    • 你能帮我修改代码来预测吗?我知道代码将 10% 作为测试数据,其余作为训练数据.....请告诉我你是否可以帮助我。
    猜你喜欢
    • 2020-09-19
    • 2020-07-17
    • 1970-01-01
    • 2016-02-09
    • 2020-06-01
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 2019-04-06
    相关资源
    最近更新 更多