Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def setUp(self):
self.position = Position(
"SLD", "PG", 100,
PriceParser.parse(77.69), PriceParser.parse(1.00),
PriceParser.parse(77.68), PriceParser.parse(77.70)
)
def run(config, testing, tickers, filename):
# Benchmark ticker
benchmark = 'SP500TR'
# Set up variables needed for backtest
title = [
'Moving Average Crossover Example',
__file__,
','.join(tickers) + ': 100x400'
]
events_queue = queue.Queue()
csv_dir = config.CSV_DATA_DIR
initial_equity = PriceParser.parse(500000.00)
# Use Yahoo Daily Price Handler
price_handler = YahooDailyCsvBarPriceHandler(
csv_dir, events_queue, tickers
)
# Use the MAC Strategy
strategy = MovingAverageCrossStrategy(tickers, events_queue)
# Use an example Position Sizer,
position_sizer = FixedPositionSizer()
# Use an example Risk Manager,
risk_manager = ExampleRiskManager()
# Use the default Portfolio Handler
"SLD", "AMZN", 200,
PriceParser.parse(565.59), PriceParser.parse(1.00)
)
# Multiple transactions bundled into one (in IB)
# Sell 300 GOOG from the portfolio
self.portfolio.transact_position(
"SLD", "GOOG", 100,
PriceParser.parse(704.92), PriceParser.parse(1.00)
)
self.portfolio.transact_position(
"SLD", "GOOG", 100,
PriceParser.parse(704.90), PriceParser.parse(0.00)
)
self.portfolio.transact_position(
"SLD", "GOOG", 100,
PriceParser.parse(704.92), PriceParser.parse(0.50)
)
# Finally, sell the remaining GOOG 100 shares
self.portfolio.transact_position(
"SLD", "GOOG", 100,
PriceParser.parse(704.78), PriceParser.parse(1.00)
)
# The figures below are derived from Interactive Brokers
# demo account using the above trades with prices provided
# by their demo feed.
self.assertEqual(len(self.portfolio.positions), 0)
self.assertEqual(len(self.portfolio.closed_positions), 2)
self.assertEqual(PriceParser.display(self.portfolio.cur_cash), 499100.50)
self.assertEqual(PriceParser.display(self.portfolio.equity), 499100.50)
self.assertEqual(PriceParser.display(self.portfolio.unrealised_pnl), 0.00)
self.assertEqual(PriceParser.display(self.portfolio.realised_pnl), -899.50)
self.portfolio.transact_position(
"SLD", "GOOG", 100,
PriceParser.parse(704.92), PriceParser.parse(1.00)
)
self.portfolio.transact_position(
"SLD", "GOOG", 100,
PriceParser.parse(704.90), PriceParser.parse(0.00)
)
self.portfolio.transact_position(
"SLD", "GOOG", 100,
PriceParser.parse(704.92), PriceParser.parse(0.50)
)
# Finally, sell the remaining GOOG 100 shares
self.portfolio.transact_position(
"SLD", "GOOG", 100,
PriceParser.parse(704.78), PriceParser.parse(1.00)
)
# The figures below are derived from Interactive Brokers
# demo account using the above trades with prices provided
# by their demo feed.
self.assertEqual(len(self.portfolio.positions), 0)
self.assertEqual(len(self.portfolio.closed_positions), 2)
self.assertEqual(PriceParser.display(self.portfolio.cur_cash), 499100.50)
self.assertEqual(PriceParser.display(self.portfolio.equity), 499100.50)
self.assertEqual(PriceParser.display(self.portfolio.unrealised_pnl), 0.00)
self.assertEqual(PriceParser.display(self.portfolio.realised_pnl), -899.50)
def test_calculating_statistics(self):
"""
Purchase/sell multiple lots of AMZN, GOOG
at various prices/commissions to ensure
the arithmetic in calculating equity, drawdowns
and sharpe ratio is correct.
"""
# Create Statistics object
price_handler = PriceHandlerMock()
self.portfolio = Portfolio(price_handler, PriceParser.parse(500000.00))
portfolio_handler = PortfolioHandlerMock(self.portfolio)
statistics = SimpleStatistics(self.config, portfolio_handler)
# Check initialization was correct
self.assertEqual(PriceParser.display(statistics.equity[0]), 500000.00)
self.assertEqual(PriceParser.display(statistics.drawdowns[0]), 00)
self.assertEqual(statistics.equity_returns[0], 0.0)
# Perform transaction and test statistics at this tick
self.portfolio.transact_position(
"BOT", "AMZN", 100,
PriceParser.parse(566.56), PriceParser.parse(1.00)
)
t = "2000-01-01 00:00:00"
statistics.update(t, portfolio_handler)
def _create_event(self, index, period, ticker, row):
"""
Obtain all elements of the bar from a row of dataframe
and return a BarEvent
"""
open_price = PriceParser.parse(row["Open"])
high_price = PriceParser.parse(row["High"])
low_price = PriceParser.parse(row["Low"])
close_price = PriceParser.parse(row["Close"])
adj_close_price = PriceParser.parse(row["Adj Close"])
volume = int(row["Volume"])
bev = BarEvent(
ticker, index, period, open_price,
high_price, low_price, close_price,
volume, adj_close_price
)
return bev
def _create_event(self, index, period, ticker, row):
"""
Obtain all elements of the bar from a row of dataframe
and return a BarEvent
"""
open_price = PriceParser.parse(row["Open"])
high_price = PriceParser.parse(row["High"])
low_price = PriceParser.parse(row["Low"])
close_price = PriceParser.parse(row["Close"])
adj_close_price = PriceParser.parse(row["Adj Close"])
volume = int(row["Volume"])
bev = BarEvent(
ticker, index, period, open_price,
high_price, low_price, close_price,
volume, adj_close_price
)
return bev
def _create_event(self, index, period, ticker, row):
"""
Obtain all elements of the bar from a row of dataframe
and return a BarEvent
"""
open_price = PriceParser.parse(row["Open"])
high_price = PriceParser.parse(row["High"])
low_price = PriceParser.parse(row["Low"])
close_price = PriceParser.parse(row["Close"])
adj_close_price = PriceParser.parse(row["Adj Close"])
volume = int(row["Volume"])
bev = BarEvent(
ticker, index, period, open_price,
high_price, low_price, close_price,
volume, adj_close_price
)
return bev
def _create_event(self, index, ticker, row):
"""
Obtain all elements of the bar a row of dataframe
and return a TickEvent
"""
bid = PriceParser.parse(row["Bid"])
ask = PriceParser.parse(row["Ask"])
tev = TickEvent(ticker, index, bid, ask)
return tev
def subscribe_ticker(self, ticker):
"""
Subscribes the price handler to a new ticker symbol.
"""
if ticker not in self.tickers:
self._open_ticker_price(ticker)
dft = self.tickers_data[ticker]
row0 = dft.iloc[0]
close = PriceParser.parse(row0["Close"])
adj_close = PriceParser.parse(row0["Adj Close"])
ticker_prices = {
"close": close,
"adj_close": adj_close,
"timestamp": dft.index[0]
}
self.tickers[ticker] = ticker_prices
else:
print(
"Could not subscribe ticker %s "
"as is already subscribed." % ticker
)