Help us understand the problem. What is going on with this article?

pythonを使った株価の自動収集

はじめに

最近、株価を予想するAIを作って欲しいということで、全くいい精度がでる期待もなかったが作ることにした。

過去にkerasやtensorflowを使ってAIを作ったことがあったが、株価を集めることはしたことがなかったのでやり方をまとめておく。

ビックデータを使いこなすにはスクレイピングやAPIの扱いになれなくてはと思ったりおもってみたり。

Quandl

流石に手動では絶命するので自動で収集する方法がないかと調べていたら、Quandlをみつけた。
銘柄コードを指定してAPIのURLにアクセスすればCSVでダウンロードできる。

会員登録

まずはここから会員登録をして、API keyをもらう必要がある。

ライブラリ経由で取得

$pip3 install quandl

使用方法

株価取得

データの取得は、quandl.get()でできる。引数は銘柄コードのみでOK。
TSEは株式会社東京証券取引所らしい。

import quandl
import pandas as pd
import  matplotlib.pyplot as plt

# SONYの株価を取得
brand = "TSE/6758"
# quandlに登録して得られたAPI keyを指定する。
quandl.ApiConfig.api_key = 'your API key'
# 株価の取得
quandl_data = quandl.get(dataset=brand, returns='pandas')
# CSVへ保存
quandl_data.to_csv('stock_price_data.csv')

移動平均の計算

せっかくなので終値の30日移動平均も計算。

## 移動平均を計算
quandl_data['30MA'] = quandl_data['Close'].rolling(window = 30, min_periods=0).mean()

グラフに表示

fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot(quandl_data['Close'], 'black', lw = 1,label="close")
axes.plot(quandl_data['30MA'],label="30MA")
axes.set_xlabel('Time')
axes.set_ylabel('Price')
axes.set_title(brand)
axes.legend()
plt.savefig('stock_price_data.png')
plt.pause(0.001)

実行してみるとこんな感じ。
stock_price_data.png

複数の銘柄から株価を取得

株価の学習をする上で、一つの銘柄より複数の銘柄で学習するのもいいのでは?と思いました。
ということで、複数の銘柄を一度に取得する方法も記載。

銘柄code listを作成

前もって銘柄code list(code.csv)を作成しておきます。
主要な銘柄である日経225から10件だけを対象にします。

image.png

株価取得

# get data
print('Getting stock price...')
import quandl
import pandas as pd
import  matplotlib.pyplot as plt
quandl.ApiConfig.api_key = 'your API key'
# 銘柄codeをcsvから読み出し
code = pd.read_csv('code.csv')
# DataFrameからのDataをlist型かつ文字列として変換
code = ["TSE/"+str(n) for n in code['code'].values.tolist()]
# 複数銘柄の株価取得
quandl_data = quandl.get(dataset=code, returns='pandas')
# quandl_dataのcolumnsにあるstr(文字列)でCloseが含まれているcolumnsのみを抽出します。
quandl_data = quandl_data.loc[:,(quandl_data.columns.str.contains('Close'))]
# 銘柄ごとに終値の移動平均を算出
for  k in range(len(code)):
    quandl_data[code[k] + '_30MA'] = quandl_data.rolling(window = 30, min_periods=0).mean().iloc[:,0]
quandl_data.to_csv('dataset.csv')

まとめ

今回は、pythonを使って株価を自動収集した。
AIの学習には大量のデータが必要であるが手作業であつめるとなると大変。
この自動収集のやり方は、FXでも適応できますのでぜひ試してください。
AIもすでに作成して精度評価しているのでもしかしたら投稿するかも??
1銘柄のデータセットと255銘柄のデータセットどちらを使うと精度がよくなるとか、AI学習前の前処理の仕方とか、どうすれば勝率があがるかなどなど。
ちなみに、移動平均の予測値は1銘柄2007~2017年のデータセットでAccuracy84~85%、誤差16円。
工夫することで勝率96%、儲からないという検出力96%まで向上させることができた。
詳しくはAI(Deep Learning)作成編で。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした