|
WU Trading Library 0.2.0
A backtesting and trading strategy library
|
Go to the source code of this file.
Data Structures | |
| struct | BuyPositionResult |
| An auxiliary struct to hold the result of setting a buy position and calculating the total cost. More... | |
Functions | |
| WU_PortfolioParams | wu_portfolio_params_default (void) |
| This file implements a basic portfolio management system that supports multiple assets with a shared cash pool. | |
| static double | calculate_years_held (WU_TimeStamp open_time, WU_TimeStamp close_time) |
| Helper function to calculate the time difference in years between two timestamps, accounting for different time units. | |
| static double | execution_price (double price, WU_ExecutionPolicy policy, bool is_buy) |
| Calculates the execution price based on the execution policy. | |
| static double | calculate_positions_value (WU_PositionVector *vec, double price) |
| Helper function to calculate the total value of all positions in a position vector at a given price. | |
| static double | calculate_portfolio_value (const struct WU_Portfolio_ *portfolio) |
| To calculate the total value of the portfolio, an iterative process is used to sum the value of each position across all assets, based on the last known price for each asset. | |
| static double | calculate_position_size (WU_BasicPortfolio portfolio, WU_Signal signal) |
| This function calculates the position size for a given signal based on the portfolio's position sizing parameters. | |
| static double | compute_total_cost (double quantity, double price, WU_ExecutionPolicy policy) |
| Computes the total cost of a trade including transaction costs. | |
| static struct BuyPositionResult | set_buy_position (WU_BasicPortfolio portfolio, WU_Signal signal) |
| This function calculates the position size for a buy signal, applies execution policy to determine the effective price, and computes the total cost of the purchase including transaction costs. | |
| static double | calculate_total_cost_basis (WU_PositionVector *vec) |
| This function calculates the total cost basis for all active positions in a given position vector. | |
| static void | execute_buy (WU_BasicPortfolio portfolio, WU_Signal signal, int asset_index) |
| This function executes a buy signal. | |
| static void | close_and_update_portfolio (WU_BasicPortfolio portfolio, double quantity, double cost_basis, double sell_price, WU_CloseReason reason) |
| This function handles the logic for closing a position and updating the portfolio's cash balance and trading statistics. | |
| static void | execute_sell (WU_BasicPortfolio portfolio, WU_Signal signal, int asset_index) |
| This function executes a sell signal. | |
| static bool | close_position (WU_BasicPortfolio portfolio, struct WU_Position_ pos, double current_price) |
| This function checks if a position should be closed based on the current price and the portfolio's stop-loss and take-profit thresholds. | |
| static void | check_and_close_positions (WU_BasicPortfolio portfolio, int asset_index, double current_price) |
| This function iterates through all active positions for a given asset and checks if any of them can be closed based on the current price and the portfolio's stop-loss and take-profit thresholds. | |
| static double | calculate_portfolio_pnl (const struct WU_Portfolio_ *portfolio) |
| The profit and loss (PnL) of the portfolio is calculated by taking the current total value of the portfolio (cash + value of all positions) and subtracting the initial cash invested. | |
| static double | calculate_total_short_value (WU_BasicPortfolio p) |
| Helper function to calculate total value of all short positions across all assets in the portfolio. | |
| static void | update_prices_and_check_exits (WU_BasicPortfolio p, const WU_Signal *signals, int count) |
| Helper function to update last prices, apply borrow interest on short positions, check exits, and update stats with current portfolio state. | |
| static void | process_sell_signals (WU_BasicPortfolio p, const WU_Signal *signals, int count) |
| Helper function to process all sell signals. | |
| static int | count_buy_signals (const WU_Signal *signals, int count) |
| Helper function to count valid buy signals. | |
| static bool | uses_strategy_guided_allocation (WU_BasicPortfolio p, const WU_Signal *signals, int count) |
| Helper function to check if signals use strategy-guided allocation. | |
| static void | process_buy_signals (WU_BasicPortfolio p, const WU_Signal *signals, int count, int buy_count) |
| Helper function to process all buy signals. | |
| static void | execute_pending_orders (WU_BasicPortfolio p) |
| Helper function to execute pending orders from previous update. | |
| static void | update_portfolio (WU_Portfolio portfolio, const WU_Signal *signals) |
| The update_portfolio function is the core of the portfolio management logic. | |
| static void | wu_basic_portfolio_free (struct WU_Portfolio_ *portfolio) |
| This function is responsible for freeing all memory associated with the portfolio. | |
| static WU_PositionVector ** | initialize_positions (const char *symbols[], int num_assets) |
| Helper function to initialize position vectors for all assets. | |
| WU_BasicPortfolio | wu_basic_portfolio_new (WU_PortfolioParams params, const char *symbols[]) |
| This constructor function creates a new basic portfolio instance. | |
| double | wu_basic_portfolio_asset_value (WU_BasicPortfolio portfolio, int asset_index) |
| The value of a specific asset's positions is calculated by summing the value of each active position. | |
| double | wu_basic_portfolio_asset_quantity (WU_BasicPortfolio portfolio, int asset_index) |
| Computes the total quantity held for a specific asset by summing the quantities of all active positions in the corresponding position vector. | |
|
static |
The profit and loss (PnL) of the portfolio is calculated by taking the current total value of the portfolio (cash + value of all positions) and subtracting the initial cash invested.
This provides a measure of the overall performance of the portfolio since inception.
|
static |
To calculate the total value of the portfolio, an iterative process is used to sum the value of each position across all assets, based on the last known price for each asset.
The cash balance is then added to this total to get the overall portfolio value. This function has a complexity of O(N*M) where N is the number of assets and M is the average number of positions per asset. Although the performance can be an issue, it provides an accurate valuation of the portfolio at a given point in time. In the future, it can consider caching the total value and only recalculating when there are changes to positions or prices, to improve performance. Additionally, it can be optimized by maintaining a running total of the portfolio value that gets updated when positions modified.
|
static |
This function calculates the position size for a given signal based on the portfolio's position sizing parameters.
It supports multiple sizing strategies, including absolute size, percentage of cash, equal percentage of portfolio, and strategy-guided sizing. The function takes into account the current price of the asset and the available cash in the portfolio to determine the appropriate quantity to buy or sell. It ensures that the calculated position size does not exceed the available cash for buy signals and can be adjusted based on the signal's quantity for strategy-guided sizing.
|
static |
|
static |
This function calculates the total cost basis for all active positions in a given position vector.
It iterates through each position, checks if it is active, and if so, it multiplies the quantity by the price to get the cost for that position, and sums it up to get the total cost basis. This total cost basis is used when closing positions to determine the profit and loss (PnL) from the trade, as it represents the total amount invested in those positions.
|
static |
|
static |
|
static |
This function iterates through all active positions for a given asset and checks if any of them can be closed based on the current price and the portfolio's stop-loss and take-profit thresholds.
If a position is closed, then it is removed from the position vector.
|
static |
This function handles the logic for closing a position and updating the portfolio's cash balance and trading statistics.
It calculates the proceeds from the sale, the transaction cost based on the defined transaction cost policy, and the profit and loss (PnL) from the trade. The portfolio's cash balance is updated by adding the proceeds and subtracting the transaction cost, and fees are tracked in stats.
|
static |
|
static |
|
static |
|
static |
This function executes a buy signal.
For portfolios without positions or with long positions, it creates new long positions. When there are short positions (negative quantity), it closes them (buy to cover). It updates the portfolio's cash balance and tracks transaction fees in stats.
|
static |
|
static |
|
inlinestatic |
|
static |
|
static |
Helper function to process all buy signals.
If cash splitting is enabled, it divides the available cash equally among the buy signals to ensure that the total allocated cash does not exceed the portfolio's cash balance. Each buy signal is processed sequentially, and the cash balance is updated after each purchase to reflect the remaining cash for subsequent buys. If cash splitting is not enabled, each buy signal is processed with the full available cash, which may lead to some buy signals being ignored if the cash runs out. This function ensures that the portfolio's cash management is consistent with the defined position sizing strategy and prevents over-allocation of funds when multiple buy signals are present.
|
static |
Helper function to process all sell signals.
It iterates through the signals, validates them, and if a signal is a sell signal, it calls the execute_sell function to close the corresponding positions. This function should be called first to ensure that all sell signals are handled before processing buy signals, which is important for proper cash management and to avoid situations where buy signals are ignored due to insufficient cash after processing sell signals.
|
static |
This function calculates the position size for a buy signal, applies execution policy to determine the effective price, and computes the total cost of the purchase including transaction costs.
It also checks if the total cost exceeds the available cash in the portfolio, and if so, it adjusts the quantity to fit within the cash constraints. The result includes the position details (timestamp, quantity, price) and the total cost and transaction cost for the trade.
|
static |
The update_portfolio function is the core of the portfolio management logic.
It processes incoming signals to update the portfolio's state. For IMMEDIATE execution, signals are processed right away. For NEXT_CLOSE execution, signals are stored and executed on the next update. The function first executes any pending orders from previous update, then updates prices and checks for exits, processes sell signals, and finally processes buy signals (or stores them as pending).
|
static |
|
static |
| double wu_basic_portfolio_asset_quantity | ( | WU_BasicPortfolio | portfolio, |
| int | asset_index ) |
| double wu_basic_portfolio_asset_value | ( | WU_BasicPortfolio | portfolio, |
| int | asset_index ) |
|
static |
This function is responsible for freeing all memory associated with the portfolio.
It iterates through each asset's position vector and deletes it, then frees the array of position vectors, pending orders array, deletes the portfolio statistics, and finally frees the portfolio structure itself. This ensures that all resources are properly released when the portfolio is no longer needed, preventing memory leaks.
| WU_BasicPortfolio wu_basic_portfolio_new | ( | WU_PortfolioParams | params, |
| const char * | symbols[] ) |
This constructor function creates a new basic portfolio instance.
Creates a new basic portfolio instance with the specified parameters and asset symbols.
It takes in the portfolio parameters and an array of asset symbols, and initializes the portfolio's internal state accordingly. Memory is dynamically allocated for the portfolio structure and the position vectors for each asset. The function also sets up the function pointers for the portfolio operations (update, value, pnl, delete) and initializes the cash balance and trading statistics. If any memory allocation fails, it ensures that all previously allocated resources are freed to prevent memory leaks.
| WU_PortfolioParams wu_portfolio_params_default | ( | void | ) |
This file implements a basic portfolio management system that supports multiple assets with a shared cash pool.
Returns default portfolio parameters with reasonable values.
The portfolio can process buy and sell signals, manage positions for each asset, and calculate the total value and profit/loss (PnL) of the portfolio. It also includes features such as transaction costs, slippage, stop-loss, and take-profit mechanisms. Returns default portfolio parameters with reasonable values.