codecamp

AI人工智能 示例:股票市场数据分析

在这个示例中,我们将逐步分析股票市场数据,以了解 HMM 如何处理序列或时间序列数据。请注意,我们正在 Python 中实现这个示例。

导入必要的包,如下所示:

import datetime
import warnings

现在,使用matplotlib.finance包中的股票市场数据,如下所示:

import numpy as np
from matplotlib import cm, pyplot as plt
from matplotlib.dates import YearLocator, MonthLocator
try:
    from matplotlib.finance import quotes_historical_yahoo_ochl
except ImportError:
    from matplotlib.finance import (
        quotes_historical_yahoo as quotes_historical_yahoo_ochl)
from hmmlearn.hmm import GaussianHMM

从开始日期和结束日期加载数据,即在两个特定日期之间,如下所示:

start_date = datetime.date(1995, 10, 10)
end_date = datetime.date(2015, 4, 25)
quotes = quotes_historical_yahoo_ochl('INTC', start_date, end_date)

在这一步中,我们将提取每天的收盘价。为此,使用以下命令:

closing_quotes = np.array([quote[2] for quote in quotes])

现在,我们将提取每天交易的股票数量。为此,使用以下命令:

volumes = np.array([quote[5] for quote in quotes])[1:]

这里,使用以下代码计算收盘价的百分比差异:

diff_percentages = 100.0 * np.diff(closing_quotes) / closing_quotes[:-1]
dates = np.array([quote[0] for quote in quotes], dtype=np.int)[1:]
training_data = np.column_stack([diff_percentages, volumes])

在这一步中,创建并训练高斯 HMM。为此,使用以下代码:

hmm = GaussianHMM(n_components=7, covariance_type='diag', n_iter=1000)
with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    hmm.fit(training_data)

现在,使用 HMM 模型生成数据,使用以下命令:

num_samples = 300
samples, _ = hmm.sample(num_samples)

最后,在这一步中,我们将以图表的形式绘制并可视化百分比差异和交易股票数量作为输出。

使用以下代码绘制并可视化百分比差异:

plt.figure()
plt.title('Difference percentages')
plt.plot(np.arange(num_samples), samples[:, 0], c='black')

使用以下代码绘制并可视化交易股票数量:

plt.figure()
plt.title('Volume of shares')
plt.plot(np.arange(num_samples), samples[:, 1], c='black')
plt.ylim(ymin=0)
plt.show()
AI人工智能 隐马尔可夫模型(HMM)分析顺序数据
AI人工智能 构建语音识别器
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

AI人工智能监督学习(回归)

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }