79 lines
2.5 KiB
Python
79 lines
2.5 KiB
Python
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 the backtrader platform
|
|
import backtrader as bt
|
|
# Create a Stratey
|
|
class TestStrategy(bt.Strategy):
|
|
|
|
def log(self, txt, dt=None):
|
|
''' Logging function for this strategy'''
|
|
if dt is None:
|
|
dt = self.datas[0].datetime.date(0) if len(self) > 0 else 'No Data'
|
|
print('%s, %s' % (dt, txt))
|
|
|
|
def __init__(self):
|
|
# Keep a reference to the "close" line in the data[0] dataseries
|
|
self.dataclose = self.datas[0].close
|
|
self.log('Strategy initialized', dt='Initialization')
|
|
|
|
def next(self):
|
|
# Log the current date and close price
|
|
self.log('Date: %s, Close: %.2f' % (self.datas[0].datetime.date(0), self.dataclose[0]))
|
|
self.log('High: %.2f, Low: %.2f' % (self.datas[0].high[0], self.datas[0].low[0]))
|
|
|
|
# Simple trading logic
|
|
if self.dataclose[0] < 30000:
|
|
self.log('BUY CREATE, Date: %s, Price: %.2f, Position: %d' % (self.datas[0].datetime.date(0), self.dataclose[0], self.position.size))
|
|
self.buy()
|
|
elif self.dataclose[0] > 30000 and self.position.size > 0:
|
|
self.log('SELL CREATE, Date: %s, Price: %.2f, Position: %d' % (self.datas[0].datetime.date(0), self.dataclose[0], self.position.size))
|
|
self.sell()
|
|
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, 'candle_test_asc.csv')
|
|
|
|
# Create a Data Feed
|
|
data = bt.feeds.GenericCSVData(
|
|
dataname=datapath,
|
|
fromdate=datetime.datetime(2022, 1, 1),
|
|
todate=datetime.datetime(2022, 5, 31),
|
|
dtformat=('%Y-%m-%d %H:%M:%S'),
|
|
timeframe=bt.TimeFrame.Days,
|
|
compression=1,
|
|
datetime=0,
|
|
open=1,
|
|
high=2,
|
|
low=3,
|
|
close=4,
|
|
volume=5,
|
|
openinterest=-1)
|
|
|
|
# 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.run()
|
|
|
|
# Print out the final result
|
|
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
|