3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonで株価を取得してみる。
ここではS&P500を例とする。

いきなりだがソースコード

import sys
from yahoo_finance_api2 import share
from yahoo_finance_api2.exceptions import YahooFinanceError
import pandas as pd
 
my_share = share.Share('^GSPC')
symbol_data = None
 
try:
    symbol_data = my_share.get_historical(
        share.PERIOD_TYPE_YEAR, 2,
        share.FREQUENCY_TYPE_DAY, 1)
except YahooFinanceError as e:
    print(e.message)
    sys.exit(1)
 
df = pd.DataFrame(symbol_data)
df["datetime"] = pd.to_datetime(df.timestamp, unit="ms")
print(df)
df.to_csv('SP500.csv')

今回はYahooのAPIを利用したが、他のAPIも含めてこの手のAPIは短時間に何回も叩くと制限に引っかかるのでCSVに変換したうえで、CSVからデータ分析を行うのがよい。(モジュールを分割すべし)
なお、他の株価を取得したい場合は^GSPCを取得したいティッカーシンボルへ変更すればよい。

Python IDLEよりRun Moduleで実行。

image.png

コンソールに結果が出力され、

image.png

CSVにも値が出力された。

image.png

めでたしめでたし。

3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?