Advertisement
Guest User

vwap_test

a guest
Dec 13th, 2019
570
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.59 KB | None | 0 0
  1. import backtrader as bt
  2. import alpaca_backtrader_api
  3. import logging
  4. from datetime import datetime
  5. import matplotlib.pyplot as plt
  6. %matplotlib inline
  7. plt.rcParams["figure.figsize"] = (10, 6) # (w, h)
  8. plt.ioff()
  9.  
  10. '''
  11. Author: B. Bradford
  12.  
  13. MIT License
  14.  
  15. Copyright (c) B. Bradford
  16.  
  17. Permission is hereby granted, free of charge, to any person obtaining a copy
  18. of this software and associated documentation files (the "Software"), to deal
  19. in the Software without restriction, including without limitation the rights
  20. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21. copies of the Software, and to permit persons to whom the Software is
  22. furnished to do so, subject to the following conditions:
  23.  
  24. The above copyright notice and this permission notice shall be included in all
  25. copies or substantial portions of the Software.
  26.  
  27. That they contact me for shipping information for the purpose of sending a
  28. local delicacy of their choice native to whatever region they are domiciled.
  29.  
  30. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  31. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  32. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  33. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  34. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  35. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  36. SOFTWARE.
  37. '''
  38.  
  39. class VolumeWeightedAveragePrice(bt.Indicator):
  40.     plotinfo = dict(subplot=False)
  41.  
  42.     params = (('period', 30), )
  43.  
  44.     alias = ('VWAP', 'VolumeWeightedAveragePrice',)
  45.     lines = ('VWAP',)
  46.     plotlines = dict(VWAP=dict(alpha=0.50, linestyle='-.', linewidth=2.0))
  47.  
  48.  
  49.  
  50.     def __init__(self):
  51.         # Before super to ensure mixins (right-hand side in subclassing)
  52.         # can see the assignment operation and operate on the line
  53.         cumvol = bt.ind.SumN(self.data.volume, period = self.p.period)
  54.         typprice = ((self.data.close + self.data.high + self.data.low)/3) * self.data.volume
  55.         cumtypprice = bt.ind.SumN(typprice, period=self.p.period)
  56.         self.lines[0] = cumtypprice / cumvol
  57.  
  58.         super(VolumeWeightedAveragePrice, self).__init__()
  59.  
  60.  
  61. # Create a Stratey
  62. class TestStrategy(bt.Strategy):
  63.     params = (
  64.         ('maperiod', 30),
  65.     )
  66.  
  67.     def log(self, txt, dt=None):
  68.         ''' Logging function fot this strategy'''
  69.         dt = dt or self.datas[0].datetime.date(0)
  70.         print('%s, %s' % (dt.isoformat(), txt))
  71.  
  72.     def __init__(self):
  73.         # Keep a reference to the "close" line in the data[0] dataseries
  74.         self.dataclose = self.datas[0].close
  75.  
  76.         # To keep track of pending orders and buy price/commission
  77.         self.order = None
  78.         self.buyprice = None
  79.         self.buycomm = None
  80.        
  81.         # Add the vmap indicator
  82.         self.vwap = VolumeWeightedAveragePrice(self.datas[0], period=self.params.maperiod, subplot=True)
  83.  
  84.         # Add a MovingAverageSimple indicator
  85.         #self.sma = bt.indicators.SimpleMovingAverage(
  86.         #    self.datas[0], period=self.params.maperiod)
  87.  
  88.     def notify_order(self, order):
  89.         if order.status in [order.Submitted, order.Accepted]:
  90.             # Buy/Sell order submitted/accepted to/by broker - Nothing to do
  91.             return
  92.  
  93.         # Check if an order has been completed
  94.         # Attention: broker could reject order if not enough cash
  95.         if order.status in [order.Completed]:
  96.             if order.isbuy():
  97.                 self.log(
  98.                     'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
  99.                     (order.executed.price,
  100.                      order.executed.value,
  101.                      order.executed.comm))
  102.  
  103.                 self.buyprice = order.executed.price
  104.                 self.buycomm = order.executed.comm
  105.             else:  # Sell
  106.                 self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
  107.                          (order.executed.price,
  108.                           order.executed.value,
  109.                           order.executed.comm))
  110.  
  111.             self.bar_executed = len(self)
  112.  
  113.         elif order.status in [order.Canceled, order.Margin, order.Rejected]:
  114.             self.log('Order Canceled/Margin/Rejected')
  115.  
  116.         self.order = None
  117.  
  118.     def notify_trade(self, trade):
  119.         if not trade.isclosed:
  120.             return
  121.  
  122.         self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
  123.                  (trade.pnl, trade.pnlcomm))
  124.  
  125.     def next(self):
  126.         # Simply log the closing price of the series from the reference
  127.         self.log('Close, %.2f' % self.dataclose[0])
  128.  
  129.         # Check if an order is pending ... if yes, we cannot send a 2nd one
  130.         if self.order:
  131.             return
  132.  
  133.         # Check if we are in the market
  134.         if not self.position:
  135.  
  136.             # Not yet ... we MIGHT BUY if ...
  137.             if self.dataclose[0] > self.vwap[0]:
  138.  
  139.                 # BUY, BUY, BUY!!! (with all possible default parameters)
  140.                 self.log('BUY CREATE, %.2f' % self.dataclose[0])
  141.  
  142.                 # Keep track of the created order to avoid a 2nd order
  143.                 self.order = self.buy()
  144.  
  145.         else:
  146.  
  147.             if self.dataclose[0] < self.vwap[0]:
  148.                 # SELL, SELL, SELL!!! (with all possible default parameters)
  149.                 self.log('SELL CREATE, %.2f' % self.dataclose[0])
  150.  
  151.                 # Keep track of the created order to avoid a 2nd order
  152.                 self.order = self.sell()
  153.  
  154.  
  155. cerebro = bt.Cerebro()
  156.  
  157. # TQQQ 5Min data starts on: 2019-12-12 09:30:00
  158. # TQQQ 5Min data starts on: 2019-12-12 15:55:00
  159. start = datetime.strptime('2019-12-12 09:30:00', '%Y-%m-%d %H:%M:%S')
  160. end = datetime.strptime('2019-12-12 15:55:00', '%Y-%m-%d %H:%M:%S')
  161.  
  162. data = bt.feeds.GenericCSVData(
  163.     fromdate=start,
  164.     todate=end,
  165.     dataname=f"./tqqq_2019_12_12_5Min.cvs",
  166.     dtformat=('%Y-%m-%d %H:%M:%S'),
  167.     openinterest=-1,
  168.     nullvalue=0.0,
  169.     timeframe=bt.TimeFrame.Minutes,
  170.     plot=False
  171. )
  172. cerebro.adddata(data)
  173.  
  174. # add strategy
  175. #cerebro.addstrategy(St, **eval('dict(' + args.strat + ')'))
  176. cerebro.addstrategy(TestStrategy)
  177. # set the cash
  178. cerebro.broker.setcash(10000)
  179. # Print out the starting conditions
  180. print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
  181. results = cerebro.run()
  182. # Print out the final result
  183. #print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
  184. cerebro.plot()
  185.  
  186. # Basic performance evaluation ... final value ... minus starting cash
  187. #pnl = cerebro.broker.get_value() - 10000
  188. #print('Profit ... or Loss: {:.2f}'.format(pnl))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement