LoginSignup
2

More than 1 year has passed since last update.

posted at

S&P 500のDaily値を取得する

Financial Modeling Prep

米国株の株価、会社情報を取得するAPIを提供している

ソースコード

URL作成

url = f"https://financialmodelingprep.com/api/v3/historical-price-full/%5EGSPC?serietype=line&apikey={apikey}"

f文字列

フォーマット済み文字列リテラル
変数をそのまま指定できて便利

S&P 500のsymbol

S&P 500のsymbolは^GSPC

serietype

serietype=lineを付けないとより詳細な情報を取得できるが(volumeやvmapなど)5年分しか取得できない
serietype=lineを付けるとpriceしか情報はないが、全期間取得できる

DatetimeIndexのDataFrame作成

response = requests.get(url)
content = response.content.decode()
json_content = json.load(StringIO(content))
df = pd.DataFrame(json_content["historical"])
df.date = pd.to_datetime(df.date)
df = df.set_index("date")

requestsとStringIO

requestsとStringIOを使っているのは
pandasでread_jsonするときにキャッシュでアクセスする方法
のため

historical

APIで取得できるフォーマットはhistoricalキーに配列形式で与えられているので、historicalをDataFrameにする

DatetimeIndex化

df.dateをDatetimeIndex化する
pd.to_datetimeに渡せばいい
その後、set_indexでdateをindexにする

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
What you can do with signing up
2