-
Hi, BT : 0.3.1 How it should works : For me, if there is only one trade How it currently works : I am missing something, but i am not able to get what. The sample code : import unittest
from datetime import date, datetime
import pandas as pd
from backtesting import Backtest, Strategy
from backtesting.test import GOOG, SMA
class Test(Strategy):
def init(self):
price = self.data.Close
def next(self):
if not self.position:
if self.data.index[-1].date() == date(2010, 5, 13):
self.buy()
else:
if self.data.index[-1].date() == date(2010, 5, 20):
self.position.close()
class BasicTestSuite(unittest.TestCase):
"""Basic test cases."""
def test_lib(self):
data = GOOG
the_date = pd.to_datetime(datetime(2010, 5, 30))
data = data.loc[:the_date]
bt = Backtest(data, Test,
cash=10000, commission=0)
output = bt.run()
print(output._strategy.orders)
print(output._strategy.closed_trades)
#print(output._strategy.closed_trades[0])
#self.assertEqual(len(output._strategy.orders), 1)
# Checking if there is only one trade...
self.assertEqual(len(output._strategy.closed_trades), 1)
# Starting equity +(-) pl must be equal to output final equity
self.assertEqual(10000 + output._strategy.closed_trades[0].pl, output["Equity Final [$]"])
# Checking that normaly (?) the Return % must be === to the pl_pct because there is only one trade
self.assertEqual(round(output._strategy.closed_trades[0].pl_pct * 100,3), round(output["Return [%]"],3))
if __name__ == '__main__':
unittest.main() The result is that : First i thought that it was related to commission... but it looks like it's not the case... |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
@kernc regarding your reply, it means that you are quiet surprised too about this behavior. |
Beta Was this translation helpful? Give feedback.
-
That's a normal, and logical behavior. In details : For exemple : I have 10k$ of cash and if i want to put all this amount on a stock that cost 880$ each ("buy" order), it means that i will have 11 stocks with an amount of 9680$ (stats["cash"]=320$). Let's say that my stock goes to 800$, and i close the position. So i am losing ((800 - 880)/880) -9,09%, -> 8800$ for the entire position. Regarding the stats : |
Beta Was this translation helpful? Give feedback.
That's a normal, and logical behavior.
Maybe we should add something as
stats["cash"]
to know the amount of cash that is not used during the trade.If all trades are closed
stats["cash"] == stats["Final equity"]
If a trade is open
stats["cash"] != stats["Final equity"]
=>stats["cash"] = old_stats["cash"]-last_trade.entry_price * last_trade.size
In details :
This issue could happen because of the difference between the global cash vs the effective cost of stocks.
For exemple : I have 10k$ of cash and if i want to put all this amount on a stock that cost 880$ each ("buy" order), it means that i will have 11 stocks with an amount of 9680$ (stats["cash"]=320$).
Let's say that my stock goes …