import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import tushare as ts
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
def get_stockData(stock_code, start, end):
data = ts.get_hist_data(stock_code, start, end)
savefile = './stockData_' + stock_code + '.csv'
data.to_csv(savefile, header=1, encoding='utf-8')
return savefile
stock_code = '000538'
file = get_stockData(stock_code, start='2019-03-20', end='2020-12-31')
origDf = pd.read_csv(file, encoding='utf-8')
df = origDf[['date', 'close', 'high', 'low', 'open', 'volume', 'price_change']]
fig, ax = plt.subplots(figsize=(14, 8)) # 绘图窗口大小
plt.title('股票价格走势图', fontsize=18) # 标题
ax.plot(origDf['date'], origDf['close'], color='blue', label='收盘价')
ax.plot(origDf['date'], origDf['open'], color='#F37726', label='开盘价')
ax.plot(origDf['date'], origDf['price_change'], color='red', label='每日涨跌(收盘价-开盘价)')
plt.xlabel('交易时间', fontsize=14) # 横坐标
plt.ylabel('收盘价', fontsize=14) # 纵坐标
x_major_locator = plt.MultipleLocator(30)
x_minor_locator = plt.MultipleLocator(5) # 将 x 轴次刻度标签设置为 5 的倍数
ax.xaxis.set_major_locator(x_major_locator)
ax.xaxis.set_minor_locator(x_minor_locator)
plt.gcf().autofmt_xdate() # 自动旋转日期标记
plt.xlim('2019-03-20', '2020-12-31')
ax.legend(frameon=False)
plt.show()
featureData = df[['date', 'open', 'high', 'volume', 'low', 'close']]
columns = ['open', 'high', 'volume', 'low', 'close']
featureData.loc[:, columns] = preprocessing.scale(featureData[columns])
feature = featureData[['date', 'open', 'high', 'volume', 'low']].values
target = np.array(featureData['close'])
# 划分训练集,测试集
feature_train, feature_test, target_train, target_test = train_test_split(feature, target, test_size=0.2)
predictedDays = int(math.ceil(0.2 * len(origDf))) # 预测天数
# 创建 LinearRegression 模型实例
lrTool = LinearRegression()
lrTool.fit(feature_train[:, 1:], target_train) # 训练
predictByTest = lrTool.predict(feature_test[:, 1:]) # 用测试集预测结果
# 计算预测的差值
pred_diff = predictByTest - target_test
# 制作预测结果的时间轴
predicted_dates = feature_test[:, 0]
# 绘制预测结果的趋势线
fig, ax = plt.subplots(figsize=(14, 8))
ax.plot(predicted_dates, predictByTest, marker='o', linestyle='-', label='预测收盘价趋势线')
# 设置日期格式
x_major_locator = plt.MultipleLocator(30)
x_minor_locator = plt.MultipleLocator(5)
ax.xaxis.set_major_locator(x_major_locator)
ax.xaxis.set_minor_locator(x_minor_locator)
plt.gcf().autofmt_xdate() # 自动旋转日期标记
plt.xlabel('交易时间', fontsize=14)
plt.ylabel('预测收盘价', fontsize=14)
plt.title('股票预测收盘价趋势图', fontsize=18)
ax.legend(frameon=False)
plt.show()
python股票预测代码
最新推荐文章于 2024-04-22 13:02:59 发布