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
import pandas as pd
import psycopg2
import numpy as np
companylist = ['A005930','A000660'] # 매수할 company리스트를 담는다.
class TestStrategy(bt.Strategy):
def log(self, txt, dt=None):
''' 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
# next함수에서 data가 multi로 feed될 것을 가정하여 self.datas를 for문을 돌려 매수를 한다. company list가 self.datas[0], self.datas[1]에 담기며 실제 이름 string('A005930')은 self.datas[0]._name이다.
def next(self):
for i, j in enumerate(self.datas):
self.log('%s Close, %.2f' % (self.datas[i]._name,self.datas[i].close[0]))
print(self.datas[i]._name)
if self.datas[i].close[0] > 0:
order = self.buy(data=self.datas[i])
self.log('psize %s, %.2f' % (j._name, self.getposition(j).size)) # self.getposition()을 통해 특정 종목의 총 매수한 수량 반환
self.log('portfolio value, %.2f' % self.broker.getvalue())
self.log('current cash, %.2f' % self.broker.getcash())
def notify_order(self, order): # order객체에도 data를 갖지고 있어 order.data._name을 통해 ticker 이름을 출력함.
if order.status == order.Completed: # order.Submitted : 1, order.Accepted : 2, order.Completed :3
self.log('Order %s buy excuted price: %.2f, size: %.2f, value: %.2f, comm: %.2f' % (order.data._name,order.executed.price,order.executed.size,order.executed.value,order.executed.comm))
con = psycopg2.connect("dbname='webcroll' user='postgres' host='localhost' password='1111'")
selectsql = '''select dates , 수정시가 as Open, 수정고가 as High, 수정저가 as Low, 수정주가 as Close,0 as Volumn,0 as OpenInterest
from periodpriceg
where 1=1
and code = %s
order by dates;'''
cur = con.cursor()
cerebro = bt.Cerebro()
for i,j in enumerate(companylist):
cur.execute(selectsql,(j,))
resultlist = cur.fetchall()
df = pd.DataFrame(data=np.array(resultlist), columns=['dates', 'open', 'high','low','close','volumn','openinterest'])
# Dataframe의 날짜 string을 datatime64형태로 type을 변경한다.
temp = []
for i in df['dates']:
i = np.datetime64(i)
temp.append(i)
df['dates'] = temp
df['open'] = pd.to_numeric(df['open'])
df['high'] = pd.to_numeric(df['high'])
df['low'] = pd.to_numeric(df['low'])
df['close'] = pd.to_numeric(df['close'])
df['volumn'] = pd.to_numeric(df['volumn'])
df['openinterest'] = pd.to_numeric(df['openinterest'])
# dates컬럼을 index로 지정한다.
df = df.set_index('dates')
print(df)
print(df.iloc[0][0])
print(type(df.iloc[0][0]))
data = bt.feeds.PandasData(dataname=df,
# datetime='Date',
nocase=True,
)
cerebro.addstrategy(TestStrategy)
cerebro.adddata(data,name = j)
cerebro.broker.setcash(100000000.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())
cerebro.plot(volume=False)
'Language > python' 카테고리의 다른 글
[ Python backtrader ] plot option (0) | 2020.01.14 |
---|---|
[ Python library ] argparse 사용법 (0) | 2020.01.14 |
[ Python backtrader ] 기본 하루 1주 매수 전략 (0) | 2020.01.13 |
[ Python zipline ] Ingesting quandl (0) | 2020.01.09 |
[ django ] static/img 폴더에 이미지 저장하기 (0) | 2020.01.05 |