본문 바로가기

Language/python

[ Python backtrader ] 기본 하루 1주 매수 전략

반응형

test.py
0.00MB

 

from __future__ import (absolute_import, division, print_function, unicode_literals)
import datetime  # For datetime objects
import os.path  # To manage paths
import sys  # To find out the script name (in argv[0])
import backtrader as bt

class TestStrategy(bt.Strategy):

    def log(self, txt, dt=None): # self.log함수 호출시 txt만 인자로 주면 앞에 일자를 넣어줌
        ''' Logging function fot this strategy'''
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        # Keep a reference to the "close" line in the data[0] dataseries
        self.dataclose = self.datas[0].close

    def next(self):
        self.log('Close, %.2f' % self.dataclose[0])
        order = self.buy() # next는 하루에 한번 호출되며 buy 함수를 토해 1주 매수, order 객체를 order변수에 담음.
        #self.log('fund value, %.2f' % self.broker.get_fundvalue())
        #self.log('fund share, %.2f' % self.broker.get_fundshares())
        self.log('portfolio value, %.2f' % self.broker.getvalue()) # broker.getvalue()를 통해 현재 포트폴리오전체금액리턴
        self.log('current cash, %.2f' % self.broker.getcash()) # broker.getcash()를 통해 현재 현금 리턴
        #print([order.Submitted, order.Accepted,order.Completed])
    def notify_order(self, order): # 주문내용을 출력하기 위해 notify_order함수를 overwriting한다.
        if order.status == order.Completed: # order.Submitted : 1, order.Accepted : 2, order.Completed :3
            self.log('Order buy excuted price: %.2f, size: %.2f, value: %.2f, comm: %.2f' % (order.executed.price,order.executed.size,order.executed.value,order.executed.comm)) # buy주문이 발생한 가격, 거래사이즈 등을 출력


if __name__ == '__main__':
    # Create a cerebro entity
    cerebro = bt.Cerebro()
    # Add a strategy
    cerebro.addstrategy(TestStrategy)

    # Datas are in a subfolder of the samples. Need to find where the script is
    # because it could have been called from anywhere
    modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
    datapath = os.path.join(modpath, '../../datas/orcl-1995-2014.txt')

    # Create a Data Feed
    data = bt.feeds.YahooFinanceCSVData(
        dataname=datapath,
        # Do not pass values before this date
        fromdate=datetime.datetime(2000, 1, 1),
        # Do not pass values before this date
        todate=datetime.datetime(2000, 12, 31),
        # Do not pass values after this date
        reverse=False)

    # Add the Data Feed to Cerebro
    cerebro.adddata(data)

    # Set our desired cash start
    cerebro.broker.setcash(100000.0)

    # Print out the starting conditions
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

    # Run over everything
    cerebro.broker.setcommission(commission=0.005)
    cerebro.run()

    # Print out the final result
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    print('Final Portfolio Cash: %.2f' % cerebro.broker.getcash())

 

 

C:\Anaconda3\python.exe D:/02_Python/01_workspace/backtrader-master/backtrader-master/samples/ykdtest/test.py
Starting Portfolio Value: 100000.00
2000-01-03, Close, 26.27
2000-01-03, portfolio value, 100000.00
2000-01-03, current cash, 100000.00
2000-01-04, Order buy excuted price: 25.68, size: 1.00, value: 25.68, comm: 0.13
2000-01-04, Close, 23.95
2000-01-04, portfolio value, 99998.14
2000-01-04, current cash, 99974.19
2000-01-05, Order buy excuted price: 22.60, size: 1.00, value: 22.60, comm: 0.11
2000-01-05, Close, 22.68
2000-01-05, portfolio value, 99996.84
2000-01-05, current cash, 99951.48

 

1월 4일자 current cash(99974.19) = 100000 - excuted price(25.68) - comm(0.13)

1월 4일자 portfolio value(99998.14)=current cash(99974.19) + close(23.95)

1월 4일자 손익 portfolio value(99998.14)-100000 = 23.95 - 25.68 - 0.13

 

2000-12-28, Order buy excuted price: 27.19, size: 1.00, value: 27.19, comm: 0.14
2000-12-28, Close, 27.63
2000-12-28, portfolio value, 98968.98
2000-12-28, current cash, 92061.48
2000-12-29, Order buy excuted price: 27.46, size: 1.00, value: 27.46, comm: 0.14
2000-12-29, Close, 25.85
2000-12-29, portfolio value, 98522.24
2000-12-29, current cash, 92033.89
Final Portfolio Value: 98522.24
Final Portfolio Cash: 92033.89

 

 

 

반응형