LoginSignup
1
3

More than 3 years have passed since last update.

Python&機械学習 勉強メモ⑦:株価の予測

Last updated at Posted at 2020-04-11

はじめに

https://qiita.com/yohiro/items/04984927d0b455700cd1
https://qiita.com/yohiro/items/5aab5d28aef57ccbb19c
https://qiita.com/yohiro/items/cc9bc2631c0306f813b5
https://qiita.com/yohiro/items/d376f44fe66831599d0b
https://qiita.com/yohiro/items/3abaf7b610fbcaa01b9c
https://qiita.com/yohiro/items/e9e80183e635e0ac4894
の続き

課題設定

過去4日間の株価上昇率を与えると、当日の株価が上昇・下降どちらになるかを推測する。

サンプルデータ

stock_price.txt
10000
9993
10259
...

1行に1日分の株価の終値が格納されている。

ソースコード

インポート

from sklearn import svm

ファイル読み込み

サンプルデータを読み込みstock_dataに格納する

# ファイル読み込み
stock_data = []
stock_data_file = open("stock_price.txt", "r")
for line in stock_data_file:
    line = line.rstrip()
    stock_data.append(float(line))
stock_data_file.close()

訓練用データの作成

日にちごとの上昇率データの作成

上昇率は以下のように算出する

i日目の上昇率=\frac{i日目の株価 - (i-1)日目の株価}{(i-1)日目の株価}

上記で算出したデータをmodified_dataに格納する。

count_s = len(stock_data)
modified_data = []
for i in range(1, count_s):
    modified_data.append(float(stock_data[i] - stock_data[i-1]) / float(stock_data[i-1]) * 20)
count_m = len(modified_data)

4日分の上昇率と当日の上昇・下降データ(=正解値)の作成

日にちごとに、過去4日分の上昇率をsuccessive_dataに格納する。
また、その日に上昇したか or 下降したかをanswersに格納する。

# 前日までの4日間のデータ
successive_data = []
# 正解値 価格上昇:1 価格低下:0
answers = []
for i in range(4, count_m):
    successive_data.append([modified_data[i-4], modified_data[i-3], modified_data[i-2], modified_data[i-1]])
    if modified_data[i] > 0:
        answers.append(1)
    else:
        answers.append(0)
n = len(successive_data)
m = len(answers)

訓練と予測

データの75%で訓練させる。

# 線形サポートベクターマシン
clf = svm.LinearSVC()
# サポートベクターマシンによる訓練(データの75%を訓練に使用)
clf.fit(successive_data[:int(n*75/100)], answers[:int(n*75/100)])

訓練結果の確認

データの残りの25%で予測を行う。

# テスト用データ
# 正解
expected = answers[int(-n*25/100):]
# 予測
predicted = clf.predict(successive_data[int(-n*25/100):])

# 末尾の10個を比較
print(expected[-10:])
print(list(predicted[-10:]))

# 正解率の計算
correct = 0.0
wrong = 0.0
for i in range(int(n*25/100)):
    if expected[i] == predicted[i]:
        correct += 1
    else:
        wrong += 1
print("正解率: " + str(correct/(correct+wrong) * 100) + "%")

結果

教材ビデオでは正解率約61%の結果が出ているが、
実際試すとwarningが出るし、正解率も約5割(当てずっぽうとほぼ大差なし)・・・

いろいろpythonなどのバージョンが違うから結果に差がでるのだろうか?

C:\Anaconda3\lib\site-packages\sklearn\svm\_base.py:947: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.
  "the number of iterations.", ConvergenceWarning)
[0, 0, 0, 1, 0, 0, 0, 1, 1, 0]
[0, 0, 0, 0, 1, 0, 0, 0, 1, 1]
正解率: 55.62248995983936%

おまけ

サンプルデータを見える化
stock.png

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3