LoginSignup
4
1

More than 1 year has passed since last update.

Pythonで株価の移動平均線を計算する。

Last updated at Posted at 2022-12-07

チャートツールなどで移動平均線を扱っていると、値が微妙過ぎてグラフからだと移動平均線を超えているか超えていないかが分からない時がある。

image.png

そんな時にはPhythonの出番。

データを取得してCSVに保存するのは前回の記事を参照されたい。

早速だがソースコード。ここでは10か月移動平均線を求めてみる。

import pandas as pd
 
# カラムごとの計算手法を指定
agg_dict = {
    "open": "first", 
    "high": "max",
    "low": "min",
    "close": "last",
    "volume": "sum"
}
 
# CSVからデータを取得
df = pd.read_csv('SP500.csv')
# 月足に変換する
df["datetime"] = pd.to_datetime(df.timestamp, unit="ms")
df_month = df.set_index("datetime").resample("M").agg(agg_dict)
print(df_month["close"].tail(10))
sumSma10 = 0
for index, row in df_month.tail(10).iterrows():
    sumSma10 = sumSma10 + row['close']
print(sumSma10 / 10)

実行すると各月の終値と最後に10か月移動平均線の終値が出力される。

image.png

4,080 > 4,057 なので12月の月足は移動平均線を上回って開始されることが分かった。

めでたしめでたし。

4
1
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
4
1