Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_history_to_df_empty(self):
"""
Test 'history_to_df' with no events.
"""
start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
port = Portfolio(start_dt)
hist_df = port.history_to_df()
test_df = pd.DataFrame(
[], columns=[
"date", "type", "description",
"debit", "credit", "balance"
]
)
test_df.set_index(keys=["date"], inplace=True)
self.assertEqual(
sorted(test_df.columns),
sorted(hist_df.columns)
)
self.assertEqual(len(test_df), len(hist_df))
self.assertEqual(len(hist_df), 0)
def test_update_market_value_of_asset_not_in_list(self):
"""
Test update_market_value_of_asset for asset not in list.
"""
start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
later_dt = pd.Timestamp('2017-10-06 08:00:00', tz=pytz.UTC)
port = Portfolio(start_dt)
asset = EquityMock("Acme Inc.", "AAA", "NYSE", tax_exempt=False)
update = port.update_market_value_of_asset(
asset, 54.34, later_dt
)
self.assertEqual(update, None)
"""
Tests create_portfolio method for:
* If portfolio_id already in the dictionary keys,
raise BrokerException
* If it isn't, check that they portfolio and open
orders dictionary was created correctly.
"""
start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
exchange = ExchangeMock()
sb = SimulatedBroker(start_dt, exchange)
# If portfolio_id isn't in the dictionary, then check it
# was created correctly, along with the orders dictionary
sb.create_portfolio(portfolio_id=1234, name="My Portfolio")
self.assertTrue("1234" in sb.portfolios)
self.assertTrue(isinstance(sb.portfolios["1234"], Portfolio))
self.assertTrue("1234" in sb.open_orders)
self.assertTrue(isinstance(sb.open_orders["1234"], queue.Queue))
# If portfolio is already in the dictionary
# then raise BrokerException
with self.assertRaises(BrokerException):
sb.create_portfolio(
portfolio_id=1234, name="My Portfolio"
)
def test_subscribe_funds_behaviour(self):
"""
Test subscribe_funds raises for incorrect datetime
Test subscribe_funds raises for negative amount
Test subscribe_funds correctly adds positive
amount, generates correct event and modifies time
"""
start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
earlier_dt = pd.Timestamp('2017-10-04 08:00:00', tz=pytz.UTC)
later_dt = pd.Timestamp('2017-10-06 08:00:00', tz=pytz.UTC)
pos_cash = 1000.0
neg_cash = -1000.0
port = Portfolio(start_dt)
# Test subscribe_funds raises for incorrect datetime
with self.assertRaises(PortfolioException):
port.subscribe_funds(earlier_dt, pos_cash)
# Test subscribe_funds raises for negative amount
with self.assertRaises(PortfolioException):
port.subscribe_funds(start_dt, neg_cash)
# Test subscribe_funds correctly adds positive
# amount, generates correct event and modifies time
port.subscribe_funds(later_dt, pos_cash)
self.assertEqual(port.total_cash, 1000.0)
self.assertEqual(port.total_securities_value, 0.0)
self.assertEqual(port.total_equity, 1000.0)
pe = PortfolioEvent(
def test_portfolio_to_dict_empty_portfolio(self):
"""
Test 'portfolio_to_dict' method for an empty Portfolio.
"""
start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
port = Portfolio(start_dt)
port.subscribe_funds(start_dt, 100000.0)
port_dict = port.portfolio_to_dict()
test_dict = {
"total_cash": 100000.0,
"total_securities_value": 0.0,
"total_equity": 100000.0
}
self.assertEqual(port_dict, test_dict)
def test_holdings_to_dict_for_two_holdings(self):
"""
Test holdings_to_dict for two holdings.
"""
start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
asset1_dt = pd.Timestamp('2017-10-06 08:00:00', tz=pytz.UTC)
asset2_dt = pd.Timestamp('2017-10-07 08:00:00', tz=pytz.UTC)
update_dt = pd.Timestamp('2017-10-08 08:00:00', tz=pytz.UTC)
asset1 = EquityMock("AAA Inc.", "AAA", "NYSE", tax_exempt=False)
asset2 = EquityMock("BBB Inc.", "BBB", "NYSE", tax_exempt=False)
port = Portfolio(start_dt)
port.subscribe_funds(start_dt, 100000.0)
tn_asset1 = Transaction(
asset=asset1, quantity=100, dt=asset1_dt,
price=567.0, order_id=1, commission=15.78
)
port.transact_asset(tn_asset1)
tn_asset2 = Transaction(
asset=asset2, quantity=100, dt=asset2_dt,
price=123.0, order_id=2, commission=7.64
)
port.transact_asset(tn_asset2)
port.update_market_value_of_asset(asset2, 134.0, update_dt)
test_holdings = {
asset1: {
"quantity": 100,
"book_cost": 56715.78,
def test_holdings_to_console_for_two_positions(self):
"""
Tests the 'holdings_to_console' console output for
two Position entities within the Portfolio.
"""
start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
asset1_dt = pd.Timestamp('2017-10-06 08:00:00', tz=pytz.UTC)
asset2_dt = pd.Timestamp('2017-10-07 08:00:00', tz=pytz.UTC)
update_dt = pd.Timestamp('2017-10-08 08:00:00', tz=pytz.UTC)
asset1 = EquityMock("AAA Inc.", "AAA", "NYSE", tax_exempt=False)
asset2 = EquityMock("BBB Inc.", "BBB", "NYSE", tax_exempt=False)
port = Portfolio(start_dt)
port.subscribe_funds(start_dt, 100000.0)
tn_asset1 = Transaction(
asset=asset1, quantity=100, dt=asset1_dt,
price=567.0, order_id=1, commission=15.78
)
port.transact_asset(tn_asset1)
tn_asset2 = Transaction(
asset=asset2, quantity=100, dt=asset2_dt,
price=123.0, order_id=2, commission=7.64
)
port.transact_asset(tn_asset2)
test_str = "\x1b[1;36m\nPortfolio Holdings | None - None\n\n" \
"\x1b[0m*======================================================" \
"============================================*\n" \
"| Holding | Quantity | Price | Change | Book Cost " \
"| Market Value | Unrealised Gain | \n" \
def test_initial_settings_for_default_portfolio(self):
"""
Test that the initial settings are as they should be
for two specified portfolios.
"""
start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
# Test a default Portfolio
port1 = Portfolio(start_dt)
self.assertEqual(port1.start_dt, start_dt)
self.assertEqual(port1.cur_dt, start_dt)
self.assertEqual(port1.currency, "USD")
self.assertEqual(port1.starting_cash, 0.0)
self.assertEqual(port1.portfolio_id, None)
self.assertEqual(port1.name, None)
self.assertEqual(port1.total_securities_value, 0.0)
self.assertEqual(port1.total_cash, 0.0)
self.assertEqual(port1.total_equity, 0.0)
# Test a Portfolio with keyword arguments
port2 = Portfolio(
start_dt, starting_cash=1234567.56, currency="USD",
portfolio_id=12345, name="My Second Test Portfolio"
)
self.assertEqual(port2.start_dt, start_dt)
def test_withdraw_funds_behaviour(self):
"""
Test withdraw_funds raises for incorrect datetime
Test withdraw_funds raises for negative amount
Test withdraw_funds raises for lack of cash
Test withdraw_funds correctly subtracts positive
amount, generates correct event and modifies time
"""
start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
earlier_dt = pd.Timestamp('2017-10-04 08:00:00', tz=pytz.UTC)
later_dt = pd.Timestamp('2017-10-06 08:00:00', tz=pytz.UTC)
even_later_dt = pd.Timestamp('2017-10-07 08:00:00', tz=pytz.UTC)
pos_cash = 1000.0
neg_cash = -1000.0
port_raise = Portfolio(start_dt)
# Test withdraw_funds raises for incorrect datetime
with self.assertRaises(PortfolioException):
port_raise.withdraw_funds(earlier_dt, pos_cash)
# Test withdraw_funds raises for negative amount
with self.assertRaises(PortfolioException):
port_raise.withdraw_funds(start_dt, neg_cash)
# Test withdraw_funds raises for not enough cash
port_broke = Portfolio(start_dt)
port_broke.subscribe_funds(later_dt, 1000.0)
with self.assertRaises(PortfolioException):
port_broke.withdraw_funds(later_dt, 2000.0)
# Test withdraw_funds correctly subtracts positive
# Test a US portfolio produces correct values
cur1 = "USD"
port1 = Portfolio(start_dt, currency=cur1)
self.assertEqual(port1.currency, "USD")
self.assertEqual(port1._currency_format(cash), "$1,234,567.56")
# Test a UK portfolio produces correct values
cur2 = "GBP"
port2 = Portfolio(start_dt, currency=cur2)
self.assertEqual(port2.currency, "GBP")
self.assertEqual(port2._currency_format(cash), "£1,234,567.56")
# Test a German portfolio fails (DE not supported yet)
cur3 = "DE"
with self.assertRaises(PortfolioException):
Portfolio(start_dt, currency=cur3)