backtrader
次の例は Yahoo finance のサービスからマイクロソフト社(MSFT)の株価データを取得して、
単純移動平均(SMA: Simplae Moving Average) を10日(sma1)、30日(sma2)の単位で求めてから、
グランビルの法則に基づいて売り買いしたときの収益をグラフ化するというもの。
code: python
from datetime import datetime
import backtrader as bt
class SmaCross(bt.SignalStrategy):
params = (('pfast', 10), ('pslow', 30),)
def __init__(self):
sma1, sma2 = bt.ind.SMA(period=self.p.pfast), bt.ind.SMA(period=self.p.pslow)
self.signal_add(bt.SIGNAL_LONG, bt.ind.CrossOver(sma1, sma2))
cerebro = bt.Cerebro()
data = bt.feeds.YahooFinanceData(
dataname='MSFT',
fromdate=datetime(2011, 1, 1),
todate=datetime(2012, 12, 31))
cerebro.adddata(data)
cerebro.addstrategy(SmaCross)
cerebro.run()
cerebro.plot()
https://www.backtrader.com/home/sigsmacross.png
グランビルの法則
短周期の移動平均(sma1)が長周期の移動平均(sma2)を
下から上にクロスしたときに買い、
その逆に、短周期の移動平均(sma1)が長周期の移動平均(sma2)
を上から下にクロスしたと きに売るというもの