Download tests/test_functionality.py from ylchiu/Leverage_Investment_Simulator: direct link, hf CLI and curl.
- Browser
- Download file 5.7 kB
-
https://huggingface.co/spaces/ylchiu/Leverage_Investment_Simulator/resolve/main/tests/test_functionality.py
- Command line
-
hf download hf://spaces/ylchiu/Leverage_Investment_Simulator/tests/test_functionality.py
-
curl -L -o test_functionality.py https://huggingface.co/spaces/ylchiu/Leverage_Investment_Simulator/resolve/main/tests/test_functionality.py
5.7 kB
| 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() | |