通过新闻预测股市涨跌

该项目采用Python进行数据分析,通过处理新闻数据来预测股市的涨跌。主要分为三个部分:constant.py定义了数据路径,tools.py将数据处理步骤模块化为函数,方便调用,而main.py作为主文件,整合所有功能并运行整个预测流程。
摘要由CSDN通过智能技术生成

在这里插入图片描述

  • constant.py

定义数据位置,在主文件中调用

raw_text_csv_file = './dataset/Combined_News_DJIA.csv'
cln_text_csv_file = './cln_text.csv'
  • tools.py
    把主文件需要数据处理的步骤模块化,分别定义为函数进行调用,代码更加清晰
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
import pandas as pd
import numpy as np
from sklearn.model_selection import GridSearchCV


def proc_text(raw_line):
    """
        处理每行的文本数据
        返回分词结果
    """
    raw_line = str(raw_line)
    # 全部转为小写
    raw_line = raw_line.lower()

    # 去除 b'...' 或 b"..."
    if raw_line[:2] == 'b\'' or raw_line[:2] == 'b"':
        raw_line = raw_line[2:-1]

    tokenizer = RegexpTokenizer(r'\w+')
    tokens = tokenizer.tokenize(raw_line)
    meaninful_words = [w for w in tokens if w not in stopwords.words('english')]
    return ' '.join(meaninful_words)


def clean_text(raw_text_df):
    """
        清洗原始文本数据
    """
    cln_text_df = pd.DataFrame()
    cln_text_df['date'] = raw_text_df['Date'].values
    cln_text_df['label'] = raw_text_df['Label'].values
    cln_text_df['text'] = ''

    # 处理25列文本数据,['Top1', ..., 'Top25']
    col_list = ['Top' + str(i) for i in range(1, 26)]

    for i, col in enumerate(col_list):
        raw_text_df[col] = raw_text_df[col].apply(proc_text)
        # 合并列
        cln_text_df['text'] = cln_text_df['text'].str.cat(raw_text_df[col], sep=' ')
        print('已处理{}列.'.format(i + 1))

    return cln_text_df


def split_train_test(data_df):
    """
        分割训练集和测试集
    """
    # 训练集时间范围 2008-08-08 ~ 2014-12-31
    train_text_df = data_df.loc['20080808':'20141231', :]
    # 将时间索引替换为整型索引
    train_text_df.reset_index(drop=True, inplace=True)

    # 测试集时间范
  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值