Chaining investing modules to allow advanced features

Clean architecture has helped us add a rich feature set to our software.

Well-written software can turn into garbage, but not the other way round. This post will give a concrete example of why software quality matters.

If you keep cramming features into software, past a certain point it gets unmanageable: buggier; slower; harder to improve further, to integrate with other software, to hire developers who won’t hate working on it, etc. Proper software architecture can help avoid these. However, this must be done before the building phase.

We have been patiently improving our software since early 2016, focusing on the long term by building it well. An important aspect of clean software architecture is having separate and independent components, each of which does one specific job. One example is how our investing engine can ‘chain’ different components that each perform one investing task.

‘Chaining’ architecture

Normally, finding the best portfolio for a client requires simultaneously considering multiple – and often conflicting – goals1, such as tax efficiency, tracking a target, ESG, transaction costs, and holding costs. Portfolio optimization is the best known technique for dealing with tradeoffs rigorously. Our proprietary portfolio optimizer handles that.

However, there are some steps that we can do independently as a separate step before running an optimization to improve that tradeoff. Examples2:

  • selling legacy (i.e. not part of the target) positions, possibly partially
  • determining the sell orders (only) for tax loss harvesting, whether in a multi-asset-class or a ‘direct indexing’ portfolio
  • ‘tax-gain harvesting’ to avoid forfeiting expiring3 carryover losses; they never expire in the US, but this is needed in certain countries such as Japan and Korea.

We accomplish the above by ‘chaining’ such components. Component C1 will generate some orders. The next component C2 will use the same inputs as C1, except that we will update:

  • the portfolio to reflect the orders from C1: e.g. if C1 only sells, then C2 will have fewer tax lots, but also more cash.
  • the closed tax lots history to reflect those (assumed) trades. If component A sells AAPL, then component C2 will ‘know’ not to buy AAPL, so as to avoid a wash sale.

As a final step, we merge the orders generated by all those components.

Tangible benefits of a clean architecture

This clean architecture has helped us write software that is flexible enough to work across fairly distinct product categories:

  1. advisor-facing trading & rebalancing (used by Riskalyze)
  2. roboadvisors
  3. direct indexing with tax loss harvesting & ESG (piloted with various firms)
  4. general portfolio optimization (used by SIMON Markets for structured investments)

This flexibility even lets us support tax systems that are quite different than the US, such as avoiding expiration of loss carryovers, which this post described.

Notes

  1. These are the 5 optimization goals that we currently support. There can be others as well, such as stock- or asset-class-specific return expectations (to the extent they go beyond what is expressed in the target itself). The point is that there are multiple goals, which means we are faced with a tradeoff.
  2. At first, it sounds like these should be part of the tradeoff, but they do not have to be, and it is expedient to implement them as a pre-processing step. An explanation is beyond the scope of this post; please contact us for more.
  3. We are currently working on this feature. However, we already have all the other functionality mentioned in this post.

Direct Indexing outside the USA

Interest in Direct Indexing1 with Tax Loss Harvesting (DI + TLH) has rapidly increased recently, with Charles Schwab and Fidelity launching DI in the US. We have ascertained the applicability of DI + TLH for several other countries using our sophisticated software, continuously improved since 2016.

How do countries differ?

Tax codes are very complicated, but only capital gains tax matters for TLH. Cash dividend taxation also matters for realistic tax calculations in our investing simulations2. Therefore, other forms of tax (property, sales, etc.) are not relevant here.

We have run backtests / simulations by specifying (via our API) the tax code of several countries. Here is a list of interesting dimensions along which tax codes:

Capital gains marginal tax rates

US clients will be subject to different federal and/or state rates. Some countries have a flat tax on capital gains. Either way, this is a simple numeric parameter which our backtester API supports.

Short term / long term

In the US, tax rates for long-term (held over 1 year) capital gains are lower than for short-term, presumably to encourage long-term investing. For countries that do not have that distinction, we simply specify the same tax short- and long-term tax rates in the API 3.

Different annual tax day

Our software accounts for the effects of tax in a very realistic and accurate manner. We outline our rigorous approach in a paper published by a prestigious Portfolio Management Research journal (also here).

Our software “does your taxes” every April 15th in the US. This is more realistic than assuming that tax benefits happen on the day when we trade: otherwise the gain from a tax-loss harvest done on January 15th of 2021 would grow with the market until April 15th, 2022, so it would (erroneously) get 15 months of “free compounding”.

This date is also a configurable4 API parameter.

Wash sales

In the US, you cannot sell a security at a loss and buy back right away – or even within 30 days5. [Note: in some countries, the term ‘wash sales’ denotes market manipulation / ‘painting the tape’, which is very different.] Other countries do not have such rules. However, having no wash sales also means that it is possible to do selling and buying of the same security at the same time. Therefore, the code has to support this for non-US investing, but also maintain the same safeguards against simultaneous buying & selling in the US.

We can disable wash sale prevention for non-US investing via a simple API parameter.

Carryover loss expiration

In all tax codes we are familiar with, realized losses which exceed gains will get “carried over” into future tax years. That is, losses can reduce tax to be paid, but do not result in an outright refund. In certain countries (although not in the US), carryover losses expire after a certain number of years.

One simple solution would be to “tax-gain harvest” by selling some holdings at a large gain and buying them back. This would increase the cost basis of those holdings so that less tax will be due when they are sold later.

An even smarter solution, which we are currently implementing, is to do this in a way that increases the likelihod and benefit of future TLH activity. We have a choice of which “gainy” positions to sell. Spreading the selling among many positions at a smaller gain will likely result in more (though smaller) TLH opportunities later.

Sell-only transaction tax

Some countries impose a tax on securities transactions. In the US, the SEC Section 31 Transaction Fees is the closest equivalent, although it is not strictly a tax. In 2022, this is set to 0.229 basis points, and only applies to selling. In other countries, it can be significant, and even exceed 1%. This chart (for Europe only) is courtesy of our friends at ALLINDEX:

Our backtester ‘disimproves’ execution prices by the appropriate transaction tax, which is also an API parameter. We are able to specify separate rates for buying vs. selling:

… and also specify them separately for different security types. For example, in our US-based backtests, we only apply them to exchange-traded securities:

Conclusion

In order to bring the benefits of DI + TLH to countries outside the US, the strategy must be modified and tuned to a given country’s specific situation. For example, various trading thresholds should be higher in countries with a higher transaction tax, so that a client will only trade when it is worth the benefit. Our tax-aware backtester can simulate investing behavior accurately and realistically. This allows rapid testing out of many scenarios in parallel, which allows us to pick the most suitable parameters to run the strategy with.

Notes

1 Quick background: DI is when you buy individual stocks instead of a fund that holds those stocks. Some advantages are customization (e.g. ESG) and increased returns via TLH. TLH is when you selectively realize losses (but not gains) to offset realized gains outside the portfolio. The postponed tax payments can grow with the market, and in some cases tax can be altogether avoided.

2 Although our software does not have this restriction, our simulations use historical price data, so backtests is a more accurate term. However, we will use simulations, which sounds less technical.

3 The code screenshots are likely too detailed for readers of this post, but we want to emphasize that this is real production-grade code that works right now. That is, we’re not just writing an essay here.

4 Most of the work associated with software features is of course building them. However, being able to run them with different parameters (e.g. different tax rates) also takes some coding work. There are three ways to do this: using fixed values in the code (“hardcoding“), which is very inflexible; using configuration files, which get loaded at startup but then use the same parameters for all clients; and specifying all parameters in every API call. The latter is what we do. It takes more work, but it is the most powerful approach. It allows us e.g. to run client A using California state tax rates in parallel with client B using New York rates.

5 The spirit of this rule is to disallow you from doing this risklessly and only for the tax benefit. This would postpone the tax benefit, and in certain cases the client would even forfeit the benefit altogether. This is much more complex and beyond the scope of this post, but our code handles 7 different cases, and we have automated tests for about 250 permutations of cases.

Portfolio personalization made easier with Order Autocorrect

Clients can write simpler strategies, by giving more tedious work to our Backtester.

Background

You can already write tax-aware investing strategies in any environment or language (e.g. Python – see post) and use our Backtester to make sure it works correctly and to personalize it for individual clients. We just added functionality that makes it even easier to do so.

The problem

Here is an algorithm for a simple rebalancer:

When the portfolio deviates enough1 from a given target (e.g. 10% cash, 40% US stocks, 50% foreign stocks), then rebalance2 by:

  • selling overweight positions down to their target, and
  • buying underweight securities up to their target.3

Two concerns specific to wealth management are:

  1. tax efficiency: we need to choose the best tax lots to sell. As a simple example, if we bought 100 shares at $20, and another 100 shares at $25, it is almost always4 better to sell the latter, because they will be at a smaller gain (or larger loss).
  2. wash sale avoidance: to simplify, if you sell AAPL at a loss, you can’t claim the loss on your taxes if you buy back AAPL during the next 30 days. The main purpose of this IRS rule is to disallow riskless realization of losses5.

Dealing with #1 and #2 requires you to do extra work.

  • #1 means you have to sort tax lots by some tax efficiency metric6 and carve out a subset to sell.
  • #2 is even more tedious. There are 7 distinct scenarios, and our own Java implementation has thousands of lines to handle this, including tests.

Our “Order Autocorrect” feature lets you shift that work to our backtester. A strategy can just say “I want to sell 100 shares of AAPL”, and the backtester will ‘autocorrect’ that sell order to include tax lots that are tax-optimal, but also do not trigger wash sales.

Three choices

What happens if your strategy wants to sell more shares than it is allowed to by the wash sale constraints? Similarly, what if it wants to buy a security that would trigger a wash sale? The backtester supports three different ways to handle this:

  1. “Clip” the order sizes: say the strategy is trying to sell 100 shares of a security, but we can sell a maximum of 90 shares from the tax lots held; selling any of the remaining tax lots would trigger wash sales. Likewise, assume the strategy is trying to buy 100 shares of a security, but buying any amount would cause wash sales. One solution is to “clip” the order sizes, and buy & sell up to the maximum allowed. This is not perfect, because buy and sell orders are coordinated; e.g. if the strategy knew that selling stock X would trigger a wash sale, then perhaps it would not want to buy Y. However, this works well enough in many cases.
  2. Do nothing: this avoids the problem above.
    • In your backtest, that could mean that your strategy would be forced to wait up to 30 days between trading. This is not too bad; rebalancing thresholds are normally set so that you should rarely trade more than once a month anyway, except possibly during large market swings.
    • In production trading, there is usually some leeway about rare cases where trading has to be done manually (except maybe for robo-advisors). This situation can be flagged and handled manually if needed.
  3. Fail: similar to #2, except that this forces you to look at it more closely if it happens.

Regardless of whether you choose #1, #2, or #3, the “Order Autocorrect” will still choose the best tax lots for you.

Next steps

Instead of the backtester trying to repair what your strategy did, the backtester can also calculate wash sale restrictions and give them to your strategy. It would be up to your strategy to heed those restrictions, so you need to do more work, but at least you wouldn’t have to deal with the tedium of calculating wash sale constraints. This will avoid all the tradeoffs present in approaches #1 through #3.

Notes

1 A threshold for what counts as bad tracking will help avoid frequent small trades.

2 This subsumes the case where we invest an all-cash portfolio, because all the targets (except for cash) are maximally underweight, at 0% vs. their target.

3 Our own portfolio optimizer supports a smarter approach, where we take tax efficiency into consideration when we decide how much to sell in the first place. This is smarter – and much harder to implement – than choosing the best tax lots to sell after we decide how much quantity to sell. However, this blog post is not about our own investing strategies; it is about strategies that you would write and research with the help of our Backtester.

4 This is essentially the basis of tax-loss harvesting; it is beyond the scope of this blog post.

5 It is more complicated than that, and there are even cases where the tax loss is altogether forfeited, instead of postponed.

6 Most firms do this on the basis of capital gains. We additionally support a smarter approach, which takes into account the differential between short- and long-term capital gains marginal tax brackets applicable to each client.

Our wind tunnel for investing logic is now public

You can now use our backtester to gain insight on the after-tax behavior of your strategies.

Portfolio customization and personalization are helped by our backtester, a tool for validating investing behavior, which can now be used by third parties.

Background

Our tax-aware investing strategies (such as direct indexing with tax-loss harvesting) are built on our proprietary portfolio optimizer. We also built our own tax-aware backtester to validate our strategies’ behavior. This is akin to us manufacturing cars, and testing them in our own wind tunnel. We are now making this “wind tunnel” available to others.

Why backtest?

Backtesting helps tune a strategy to a particular client. For example, for a particular combination of capital gains tax rates, rebalance thresholds, tax loss harvesting thresholds, and target allocation, how does the strategy behave over a multi-year period? Does it trade too frequently, leave uninvested cash, have high tracking error, or realize a lot of tax gains?

It is not enough to come up with some investing logic that makes a single-point-in-time decision on how (and whether) to trade. Even if the logic is reasonable, the interaction between multiple days may make it suboptimal. For example, if we trade to a perfect portfolio today, we may reduce our ability to trade over the next 30 days due to the wash sale rule. Backtests help uncover such problems.

There are many backtesters out there, but ours has a strong focus on wealth management, and capital gains taxes in particular. It specializes in simulating realistic after-tax behavior of investing strategies.

Simple API

“Plugin” strategies can be implemented in any programming language and environment, as long as they implement a simple HTTP-based API. If you don’t want to use one of our existing strategies, you can write your own plugin in e.g. Python – possibly even using another portfolio optimizer, or even rules – and then use our backtester to analyze the behavior of your strategy. There are only 3 steps, which we will illustrate using a working, almost-production-grade tax-aware rebalancer we wrote in Python¹:

1. Initialization

Tells the backtester what settings to use to run the investing strategy. Here, we specify 3 different ways to charge account fees (0, 10, and 20 bps annually), and 4 rebalance thresholds. This also gives information specific to all backtests in this group: date range, target allocation, etc.

2. Single day’s run

Takes in as an input the current state of the account (today’s holdings, market data, etc.) and returns orders (if we decide to trade), plus our reasoning.

The following code will create orders without tax-lot-level detail (sellUnspecifiedLots), but the backtester is smart enough to “auto-correct” them to use the best tax lots! This simplifies your strategy, by allowing it to leave the work of wash sale avoidance and optimal tax lot selection to the backtester, in most cases. It is the subject of our next blog post.

3. Processing of backest results

At the end of the backtest, we get a table of 500+ metrics, such as money- and time-weighted returns pre- and after-tax, various flavors of tracking error, etc. The code could do something with them. Either way, the backtester additionally generates tens of files with daily detail, such a tax-lot-level holdings at the end of each backtest day. Those are too large to return over this API, but users of the backtester can inspect them manually or automatically.

This prints the following. We formatted it manually to show the 3×4 grid of input settings; rows are ‘fee rules’ (0, 10, and 20 bps annualized), and columns are the 4 rebalance thresholds. As expected, money-weighted returns decrease by about 10 bps as we go down the rows from 0 to 10 to 20 bps of account fees.

{'values': [1.055893, 1.055537, 1.055568, 1.05538, 
            1.054855, 1.054387, 1.054474, 1.054283, 
            1.053785, 1.053024, 1.053409, 1.05319], 
'description': 'money-weighted returns, for portfolio held by us, annually compounded, annualized, ignoring embedded gains, in bps', 
'searchLabels': ['Returns', 'Basis points']}

That’s all you need to do. Note that these 150 lines of code are for creating a new strategy from scratch; making an existing tax-aware investing strategy use the backtester should be even easier.

Summary

We have created our own implementations of different tax-aware investing strategies, such as a multi-asset-class portfolio rebalancer (possibly with tax-loss harvesting), and direct indexing with TLH. However, clients who want to use their own strategies can still use our backtester to gain insight on how to tune them and customize them to their individual clients. It only takes a few lines of code.


Notes

¹ We formatted the code to reduce size on this page.

On-the-fly ESG attribute creation

Arbitrary mathematical formulas can be used by our software to generate new ESG scores on the fly, based on scores published by data providers.

Background

ESG (Environmental, Social, and Governance) scores are a popular way of customizing portfolios. One can reduce the weights of stocks with bad ESG scores and/or increase the weights of stocks with good ESG scores. Those scores (e.g. ‘AAPL has an environmental score of 8 out of 10‘) can be sourced from one or more ESG data providers. Client-specific instructions can describe how exactly to change the weights based on those ESG scores – e.g. ‘for any stock with an E score of less than 3 out of 10, reduce its weight by 20%‘. However, clients may want to customize their portfolios based on some combination of ESG scores, instead of a single ESG score published by a single provider. Here are some reasons.

Examples

ESG data are too granular: One particular data provider includes hundreds of ESG attributes at fine granularity. Their least granular scores are E, S, and G; there is no combined single ESG score one can use directly.

Not relying on a single provider: ESG data are subjective, unlike financial data. To smooth out differences by provider, it may be useful to use the average ESG score from all those providers.

Our solution

We have built¹ a mechanism that allows constructing any ESG-related score from existing ones. Here are some examples of what we can define this way:

  1. Average_esg = (E + S + G) / 3
  2. Geometric_average_esg = ∛(E * S * G); possibly overkill, but the mechanism is general enough to allow any formula; it’s not just linear combinations of existing ESG scores.
  3. We can calculate the average of “collared” values, across multiple ESG data providers, to get rid of outliers. This is similar to filtering out very positive or very negative reviews of a product to get a more stable score.

These dynamic, ‘on-the-fly’ ESG-related scores are defined in an ordered list. Dynamic scores that are defined later in the list can also rely on previously defined dynamic scores, not just existing ones supplied by the ESG data providers.

This code example implements #1 from above:

singletonAllDynamicEsgAttributeCalculatingInstructions(
  singleDynamicEsgAttributeCalculatingInstructions(
    label("ESG single score as average of E, S, and G, dynamically generated"),
    DYNAMICALLY_GENERATED_ESG_AVERAGE_SCORE,
    "1 / 3.0 * (E + S + G)",
    rbMapOf(
        // This maps the strings in the string formula above 
        // to the ESG attributes in the files
        "E", ENVIRONMENTAL_PILLAR_SCORE,
        "S", SOCIAL_PILLAR_SCORE,
        "G", GOVERNANCE_PILLAR_SCORE),
    emptyRBMap(), // no long attributes in this formula
    Range.closed(0.0, 10.0), // make sure calculated ESG is between 0 and 10
    // If one or more of E, S, G are missing, then the value
    //  of this dynamically generated ESG attribute will also count as missing.
    esgDoubleAttributeMissingValue())),

To clarify: ESG scores (whether supplied by ESG data providers or calculated on the fly) are not by themselves instructions on how to increase/ownership of a particular stock. Instead, they are inputs into a formula that decides how to do so. This mechanism gives us better control of those inputs.

Summary

ESG data are subjective and require research. Software cannot calculate e.g. a count of controversies in the news.

However, it is often useful to create new ESG data on the fly based on existing data. Our software can do that.


Notes

¹ We rely on a third-party Java library to parse arbitrary mathematical expressions.

Unbiased measurement of tax-loss harvesting benefits

Our software “does your taxes” on April 15th of every backtest year, for more accurate & unbiased estimates of the benefits of tax-loss harvesting.

Background

When estimating the after-tax benefit of tax-loss harvesting (TLH) strategies, a common simplifying assumption is that offsetting tax savings get posted to the account on the same day of a TLH sell order. However, in practice, one would have to wait until tax time (April 15th of the following year) to see the benefit. Such a simplification biases results by giving tax savings more time to grow with the market, thereby making after-tax returns look better.

Our software takes the cleaner – though harder to implement – approach of “doing your taxes” on April 15th of every backtest year.

Example

Assume that on Jan. 25, 2020, the system sells 1,000 shares of XYZ (bought at $30 per share, long-term, without loss of generality) for $26 per share. The account has a realized loss of ($30 – $26) * 1,000 = $4,000. Using a long-term tax rate of 20%, this results in a 20% * $4,000 = $800 tax savings. [Note: to keep this example simple, we will assume here that there are always other long-term capital gains to offset against (vs. the $3,000 cap against ordinary income), so losses do not have to be carried forward. This is a fixed assumption that even the biggest firms make, but we do not; see here.]

However, in reality, that $800 won’t just appear in the account on Jan. 25, 2020, the day of the trade. Instead, the client will prepare his / her tax return in the next year, and then receive that $800 benefit (i.e. a reduction in tax owed) around April 15 of 2021, the day tax returns are due¹.

On average, if such TLH trades are equally spaced throughout the year, and considering that April 15th is 3.5 months into the year, then the simple-yet-inaccurate approach would give those tax savings 6 + 3.5 = 9.5 extra months to grow with the market.

Accurate approach

In our backtests, we “do your taxes” on the annual tax day (first market day on or after April 15th) for all realized taxes incurred in the previous year, and make any tax payment (or deposit any “refund” – really a reduction in tax owed) afterwards.

Disadvantages

  1. Harder to implement.
  2. Must avoid negative cash: if a large tax payment is due on April 15, and the account has insufficient cash, then we would need to sell stock in the backtest to make the tax payment.
  3. Requires cleaner after-tax values. A big TLH sell on Jan. 25, 2020 would result in a lower total cost basis for the portfolio (thereby increasing the after-tax liquidation value right away), while an offsetting tax refund will appear on Apr. 15, 2021. Extra work is needed to avoid this looking like a spurious drop in the after-tax liquidation value on Jan. 25, 2020.
  4. Having a large tax refund appear on a single point in time can make the results look noisy. If e.g. prices are very cheap around April 15th, 2021, and we invest that large “refund” (a tax offset, really) on that day, then total returns would look high. We are aware of this, and have implemented a simple way to avoid this.

Advantages

  1. More realistic and accurate because we avoid extra compounding. In the simple approach, “cashing in” the TLH benefit right away would result in investing in securities whose returns have more time to compound². In the example, that would be roughly 15 months (Jan. 25, 2020 to Apr. 15, 2021). Therefore, the simple approach will (on average) erroneously conclude that the after-tax performance of enabling TLH is higher than it actually is.
  2. More realistic and accurate because we can apply proper netting of short/long term gains/losses according to IRS rules. It is only possible to do this right if we know the aggregate values for an entire tax year. Moreover, this provides a basis to handle loss carryovers from previous years and to calculate any remaining loss carryovers for later, which makes our tax calculations even more realistic.

Summary

We have been obsessing about investing sophistication and rigor since March 2016, when we started work on our software. We always prefer to do things correctly, even if it’s more work, and even if it penalizes the calculated TLH after-tax performance.


Notes

¹ Note that the opposite is also true (i.e. tax payments are not actually due on the day a gain is realized), although only in the context of regular rebalancing, since TLH will not realize gains.

² “Compound” is not the best term here, since this is not bank interest, and securities may move up or down; however, securities markets trend upwards over the long term, so the value will go up, on average.

Replacing ESG portfolio tilts with optimization

How our proprietary portfolio optimizer improves upon the industry standard approach

Background

With Direct Indexing (DI), instead of buying a fund that tracks a stock index (such as an index ETF), we buy the individual stocks. DI can increase after-tax returns through tax loss harvesting. Another benefit, which is not applicable just to taxable accounts, is the ability to customize a portfolio for Environmental, Social, and Governance (ESG) concerns1. For example, a client may want to decrease holdings in high-carbon-footprint stocks relative to the weights in the index being tracked2. 

Tilts

The industry standard approach to improve the ESG score of a portfolio is to “tilt” the weights of stocks relative to their weight in the index. For example, if Chevron is 4% of the index, we reduce the target percentage, but not so much as to cause too much tracking error – so perhaps we settle on 3%. In general, index constituents are tilted up (for “good” stocks) or down (for “bad” stocks) as needed, the total is normalized to add up to 100%, which effectively creates a new custom index. The tilt can also vary so that “somewhat bad” stocks get affected less than “very bad” ones3.

Tilts have a simple qualitative explanation: “we bought less of this undesirable stock“. They also work with simple (non-optimization-based) software: you can do a regular portfolio rebalance on this new custom tilted index. Finally, tilts work well enough if we can actually get to a portfolio that resembles the tilted one.

However, that is not always possible for several reasons. Perhaps we cannot sell the overweight stocks (or buy the underweight ones) because we want to avoid wash sales or capital gains. This can be a problem when we combine DI with tax-loss harvesting, which results in more trading, and hence more situations where wash sales and capital gains must be avoided.

Sidebar – optimization

Optimization is, at its core, a rigorous way to evaluate tradeoffs between goals that may conflict. Our software currently (Jan. 2021) supports 5 such goals:

  • Tracking: the portfolio should be similar4 to a target.
  • Tax: avoid realizing capital gains; attempt to realize capital losses.
  • Transaction cost: reduce trading, and prefer trading securities that are cheaper to trade.
  • Holding cost: e.g. prefer holding ETFs with lower expense ratios.
  • ESG: prefer higher portfolio-wide (i.e. weighted by holdings) ESG scores.

ESG “goals”: an improvement over tilts

Clients care about the portfolio-level ESG scores. Their specific stock-level holdings are only a means to that end. Of course, one coarse way to reduce carbon footprint of the entire portfolio is to tell the system to reduce each high-carbon-footprint stock. However, it is not the same.

Extending our food analogy, if adding an ESG goal to portfolio optimization is like making a meal with the best combination of cost and healthiness, tilts are like instructions to use half as much ham and ranch dressing. Tilts sound right, and usually push outcomes in the right direction, but they do not directly address the high-level goal. This can result in suboptimal outcomes that are not intuitive to foresee.

Example

Say both Chevron (CVX) and Exxon Mobil (XOM) both have a target of 4%, but have been tilted down to a target of 3% because they both have a high carbon footprint. Assume there are only two choices5:

  1. 2.6% CVX, 3.4% XOM
  2. 3.0% CVX, 3.0% XOM

A simple approach that uses tilts would always prefer #2: CVX is underweight its tilted target of 3%, and XOM is overweight its tilted target of 3%. Of course, CVX and XOM are both underweight their original (untilted) target of 4%, so intuitively #1 and #2 should be equally desirable6.

One may say “OK, the system really prefers one of the two portfolios, but they are equivalent, so I don’t care in the end.” However, the problem becomes more evident in the presence of other – possibly conflicting – portfolio goals. Take a situation where it is actually preferable to move from #2 to #1, such as realizing a loss by selling CVX from 3% to 2.6%, and buying XOM instead, to 3.4% of the total portfolio. Compared to their respective targets of 4%, CVX would become more underweight, but XOM would become less underweight, so the effect on tracking would roughly balance out.

The optimization approach would say “tracking doesn’t really change, and the tax outcome is better, so let’s trade”. With tilts, even if a sophisticated optimization system were to be used (vs. a simple rules-based “rebalancer”), the system would think that improving the tax situation would also increase the expected tracking error, and (erroneously) avoid trading.

Summary

Our proprietary portfolio optimizer, developed over the last 5 years, allows ESG scores to be considered alongside other portfolio goals. This is a more natural way to specify how much a client cares about maximizing a specific ESG score. It also results in better investing outcomes, especially in situations where the best achievable portfolio cannot get too close to the ideal.


Notes

  1. Socially Responsible Investing (SRI) typically reflects a client’s personal values, whereas ESG focuses on objective aspects, such as having a cybersecurity policy. This distinction is not relevant in this post.
  2. This post focuses on portfolios that track a stock index, but the approach discussed can apply to any portfolio target.
  3. Exclusion filters are also common: instead of holding less of a “bad” stock, the client may want to hold none of it. However, they are effectively an extreme tilt (all the way down to zero), so we will not discuss them here. 
  4. We actually further break down tracking to cover two interpretations of ‘similar’: ‘looks similar’ (adheres to the nominal target percentages) and ‘has similar behavior’ (has similar factor exposures as per a factor-based risk model).
  5. We assume this to simplify the example; normally, there will be infinite possible portfolios. In this case, if both 3%/3% and 2.6%/3.4% are possible, then e.g. 2.9%/3.1% will also be possible, as will 2.8%/3.2%, etc.
  6. In practice, the misallocation penalties may not be linear (proportional): in our system, they increase faster as we move further away we go from the target. The idea is that we don’t care as much about 4% becoming 3.5% (e.g. due to price movement) as much as we care about 3.5% becoming 3% (which means we’re really starting to drift). The shape of the misallocation penalty function is highly customizable in our system. This detail does not invalidate our main argument, though.

Direct Indexing problems during big market drops, part 1

Our proprietary backtest infrastructure allows us to discover potential problems early on, and to fine-tune investing behavior.

Background

Tax loss harvesting (TLH) is a technique that can increase after-tax returns in taxable accounts. It does so by selling (“harvesting”) lossy positions, while replacing them in a way that attempts to maintain a similar exposure.

A widely implemented approach uses pairs of similar ETFs: buy X, and when it is at a loss, sell X and buy Y. Direct Indexing (DI) is more sophisticated1. Instead of buying “prepackaged” exposure to a stock index via an ETF or mutual fund, it buys the individual index constituent stocks, at the proportions defined by the stock index. When some holdings are at a loss, they are sold (“harvested”). By selling individual stocks instead of the entire basket, there are harvesting opportunities even when the index as a whole is up. The cash generated gets used to buy other index constituents, such that the resulting portfolio has similar behavior as the index. Typically this is done via a risk model, which tells you how similar different stocks are. As a simple example, if Exxon was just sold at a loss and is underweight, the risk model could tell us to make Chevron overweight. A more general example is when we sell 4 stocks from a portfolio that was already imbalanced with respect to the index. In that case, we may buy 7 other stocks, so as to correct:

  • any previous imbalance
  • the newly introduced imbalance from selling those 4 stocks
  • possibly another imbalance due to a cash deposit, cash dividends paid, a withdrawal, etc.

Over-harvesting problem

If the market drops by a lot, as it did on many days of March 2020, we could naively try to harvest (sell) too much compared to how much we would be able to buy. Let us break down this statement.

Selling

For a tax lot to be sold today2:

  • it must be at a big enough loss today.
  • it was not at a big enough loss yesterday3, otherwise we would have sold it then.

Having a tax lot cross that threshold is relatively uncommon. Therefore, the total harvesting amounts on any given day for an entire DI portfolio are not too large.

Buying

At any point in time, some stocks can be unbuyable for several reasons, such as:

  1. due to wash sale restrictions, if we sold them at a loss within the last 30 days. This includes today; we can’t sell at a loss and buy the same stock4.
  2. because they are already at the top of the acceptable range. For example, if AAPL is 4% of the index, DI will typically allow it to be within a range such as 2% to 6%, so as to keep it from dominating the portfolio.

Even when stocks are not completely unbuyable, they are always partially unbuyable due to the range restrictions, as per #2.

Why is this bad?

If we over-harvest, we will end up with a lot of uninvested cash, and therefore with tracking error (overweight cash, underweight stocks). Moreover, this is a particular bad kind of tracking error. Being overweight some stocks and underweight others will at least maintain some market exposure. However, cash does not move with the stock market. The result is bad, not just for a client’s reality (tracking error), but also perception. A client will be unhappy if an error creates extra uninvested cash, and therefore the client misses out on a market bounce. However, this does not work symmetrically: if the market drops further, they will not call to thank you for selling early due to a mistake.

We have implemented a fairly thoughtful and optimal solution to this problem, but that will be the focus of a follow-up post.

How did we discover this?

Most software is written by foreseeing scenarios ahead of time, and writing code to address them. For example:

  • If someone deposits cash into the account, then we must create buy orders for the correct amounts.
  • If a stock’s has tax lots at a loss greater than 2%, then we must sell them.

… and so on. We do that as well; we have to. However, this approach is not sufficient by itself, because not all scenarios are easy to foresee. The over-harvesting problem sounds obvious in retrospect, but you should not assume that all DI implementations handle it correctly. In fact, this very scenario affected a large firm in a very public and painful way.

We have built a sophisticated backtest infrastructure, which supports a complementary approach that can uncover such problems early on. It allows us to use the same exact code that would normally run in a production environment, and to simulate its behavior over a multi-year period in the past. This causes certain complex situations to arise organically, which may otherwise be hard to foresee. Over-harvesting is one such example.

Of course, it is not enough to generate such situations; we need to be able to know whether a behavior is wrong, so that we can fix the code to handle it. Here is how we do that:

  1. At the end of a backtest, the code generates a few hundred different metrics, such money-weighted returns, ex-ante and ex-post tracking error, etc.
  2. Afterwards, a different piece of code performs sanity checks on those metrics. As a specific example, we were alerted to the over-harvesting problem because the metric for “maximum ex-ante tracking error for any day in the backtest” exceeded an otherwise loose threshold.

One might ask: “if you can automatically detect wrong behavior in another piece of code that you yourselves wrote, why is it any harder to have that code be correct in the first place?” Detecting side effects of medicines is a good analogy. It is fairly easy to define what “normal” is under several health indicators (sleep, temperature, pressure, heart rate, etc.). There may be a few rare false positives or false negatives, but those health indicators are a useful guide in most cases.

Mapping our analogy to the original point, detection is particularly valuable when:

  • It is simple compared to the solution. Measuring the end result (heart rate; maximum cash %) is much simpler than making sure the end result will always cover every possible scenario, including rare ones (using the drug while simultaneously taking another rare drug; second-biggest market drop in the last ~90 years).
  • There are not too many false positives (higher but still normal heart rate; cash just a bit more overweight than normal) or false negatives (patient experiencing an hard-to-detect health problem; portfolio being moderately imbalanced on every day instead of extremely imbalanced on a single day only).

Summary

Our proprietary backtest infrastructure helps us validate investing behavior extensively during development time. This is an improvement over performing some one-off investment research before rolling out an investing product. Detecting problems ahead of time is obviously better than getting a call from an unsatisfied client who discovers a problem months after rolling out DI.


Notes

  1. Direct Indexing also allows values-based investing, where certain stocks may be excluded, or held at different weights than their normal target in the stock index, so as to conform to an investor’s values (e.g. a vegetarian avoiding meat processor stocks). Unlike “DI with TLH”, this is also applicable to tax-deferred accounts. We support that as well – not just exclusions, but also tilts – but it is not as interesting from an investment sophistication angle, and we are ignoring it for purposes of this post.
  2. This assumes a daily schedule for evaluating accounts to decide whether to harvest losses (though not necessarily trading daily, because it will not always be worth the trouble). It can be done less frequently, especially if it requires human intervention, or more frequently, especially on days with big intraday moves. In practice, daily is frequent enough.
  3. This decision may also consider the entire position, not just a single tax lot. We may not want to sell too small a tax lot at a loss today, because buying later will cause a wash sale, so it ‘locks out’ that stock during the next 30 days, so we may want to limit selling to large enough amounts.
  4. Although there are a few cases involving a combination of taxable and tax-deferred accounts where the tax loss is forfeited forever, in most cases a wash sale results in the tax loss being disallowed, but it can be used to reduce liability in the future. However, in practice, it is customary to disallow wash sales altogether, except for scenarios such as withdrawals, where a client may not care about wash sales.

Tax-smart withdrawals and partially ordered sets

Audience requirements: Some Java, but only for the last half.

Problem description

When a client makes a large enough withdrawal, we may need to suspend some of our normal restrictions, such as avoiding wash sales1, or avoiding selling of (highly-taxed) short-term capital gains2. If the client wants to withdraw money, we cannot just tell her “sorry, that would cause a wash sale”.

Solution

An architectural principle of ours is that, for almost everything that could be a hard-coded constant or a configuration file setting, we instead allow it to be dynamically passed into the system on a per-API-call basis3. That is, investing customer X’s portfolio could use one set of settings, and then one second later the system can be called with customer Y and his (possibly different) settings.

In keeping with that spirit, it is possible to specify a “withdrawal relaxation path” dynamically. The Java code reads like English:

taxAwareEigenRebalancerRelaxationPathInstructions(
    emptyTaxAwareEigenRebalancerSettingsRelaxationStepInstructions(),
    relaxTo(onlySellShortTermLosses(),        DISALLOW_WASH_SALES),
    relaxTo(doNotSellAnyGains(),              DISALLOW_WASH_SALES),
    relaxTo(doNotSellShortTermCapitalGains(), DISALLOW_WASH_SALES),
    relaxTo(canSellAnything(),                DISALLOW_WASH_SALES),
    relaxTo(canSellAnything(),                ALLOW_WASH_SALES));

The idea is that, if it is not possible to fulfill the withdrawal with the restrictions implied by the settings in step N, we try the settings in step N+1, and so on, until it is possible for the withdrawal to go through (i.e. the underlying linear optimization is feasible).

Our mechanism is very flexible. It is possible to specify separate restrictions for short-term and long-term tax lots. The following example can be passed as a 1st argument to relaxTo above, and will not sell any:

  • short-term capital gain above 20%
  • long-term capital gain above 50%
  • short-term capital gain that will go long-term (and be eligible for lower tax) in 15 or fewer days
  sellPermissionsBuilder()
      .forShortTerm(doNotSellAbove(onesBasedReturn(1.2))
      .forLongTerm(doNotSellAbove(onesBasedReturn(1.5))
      .dontSellThisManyDaysBeforeLongTermGain(15)
      .build();

What is partial comparison?

Partial comparison is (roughly speaking) when not all items in a set are comparable. As an example, let us use a pair of portfolios (N, R): N can be liquidated now, whereas R can only be liquidated in 20 years (at retirement).

It is hard to disagree that it is always better if one or both of N and R have more money in them:

  • (100, 301) > (100, 300)
  • (101, 300) > (100, 300)
  • (101, 301) > (100, 300)

However, how do you compare (101, 300) and (100, 302)?

  • (101, 300) has a bigger amount that can be used right now
  • (100, 302) has more total money in it

Any preference for one or another pair of portfolios is not objective, and will depend on liquidity needs.

Why partial comparison?

We want to confirm that the sequence of relaxation steps is indeed in increasing “relaxation order”.

There is nothing inherently wrong if this is not respected. We can tell the system to try trading first under some loose restrictions (step 1), and – after that fails – try trading with stricter restrictions (step 2). The stricter step will always fail if the looser step failed. However, the 2nd step is a waste of resources. Even more importantly, it may mean that the person who constructed this sequence of steps made an error, so it is good to get an alert.

Partial comparison is relevant here, because “relaxation steps” are partially comparable. Take the following steps:

  • Step 1: do not sell short-term capital gains of over 10%, or long-term gains over 20%
  • Step 2: do not sell short-term capital gains of over 17%, or long-term gains over 27%
  • Step 3: do not sell short-term capital gains of over 14%, or long-term gains over 15%

Step 2 is more relaxed than step 1, as it is less restrictive in selling both short- and long-term gains.

However, there is no partial comparison of step 1 and step 3; step 3 is more restrictive with long-term gains, but less restrictive with short-term gains.

Our sanity checks will only complain if step K is strictly less relaxed than step M (K < M), but not when they are not comparable. Still, this has the potential to catch bugs, so it increases system safety.

Our Java support for partial comparison

In order to build our sanity checks, we formalized the concept of partial comparison in our code. Java has Comparable<T> and Comparator<T>, but there is no support for partial comparison, even in commonly used libraries such as Google Guava or Apache Commons. Therefore, we wrote our own.

Without too much code, here is a summary of what we added:

public interface PartialComparator<T> {
  PartialComparisonResult partiallyCompare(T o1, T o2);
}
public interface PartiallyComparable<T> {
  PartialComparisonResult partiallyCompareTo(T o);
}

PartialComparisonResult (code not shown): can be less-than, equal, greater-than, undefined (4 cases total). This also abstracts away the less-intuitive outcomes of Comparable#compareTo, which use {negative, 0, positive} to denote {<, ==, >}.

The following method will look at the comparisons of all fields of two objects, and determine whether there is a well-defined ordering or not. This generalizes the idea that, for class A, if all fields of object A1 are >= those of object A2, and at least one is >, then A1 > A2. If any field is not comparable, then A1 and A2 are not comparable.

public static PartialComparisonResult partiallyCompareMultiple(
    PartialComparisonResult first, 
    PartialComparisonResult second,
    PartialComparisonResult...rest)

Finally, the following throws an exception if the items in a list do not respect a certain partial comparison, as per the PartialComparator<T> passed in. One actually has to compare every pair of items, not just consecutive ones.

public static <T> void checkDecreasingPerPartialComparison(
    PartialComparator<T> partialComparator, 
    List<T> list, 
    String format, 
    Object...args) {
  forEachUnequalPairInList(list, (item1, item2) ->
      partialComparator.partiallyCompare(item1, item2)
          .getRawResult()
          .ifPresent(comparisonResult -> Preconditions.checkArgument(
              comparisonResult > 0,
              format,
              args)));
}

All this infrastructure will now be reusable for other cases in the future, beyond this specific scenario of withdrawal relaxation instructions.

Summary

It is possible to specify dynamically – and in a very understandable, English-language-like format – how we want the system to behave when there is a withdrawal. We are very meticulous about system safety, so we added checks that the sequence of constraint relaxation steps does not get stricter. We could have done this with a one-off, localized check, but we instead added support in the code for generalized partial comparison. This makes for cleaner code; also, we can reuse that infrastructure later, if needed.


Notes

  1. Very roughly speaking, a wash sale is when we buy and sell the same stock within a month. The IRS disallows claiming a capital loss in certain cases. It is there to prevent a largely riskless realization of capital losses just for tax purposes. Wash sales add undesirable for several reasons (beyond the scope of this post).
  2. Our optimization logic already penalizes selling of capital gains. However, it takes in an additional parameter that results in adding hard constraints to avoid bad tax outcomes, such as selling short-term capital gains, selling any long-term gains above 50%, etc. The idea is that, even if in some cases selling a short-term capital gain may improve the portfolio in some way (e.g. better tracking to the target allocation), in practice it looks bad to a client if we sell short-term capital gains. Note that this is highly configurable, so “no extra constraints” is still an option.
  3. One obvious advantage is that it makes the system very flexible. However, another big advantage is that we can have test code that compares what happens with one setting vs. another. For example, we can assert that, over the duration of an 8-year backtest, we will realize fewer tax gains if we prevent the selling of gains than if we do not. This, in turn, helps us ascertain that our investing logic is correct.

Easy, single-statement unit tests

Our testing framework lets us test our code more extensively, and with less effort. This makes the code simpler, easier to refactor, and results in fewer bugs.

Audience requirements: Java; unit testing.

Some background: our architecture

We divide all our java classes into 2 categories:

  • data/noun classes store data only, and have almost no logic, except for construction preconditions.
  • verb classes are stateless and implement the business logic.

Opinions may differ on this style, but it works well with dependency injection (e.g. Google Guice), and we have seen it used successfully elsewhere, so we like it.

We make heavy use of data classes instead of ‘more raw’ types. For example, we have a Partition class for representing “a collection of items with weights that sum to 1, i.e. 100%”. It is better than a simple Map<T, Double> because:

  1. Single check: We only need to check once that sum(values) ~= 1, at the Partition constructor. Otherwise, if 7 methods took a raw Map<T, Double> argument with implicit partition semantics, we would need to have 7 preconditions in the code. That would clutter the production code, and also require 7 more tests. Secondarily, it’s better performance to check the preconditions only once.
  2. Clearer semantics than relying on the name of a parameter, which may not be descriptive – or even correct.
  3. Type safety avoids bugs. Example: say OptimizationResult stores the solution from the optimizer in a Map<AssetClass, Double>, but there’s no restriction that the values sum to 1 (e.g. perhaps it is in dollars, not %)1. Passing a Partition instead of an OptimizationResult will not compile, which is good. However, with a raw Map<AssetClass, Double>, it is possible to make such a mistake.

With 600+ data classes, and 185,000+ lines of test code (as of this writing), it pays to have systematic ways to test data classes, and to simplify the testing of verb classes.

Matchers

We make extensive use of the Hamcrest matcher framework. You can think of a matcher as a test-only, parametrizable equals().

We only implement hashCode & equals in our data classes in very few cases, such as when its instances will be used as keys to some map. Otherwise, we prefer using a matcher:

  • Since matcher code lives in test files, we avoid cluttering up prod code with test-oriented logic.
  • Matchers are like a parametrizable equals() in a way. For instance, we can compare two objects subject to an epsilon passed in, and use a different epsilon in different cases.
  • Matchers make it easier to read and write unit tests of ‘verb classes’.

Our data classes each have corresponding test classes that extend RBTestMatcher, a class that we built (simplified below):

public abstract class RBTestMatcher {
  public abstract T makeTrivialObject();
  public abstract T makeNontrivialObject();
  public abstract T makeMatchingNontrivialObject();
  protected abstract boolean willMatch(T expected, T actual);
}

Here is a concrete example for a TradeAmounts class, which stores the $ amount bought and sold, broken down by stock.

public class TradeAmountsTest extends RBTestMatcher {

  public static TradeAmounts emptyTradeAmounts() {
    return tradeAmounts(emptyBoughtTradeAmounts(), emptySoldTradeAmounts());
  }

  @Override
  public TradeAmounts makeTrivialObject() {
    return emptyTradeAmounts();
  }

  @Override
  public TradeAmounts makeNontrivialObject() {
    return tradeAmounts(
        new BoughtTradeAmountsTest().makeNontrivialObject(),
        new SoldTradeAmountsTest().makeNontrivialObject());
  }

  @Override
  public TradeAmounts makeMatchingNontrivialObject() {
    return tradeAmounts(
        new BoughtTradeAmountsTest().makeMatchingNontrivialObject(),
        new SoldTradeAmountsTest().makeMatchingNontrivialObject());
  }

  @Override
  protected boolean willMatch(
        TradeAmounts expected,
        TradeAmounts actual) {
    return tradeAmountsMatcher(expected).matches(actual);
  }

  public static TypeSafeMatcher tradeAmountsMatcher(
        TradeAmounts expected) {
    return makeMatcher(expected,
        match(v -> v.getBoughtTradeAmounts(), f -> boughtTradeAmountsMatcher(f)),
        match(v -> v.getSoldTradeAmounts(),   f -> soldTradeAmountsMatcher(f)));
  }

}

Subclasses of RBTestMatcher just need to implement:

  • makeTrivialObject to return the most trivial object possible (in this case, nothing traded).
  • makeNontrivialObject to return most general object possible (e.g. we bought and sold different amounts, and in multiple stocks – not just one).
  • makeMatchingNontrivialObject that should ‘match’ makeNontrivialObject, but not be equal in the traditional sense of equality: e.g. the two could be off by some epsilon.
  • willMatch: a simple predicate to return true if two objects are similar enough to consider to be matching.

By convention, we also add a static method that returns a matcher (here, tradeAmountsMatcher). Hidden behind the syntactic sugar of makeMatcher() and match() is the fact that it in turn relies on boughtAmountsMatcher and soldAmountsMatcher. Since all of our data test classes adhere to the RBTestMatcher convention, this is not a restriction.

Of course, additional tests may be necessary, most commonly for preconditions. For example, TradeAmountsTest also tests (not shown here) that a stock cannot both be bought and sold.

There are several advantages to having every data test class extend RBTestMatcher:

  • We get a free unit test for the matcher logic. TradeAmountsTest inherits a unit test called RBTestMatcher#matcherMetaTest() (not shown), which checks that:
    • makeTrivialObject does not match the two non-trivial objects
    • all 3 objects match themselves
    • makeNontrivialObject matches makeMatchingNontrivialObject
  • We get a free unit test for toString(), also inherited from RBTestMatcher. It’s a simple test that just calls toString() and ignores the return value, but at least it ensures no exceptions are thrown.
  • We some free rudimentary testing of the constructors, insofar as no exceptions are thrown from within the 3 make*Object methods.
  • It standardizes the format of the data class test code, making it easier to read.
  • It lets other tests construct a realistic test object without needing to know how to construct one (e.g. knowing what would constitute valid constructor parameters). For example, TradeAmountsTest#makeNontrivialObject builds an object by utilizing in turn BoughtTradeAmounts#makeNontrivialObject.

Single-statement unit tests

Another big benefit of all data classes having matchers is that verb class unit tests can be much more concise – in some cases, a single Java statement.

Take a look at this extensive test2 of summarize() in TradesToTradeAmountsSummarizer. The logic is fairly straightforward: it adds up the corresponding amounts bought and sold in the Trades object in the input, and summarizes to a TradeAmounts object, which only records amounts bought and sold.

assertThat(
    makeTestObject().summarize(
        trades(
            boughtTrades(iidMapOf(
                STOCK_B1, boughtTradesWithOrder(
                    buyOrder(STOCK_B1, buyQuantity(11), price(100.10), DUMMY_TIME),
                    rbSetOf(
                        boughtTrade(STOCK_B1, buyQuantity(2), price(100.02), DUMMY_TIME),
                        boughtTrade(STOCK_B1, buyQuantity(3), price(100.03), DUMMY_TIME))),
                STOCK_B2, boughtTradesWithOrder(
                    buyOrder(STOCK_B2, buyQuantity(44), price(100.04), DUMMY_TIME),
                    rbSetOf(
                        boughtTrade(STOCK_B2, buyQuantity(5), price(100.05), DUMMY_TIME),
                        boughtTrade(STOCK_B2, buyQuantity(6), price(100.06), DUMMY_TIME))))),
            soldTrades(iidMapOf(
                STOCK_S1, soldTradesWithOrder(
                    sellUnspecifiedLots(STOCK_S1, sellQuantity(11), price(200.10), DUMMY_TIME),
                    rbSetOf(
                        soldTrade(STOCK_S1, sellQuantity(2), price(200.02), DUMMY_TIME),
                        soldTrade(STOCK_S1, sellQuantity(3), price(200.03), DUMMY_TIME))),
                STOCK_S2, soldTradesWithOrder(
                    sellUnspecifiedLots(STOCK_S2, sellQuantity(44), price(200.04), DUMMY_TIME),
                    rbSetOf(
                        soldTrade(STOCK_S2, sellQuantity(5), price(200.05), DUMMY_TIME),
                        soldTrade(STOCK_S2, sellQuantity(6), price(200.06), DUMMY_TIME))))))),
    tradeAmountsMatcher(
        tradeAmounts(
            boughtTradeAmounts(iidMapOf(
                STOCK_B1, money(doubleExplained(  500.13, 2 * 100.02 + 3 * 100.03)),
                STOCK_B2, money(doubleExplained(1_100.61, 5 * 100.05 + 6 * 100.06)))),
            soldTradeAmounts(iidMapOf(
                STOCK_S1, money(doubleExplained(1_000.13, 2 * 200.02 + 3 * 200.03)),
                STOCK_S2, money(doubleExplained(2_200.61, 5 * 200.05 + 6 * 200.06)))))));

This was a clean implementation as a single Java statement.

Let’s imagine we didn’t have tradeAmountsMatcher, and instead implemented hashCode/equals in TradeAmounts, BoughtAmounts, and SoldAmounts.

A simple assertEquals might not work, because double arithmetic may result in tiny deviations. Of course, we could relax the various equals() methods to check equality subject to some epsilon. However, that gets complicated quickly: the epsilon may not always be a fixed amount, yet equals() cannot take epsilon as a parameter.

Therefore, the test logic would have to be something like this (shown in pseudocode):

  • Get output of summarize()
  • For BoughtAmounts:
    • Check that the map has entries for B1 and B2 (no more or fewer stocks)
    • For B1, confirm the $ amount
    • For B2, confirm the $ amount
  • Same for SoldAmounts

The deeper the structure of an object (e.g. a tree of collections of trees), the faster this will get unwieldy very quickly. Instead, our test matcher allows us to write such a test as a single Java statement.

Summary

We are big proponents of automated testing, instead of manual QA. To that end, we have built infrastructure to make it much easier to write and read automated tests. This results in test code of higher quality and wider coverage, making it easier to improve the code via refactors, and to catch bugs.


Notes

1. This is not a good example in the context of our own code base, because we rarely use plain doubles anyway. Even if we used raw maps in our code, the Partition would be a Map<AssetClass, UnitFraction>, where UnitFraction is forced to be within 0 and 1, and the OptimizationResult (if it were in $ terms, which it is not) would be a Map<AssetClass, Money>. Those two are not interchangeable, even by accident. A better example would be a TargetPartition and HeldPartition, where each can instead be represented as a raw Partition, with the former representing the target/goal, and the latter representing the current holdings before any trading. The two are conceptually different, so we should never want to use one instead of the other, yet both contain a Partition inside them.

2. Inside this test code, doubleExplained() is a handy in-line way to show an actual value that gets used in a test alongside the calculation that gave rise to it. Otherwise, the actual value used may look arbitrary. Also, DUMMY_TIME is a predefined constant which we use to imply that time does not matter in a calculation; here, that makes sense, because we are just summing dollar amounts.

Create your own website, free on WordPress.com.Create your own website.
Start free