始める無料で始める

年次の株価トレンドを比較する

動画では、時系列から特定の期間を抽出する方法を見ました。

これを使って、Yahooの株価の3年間のパフォーマンスを比較します。

この演習はコースの一部です

Pythonでの時系列データ操作

コースを見る

演習の手順

すでに pandaspdmatplotlib.pyplotplt としてインポート済みで、'yahoo.csv' は DateTimeIndex と単一列 price を持つ変数 yahoo に読み込まれています。

  • 空の pd.DataFrame() を作成し、prices という名前を付けます。
  • 文字列の 2013、2014、2015 の3年を要素に持つリストを反復し、各ループで次を行います。
    • 反復変数を使って、その年のデータと列 price を選択します。
    • .reset_index()drop=True を指定して DatetimeIndex を取り除きます。
    • price の名前を、その年 (year) に適切にリネームします。
    • pd.concat() を使って、年ごとのデータを prices のデータと axis=1 に沿って結合します。
  • prices をプロットします。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# Create dataframe prices here
prices = ____

# Select data for each year and concatenate with prices here 
for year in [___, ___, ___]:
    price_per_year = yahoo.loc[___, [___]].reset_index(drop=True)
    price_per_year.rename(columns={___: year}, inplace=True)
    prices = pd.concat([prices, ___], axis=1)

# Plot prices

コードを編集して実行