how to buy at current day close price?
-
hi ,in code below it is buy in the next day open price but I want it to buy at current day close price how to modified it?
import pandas as pd import backtrader as bt import backtrader.feeds as btfeeds import backtrader.plot as btp class SMACrossover(bt.Strategy): def __init__(self): self.additional_buy_dates = ['2021-01-01'] self.additional_sell_dates= ['2021-01-02'] def next(self): if self.position.size == 0: # No existing position current_date = self.data.datetime.date().isoformat() # Get the current date if current_date in self.additional_buy_dates: self.buy() # Place a buy order elif self.position.size > 0: # Already in a long position current_date = self.data.datetime.date().isoformat() if current_date in self.additional_sell_dates: self.close() # Place a sell order to close the position # Create a DataFrame (sample data for demonstration) df = pd.DataFrame({ 'datetime': ['2021-01-01', '2021-01-02'], 'open': [9, 11], 'high': [11, 13], 'low': [8, 10], 'close': [10, 12], 'volume': [100000, 2000000], }) df['datetime'] = pd.to_datetime(df['datetime']) data = bt.feeds.PandasData(dataname=df, datetime='datetime', open='open', high='high', low='low', close='close', volume='volume') cerebro = bt.Cerebro() cerebro.adddata(data) cerebro.addstrategy(SMACrossover) cerebro.broker.setcash(100) cerebro.broker.setcommission(commission=0) cerebro.addanalyzer(bt.analyzers.TimeReturn) # Run the backtest results = cerebro.run()
-
you can create a limit buy order. current code executes a market buy order.
should be something like:
self.buy(exectype=bt.Order.Limit, price = self.close[0])you can edit of course price to anything you like, like put 20bps margin:
self.buy(exectype=bt.Order.Limit, price = self.close[0]*0.998) -
@John-Doe but obviously, a limit order is not guaranteed to execute if price doesnt go below this limit level.
also, you will need to cancel open orders sometime or you get clogged with many open orders. -
You just need to set your Broker Object's "coc" value to True. It allows you to cheat-on-close (basically you can sell at the closing price even though the day is technically over).
From the documentation:
coc (default: False)
Cheat-On-Close Setting this to True with set_coc enables
matching a
Market
order to the closing price of the bar in which
the order was issued. This is actually cheating, because the bar
is closed and any order should first be matched against the prices
in the next barJust add this line after your Broker has been instantiated: cerebro.broker.set_coc(True)