5/23の進捗 - スクレイピング -

前回定めたテーマ*1に基づく分析を行う上で必要なデータ用意すべく、スクレイピングを行った。

ここで必要なデータとは、以下の2つを指す。

日経平均

>> そもそも分足のデータがあんまり公開されてない! apiとかあったら教えてもらいたい。<<

ibi-square.jpさんより拝借する。

import time
import urllib.request
from bs4 import BeautifulSoup

html = urllib.request.urlopen("http://www.ibi-square.jp/n225/all.shtml")

soup = BeautifulSoup(html)
url_list = soup.find_all('table')[10].find_all('a')

for url in url_list[5:]:
    print(url.get('href'))
    csv_html = urllib.request.urlopen(url.get('href'))
    req = urllib.request.Request(url.get('href'), None, headers)
    response = urllib.request.urlopen(req)
    time.sleep(5)
    break

※ このままだと HTTP Error 403: Forbiddenで蹴られる。

user agentを弄ってもパッと見、だめ。

少しずつクエリを投げるか time.sleepを調整する必要がある。

yahooニュース編

こっちは簡単。

import urllib.request
from bs4 import BeautifulSoup
import math
from tqdm import tqdm

news = []

html = urllib.request.urlopen("https://news.yahoo.co.jp/list/?p=1")
soup = BeautifulSoup(html)

page = math.ceil(int(soup.find(class_ = 'counter').find('span').contents[0][1:-1].replace(",", "")) / 20)

for i in tqdm(range(1,page)):
    news_html = urllib.request.urlopen('https://news.yahoo.co.jp/list/?p={}'.format(i))
    news_soup = BeautifulSoup(news_html)
    news_list = soup.find_all(class_ = 'ListBoxwrap')
    for n in news_list:
        news.append([n.find(class_ = 'date').contents[0], n.find('dt').contents[0], n.find('a').get('href')])
    

今後の予定

上記によりデータの収集は達成したので、両方を照らし合わせ大きく日経平均が変動した際に、影響し得るだろうニュースが同時刻より前に出ていないか確かめ、それらのニュースに一定の相関が見られるか検証を行う。

*1:ニュース記事or有名人のツイートなどから日経平均への影響度を分析し、過度に影響すると思われるものは通知し、投資リスクの低減に繋げる。