File size: 5,698 Bytes
be064c1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | import importlib
import sys
import unittest
from unittest.mock import patch
import numpy as np
import pandas as pd
import lib
def load_app_module():
if "app" in sys.modules:
return sys.modules["app"]
if "simulations" not in sys.modules:
with patch.object(lib, "StockData", return_value=object()):
importlib.import_module("simulations")
return importlib.import_module("app")
app = load_app_module()
class LoanTests(unittest.TestCase):
def test_interest_is_calculated_per_trading_day(self):
loan = lib.Loan(100_000, 0.12, "Credit")
self.assertAlmostEqual(loan.getInterest(20), 1_000)
def test_equal_principal_payment_uses_monthly_rate(self):
loan = lib.Loan(1_000, 0.12, "Credit")
monthly_rate = 0.12 / 12
expected = monthly_rate * 1_000 / (1 - (1 + monthly_rate) ** -12)
self.assertAlmostEqual(loan.get_equal_principal_payment(240), expected)
class InvestmentTests(unittest.TestCase):
def test_investment_returns_each_configured_income(self):
investment = lib.Investment([10, 20], interval=5)
self.assertEqual(investment.getIncome(), 10)
self.assertEqual(investment.getIncome(), 20)
self.assertEqual(investment.getInterval(), 5)
def test_stock_history_compounds_daily_price_changes(self):
history = lib.getStockHistory(100, 2, np.array([0.1, 0.1]))
np.testing.assert_allclose(history, [110, 121])
def test_stock_history_accounts_for_daily_loan_interest(self):
loan = lib.Loan(100, 0.24, "Credit")
history = lib.getStockHistory(100, 3, np.zeros(3), loan=loan)
np.testing.assert_allclose(history, [100, 99.9, 99.8])
def test_stock_history_adds_periodic_income(self):
income = lib.Investment([10, 20], interval=2)
history = lib.getStockHistory(100, 4, np.zeros(4), incomes=income)
np.testing.assert_allclose(history, [100, 110, 110, 130])
class TradingTests(unittest.TestCase):
def test_day_trading_profit_subtracts_transaction_fee(self):
profit = lib.getDayTradingProfit(1_000, 0.02, 0.005)
self.assertAlmostEqual(profit, 15)
def test_day_trading_history_applies_daily_profit(self):
history = lib.getDayTradingHistory(
start_cash=100,
quota=1_000,
num_days=3,
percentage_diff_history=np.array([0, 0.02, -0.01]),
trade_fee=0.005,
lending_rate=0,
allow_lending=False,
)
np.testing.assert_allclose(history, [100, 115, 100])
class DataTests(unittest.TestCase):
def test_histogram_probabilities_sum_to_one(self):
histogram, bins = lib.getHistogram(np.linspace(-0.1, 0.1, 101))
self.assertEqual(len(histogram), 100)
self.assertEqual(len(bins), 100)
self.assertAlmostEqual(float(histogram.sum()), 1)
def test_generated_return_history_has_requested_number_of_days(self):
histogram = np.array([0.25, 0.75])
bins = np.array([-0.01, 0.02])
with patch("lib.np.random.choice", side_effect=[1, 0, 1, 1, 0]):
history = lib.getPercentageDiffHistory(5, histogram, bins)
self.assertEqual(len(history), 6)
self.assertEqual(history[0], 0)
np.testing.assert_array_equal(history[1:], [0.02, -0.01, 0.02, 0.02, -0.01])
def test_house_quarters_convert_to_gregorian_dates(self):
house_data = lib.HouseData.__new__(lib.HouseData)
self.assertEqual(house_data.quarter_to_date("112Q2"), "2023-06-01")
np.testing.assert_array_equal(
house_data.quarter_to_date(np.array(["112Q1", "113Q4"])),
["2023-03-01", "2024-12-01"],
)
def test_stock_data_normalizes_date_and_price_columns(self):
stock_data = lib.StockData.__new__(lib.StockData)
source = pd.DataFrame(
{
"Date": pd.to_datetime(["2024-01-02", "2024-01-03"]),
"Close": ["10", "11"],
"High": ["10", "11"],
"Low": ["10", "11"],
"Open": ["10", "11"],
"Volume": ["100", "200"],
}
)
normalized = stock_data._normalize_table(source)
self.assertEqual(normalized["Price"].tolist(), ["2024-01-02", "2024-01-03"])
self.assertEqual(normalized["Close"].tolist(), [10, 11])
self.assertTrue(pd.api.types.is_datetime64_any_dtype(normalized["Date"]))
class InterfaceTests(unittest.TestCase):
def test_custom_ticker_input_is_enabled_only_for_custom_target(self):
custom_state = app._update_alias_input_state("自定義投資標的")
regular_state = app._update_alias_input_state("AAPL")
self.assertTrue(custom_state["interactive"])
self.assertFalse(regular_state["interactive"])
self.assertEqual(regular_state["value"], "")
def test_compare_template_visibility_matches_target_type(self):
stock_template, house_template = app._toggle_compare_template("股票")
self.assertTrue(stock_template["visible"])
self.assertFalse(house_template["visible"])
def test_compare_setting_count_is_clamped_to_allowed_range(self):
minimum = app._update_compare_settings_count(1, -1, 3)
maximum = app._update_compare_settings_count(3, 1, 3)
self.assertEqual(minimum[0], 1)
self.assertFalse(minimum[3]["interactive"])
self.assertEqual(maximum[0], 3)
self.assertFalse(maximum[2]["interactive"])
self.assertEqual(
[item["visible"] for item in maximum[4:]],
[True, True, True],
)
if __name__ == "__main__":
unittest.main()
|