株のシステムトレードをしよう - 1から始める株自動取引システムの作り方

株式をコンピュータに売買させる仕組みを少しずつ作っていきます。できあがってから公開ではなく、書いたら途中でも記事として即掲載して、後から固定ページにして体裁を整える方式で進めていきます。

とりあえず、Polygon.ioから指定日の1分毎に集約した四本値を取得することができた

もともとのレスポンスだとUnixtimeが返ってくるが、人間が読むには扱いづらいので datetime に変換するようにしておいた。

!pip install polygon-api-client
POLYGON_API_KEY = ''

from polygon import RESTClient
from typing import cast, Union, List, Optional
from datetime import datetime, date
from urllib3 import HTTPResponse
import json
from polygon.rest.models.aggs import Agg
from polygon.modelclass import modelclass

@modelclass
class AggWithDatetime(Agg):
    open: Optional[float] = None
    high: Optional[float] = None
    low: Optional[float] = None
    close: Optional[float] = None
    volume: Optional[float] = None
    vwap: Optional[float] = None
    timestamp: Optional[int] = None
    transactions: Optional[int] = None
    otc: Optional[bool] = None
    dt: Optional[datetime] = None

    @classmethod
    def create_from_agg(cls, agg: Agg):
        dt: datetime = cls._unixtime_to_datetime(agg.timestamp / 1000)
        return AggWithDatetime(
            agg.open,
            agg.high,
            agg.low,
            agg.close,
            agg.volume,
            agg.vwap,
            agg.timestamp,
            agg.transactions,
            agg.otc,
            dt,
        )

    @classmethod
    def _unixtime_to_datetime(cls, unixtime: Optional[int]) -> datetime:
        if unixtime is None:
            return None
        return datetime.fromtimestamp(unixtime)

def get_sticks(
        ticker_symbol: str,
        timespan: str,
        from_: Union[str, int, datetime, date],
        to: Union[str, int, datetime, date],
    ) -> List[AggWithDatetime]:
    client = RESTClient(api_key=POLYGON_API_KEY)

    aggs = cast(
        HTTPResponse,
        client.get_aggs(
            ticker_symbol,
            1,
            timespan,
            from_,
            to,
            raw=False,
        ),
    )
    return [AggWithDatetime.create_from_agg(agg) for agg in aggs]

sticks: List[AggWithDatetime] = get_sticks('DOW', 'minute', '2022-08-01', '2022-08-01')
Output exceeds the size limit. Open the full output data in a text editor
[AggWithDatetime(open=53.45, high=53.45, low=53.45, close=53.45, volume=204, vwap=53.448, timestamp=1659341040000, transactions=4, otc=None, dt=datetime.datetime(2022, 8, 1, 8, 4)),
 AggWithDatetime(open=53.19, high=53.19, low=53.19, close=53.19, volume=100, vwap=53.19, timestamp=1659343620000, transactions=1, otc=None, dt=datetime.datetime(2022, 8, 1, 8, 47)),
...
 AggWithDatetime(open=52.33, high=52.33, low=52.33, close=52.33, volume=595, vwap=52.33, timestamp=1659398160000, transactions=1, otc=None, dt=datetime.datetime(2022, 8, 1, 23, 56)),
 AggWithDatetime(open=52.33, high=52.33, low=52.33, close=52.33, volume=215, vwap=52.33, timestamp=1659398280000, transactions=1, otc=None, dt=datetime.datetime(2022, 8, 1, 23, 58))]

(C) 2020 dogwood008 禁無断転載 不許複製 Reprinting, reproducing are prohibited.