DEVGRU

プログラミングと競馬予想について書きます

Python と pypetteer で某所から株価を無料で取得する

結局、仮想通貨は逃げるタイミングが遅れてとんでもない負債を私に残していったので、 ボラリティは低いが安定している株取引を粛々とすることにした。

さて、株取引の自動化は厳しいが、せめて売買のタイミングぐらいは自動的に分かるようにしておきたい。

幸い、無料で株価履歴を公開しているサイトがあるので、そこから自動取得するようにしてテクニカル指標を求めるようにすることにした。

import os
import asyncio
import time

from pyppeteer import launch

import pandas as pd
import matplotlib.pyplot as plt

async def scrape(browser, url):
    page = await browser.newPage()
    await page.goto(url)
    await page.waitFor('tr')
    elements = await page.JJ('tr')
    
    result = []
    for element in elements[1:]:
        values = (await element.getProperty('textContent')).toString().split()[1:]
        date, o, h, l, c, volume, _ = values
        result.append([date, int(o), int(h), int(l), int(c), int(volume)])
    return result

async def main():
    browser = await launch()
    stock_id = 3341
    result2017 = await scrape(browser, f'https://kabuoji3.com/stock/{stock_id}/2017/')
    result2018 = await scrape(browser, f'https://kabuoji3.com/stock/{stock_id}/2018/')
    result = result2017 + result2018
    await browser.close()
    
    print(result)
    
asyncio.get_event_loop().run_until_complete(main())

stock_id を適当な銘柄番号にすると2017/1/1〜の日付、OHLC, Volumeが取得できます。