首页 > 解决方案 > 为什么我只有在不使用今天的日期时才有不同的数组尺寸?

问题描述

我正在尝试获取一家公司的股票数据并预测未来的股票价格。我知道这不准确,但我将其用作学习工具。当使用今天的日期作为结束日期并将预测日期作为未来的日期时,我的代码似乎可以工作。但是,当使用过去的日期并预测未来时,这会产生错误:

“ValueError:x 和 y 必须具有相同的第一维,但具有形状 (220,) 和 (221,)”

我想这样做,因为这样我就可以将预测与实际价格进行比较。

import numpy as np
import datetime
import pandas_datareader as web
import statistics
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import style
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

stock_name = 'BP.L'

prices = web.DataReader(stock_name, 'yahoo', start = '2019-01-01', end = '2019-11-05').reset_index(drop = False)[['Date', 'Adj Close']]


#plt.plot(prices['Date'], prices['Adj Close'])
#plt.xlabel('Days')
#plt.ylabel('Stock Prices')
#plt.show()


# Parameter Definitions

# So    :   initial stock price
# dt    :   time increment -> a day in our case
# T     :   length of the prediction time horizon(how many time points to predict, same unit with dt(days))
# N     :   number of time points in the prediction time horizon -> T/dt
# t     :   array for time points in the prediction time horizon [1, 2, 3, .. , N]
# mu    :   mean of historical daily returns
# sigma :   standard deviation of historical daily returns
# b     :   array for brownian increments
# W     :   array for brownian path

start_date = '2018-01-01'
end_date = '2019-01-01'
pred_end_date = '2019-11-05'

# We get daily closing stock prices
S_eon = web.DataReader(stock_name, 'yahoo', start_date, end_date).reset_index(drop = False)[['Date', 'Adj Close']]

So = S_eon.loc[S_eon.shape[0] -1, "Adj Close"]

dt = 1

n_of_wkdays = pd.date_range(start = pd.to_datetime(end_date, 
              format = "%Y-%m-%d") + pd.Timedelta('1 days'), 
              end = pd.to_datetime(pred_end_date, 
              format = "%Y-%m-%d")).to_series(
              ).map(lambda x: 
              1 if x.isoweekday() in range(1,6) else 0).sum()
T = n_of_wkdays

N = T / dt

t = np.arange(1, int(N) + 1)

returns = (S_eon.loc[1:, 'Adj Close'] - \
          S_eon.shift(1).loc[1:, 'Adj Close']) / \
          S_eon.shift(1).loc[1:, 'Adj Close']

mu = np.mean(returns)

sigma = np.std(returns)


scen_size = 10000
b = {str(scen): np.random.normal(0, 1, int(N)) for scen in range(1, scen_size + 1)}

W = {str(scen): b[str(scen)].cumsum() for scen in range(1, scen_size + 1)}

drift = (mu - 0.5 * sigma**2) * t
diffusion = {str(scen): sigma * W[str(scen)] for scen in range(1, scen_size + 1)}

S = np.array([So * np.exp(drift + diffusion[str(scen)]) for scen in range(1, scen_size + 1)]) 
S = np.hstack((np.array([[So] for scen in range(scen_size)]), S))
S_avg = np.mean(S)
print(S_avg)

#Plotting 
plt.figure(figsize = (20,10))
for i in range(scen_size):
    plt.title("Daily Volatility: " + str(sigma))
    plt.plot(pd.date_range(start = S_eon["Date"].max(), 
                end = pred_end_date, freq = 'D').map(lambda x:
                x if x.isoweekday() in range(1, 6) else np.nan).dropna(), S[i, :])
    plt.ylabel('Stock Prices, €')
    plt.xlabel('Prediction Days')
plt.show()

错误显示:

“文件“C:\Users\User\Anaconda3\lib\site-packages\matplotlib\axes_base.py”,第 270 行,在 _xy_from_xy 中“具有形状 {} 和 {}”.format(x.shape, y.shape) )"

标签: python

解决方案


您能否尝试在预测结束日期上再增加一天?

pred_end_date = '2019-11-06'

您的错误只是形状不匹配,而您的日期系列只错过了一个值


推荐阅读