{'fraction_non_alphanumeric': 0.03974536023443026, 'fraction_numerical': 0.0121593856310418, 'mean_word_length': 4.563050402848042, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 2, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Conditional Value-at-Risk for Quantitative Trading: A Direct Reinforcement Learning Approach

We propose a convex formulation for a trading system with the Conditional Value-at-Risk as a risk-adjusted performance measure under the notion of Direct Reinforcement Learning. Due to convexity, the proposed approach can uncover a lucrative trading policy in a"pure"online manner where it can interactively learn and update the policy without multi-epoch training and validation. We assess our proposed algorithm on a real financial market where it trades one of the largest US trust funds, SPDR, for three years. Numerical experiments demonstrate the algorithm's robustness in detecting central market-regime switching. Moreover, the results show the algorithm's effectiveness in extracting profitable policy while meeting an investor's risk preference under a conservative frictional market with a transaction cost of 0.15% per trade.


I. INTRODUCTION
Financial markets exhibit severe stochasticity with nonstationary behavior [1]. With this, the financial market can be viewed as a stochastic system with high uncertainties. To optimize a financial performance measure, that system, indeed, requires tools from control theory. Recent developments in control provided strong tools that are yet to be utilized in the field of quantitative finance, in particular asset allocation and portfolio management problems. Such problems can be looked at through the lens of stochastic optimal control [2].
The emergence of the Reinforcement Learning (RL) [3], a machine learning paradigm that intersects with optimal control theory, motivated researchers to explore its application in the field of asset allocation and portfolio optimization. The first two works that considered formulating the problem using RL were the ones by Neuneier [4], and Moody and Saffel [5]. Neuneier implemented estimation of value functions with Q-learning while Moody and Saffel explored the use of direct policy search, which they called Direct Reinforcement Learning (DRL). Therefore, the adoption of RL as a tool to solve asset allocation and portfolio optimization problems is appealing since, under that paradigm, the controller can learn an optimal policy in an online manner.
Formulating the problem under the notion of DRL composes of several main parts. The first is the sensory part responsible for sensing the financial market's environment (system). The other part generates trading signals (control) following a parametric policy based on the environment's states 1 . Lastly, we evaluate the policy pursued by the controller through a "reinforcing signal" that is received from the environment. That signal acts as feedback of the policy effectiveness in optimizing a predefined financial performance measure. Noteworthy, the mathematical properties of performance measures play a crucial role in determining the quality of the final obtained policy. That, in particular, motivates us to explore performance measures that can introduce convexity into the problem. Thus, we present the Conditional Value-at-Risk (CVaR) as the financial measure in this work. To the best of our knowledge, this is the first work that proposes a convex performance measure with CVaR in the development of a trading system under the notion of DRL.
The pioneering work of Rockafellar and Uryasev [6] was the first that introduced CVaR. We can fundamentally define CVaR as the expected low-probable but significant losses that may incur during the investment horizon. Mathematically, CVaR is a statistical quantity that measures the expectation of large losses that fall within the tail of the loss distribution. Due to the appealing mathematical properties of CVaR, such as convexity, it has grabbed the attention of researchers in the field of finance. In [7]- [9], the portfolio optimization problem was solved with CVaR being an objective function or a constraint. In [10], a risk-constrained RL algorithm that maximizes the expectation of the value function while meeting a constraint on CVaR was proposed. Moreover, a DRL algorithm that searches for CVaR-optimal policy was proposed in [11].
In this paper, we propose a trading system that follows the DRL notion introduced in [5] while considering CVaR as the system's performance measure. Our selection of CVaR is motivated by financial and mathematical aspects. Financially, searching for an agent's policy based on optimizing CVaR prevents the agent from making risky decisions that may cause significant losses. Therefore, it learns a policy that is aware of risk management under the severe uncertainties within the financial market. From the mathematical aspect, under careful formulation using CVaR, we can ensure convexity of the problem while keeping it general. The convex formulation provides provision for finding an optimal global policy, which allows for a fast online algorithm and leads to faster convergence. In fact, all of our experiments in this paper were implemented in a pure online manner, where the controller can interactively learn and update its policy "on the go" without multi-epoch training and validation. Moreover, they demonstrate the controller's robustness in handling the underlying uncertainties in the financial market. Noteworthy, convexity is not usual in quantitative finance, making our method appealing, avoiding solutions at local minimum that may cause unpredicted portfolio performance with high in-curred losses [12].

A. Related Work
To the best of our knowledge, Moody and Saffel were the first who introduced the concept of policy search RL into trading problems under the name of DRL [5]. They endeavored to design subtle performance measures that enhance the controller's risk awareness while trading. Their first measure was the Sharpe ratio, which is defined as the mean of achieved investment returns over its standard deviation [13]. In that sense, the Sharpe ratio is a symmetric risk-performance measure since it counts for the variance of both upside and downside returns. They, therefore, developed an asymmetric risk measure that counts for the downside returns, which they called the Downside Deviation ratio. Bertoluzzo and Corazza [14] explored a performance measure that maximizes the upside returns while minimizing the downside risk. In that sense, the learned policy is eager to maximize the positive returns while simultaneously avoiding decisions that may result in losses. In [15], [16], total returns and Sharpe ratio as the system's performance measures were implemented using a sparse-coding algorithm and deep fuzzy learning, respectively. Almahdi and Yang [17] designed the performance function following the concept of Calmar ratio, which is defined as the ratio of expected returns to the expected maximum drawdown (MDD), i.e., the largest observed loss from a top of wealth to a trough [18]. Noteworthy, the two performance measures, total returns, and Sharpe ratio, are the most common among others and they were extensively scouted with different deep learning architectures [19]- [22]. Although most of the works report a promising result of their trading systems, their performance measures are non-convex. Hence, the optimization algorithms will probably converge to a local optimum, especially in deep learning algorithms where the problem is highly non-convex. To this end, we believe that our work takes the research of trading systems with the DRL notion to the next level, where we introduce CVaR as a risk-performance measure that leads to a convex formulation for the problem.

B. Contributions
In this work, our contributions into the field of developing trading systems under the notion of DRL are summarized as follows: • We bridge the gap between quantitative trading via DRL and the literature by introducing CVaR as a performance measure. • We provide sufficient conditions for the convexity of our model, which ensures superior performance for various setups and considerations. • We propose an online algorithm that can actively discover and update a lucrative policy through a single run over the data. In other words, our proposed system can learn without multi-epoch training and validation. The manuscript is organized as follows. We discuss the problem's preliminaries in Section II. Then, we provide our exposition for the proposed model in Section III. The numerical experiment is exhibited in Section IV. Section V discusses several potential generalizations for our proposed model, and the manuscript is concluded by Section VI. II. PRELIMINARIES Let p 1 , p 2 , ..., p t denote the price quotes of the financial asset, which are released by the exchange centers. We let the financial market represent the controller's environment, where its states are functions of the past n prices, and are denoted by the vector x t := h t (p t , p t−1 , ..., p t−n ), where h t is continuous for each t. When the controller senses the environment's state x t , it takes an action following a deterministic policy denoted by π t ∈ [−1, 1], and any π t > 0 indicates a long position while π t < 0 indicates a short position 2 . Based on the action π t at a state x t , the controller receives a reinforcing signal from the environment that represents the achieved return at the immediate next time step, denoted by R t+1 . The trading process of sensing the environment state, taking action and receiving a reinforcing signal repeats at each time step for t = 1, 2, 3, ..., T where T is the investment horizon.
Considering an investment's capital (or wealth) W 0 at time t = 0, the controller's main objective is to learn a policy that optimizes a risk-adjusted performance measure over the investment horizon T , denoted by U T (W 0 , R) where R ∈ R T is a reward vector representing received reinforcing signals over the investment horizon. In our work, for the performance measure, we are interested in utilizing the well-known risk measure CVaR. At a probability level γ, CVaR γ is the conditional mean of all losses that exceed the Value-at-Risk (VaR), where VaR specifies the lowest loss β that will not be exceeded at a confidence level γ, and denoted by VaR γ . We have the following definitions.
Definition 1: Considering a continuous random loss denoted by Z with a probability distribution function Ψ Z (z), then VaR at a probability level γ is given by: Definition 2: Considering a continuous random loss denoted by Z with a probability density function ψ Z (z), then CVaR at a probability level γ is given by: Fig. 1 illustrates a general example for ψ Z (z) with its VaR γ and CVaR γ . We emphasize that the confidence level γ also plays the role or risk-aversion parameter where the controller is more risk-averse as γ → 1, and less risk-averse as γ → 0.
With CVaR as our risk-sensitive measure, we formulate our problem next.
III. PROPOSED MODEL One can consider a general risk-sensitive problem that is to be optimized over an investment horizon of t = 1, 2, ..., T : In our case, the selection of the risk-adjusted performance is motivated by the attractive mathematical properties found in CVaR. We, therefore, are interested in minimizing the CVaR of the loss −R at a confidence level γ, i.e., CVaR γ [−W 0 R], that is altogether controlled by a parametric policy with a decision vector Θ. Thus, Problem (3) becomes: By the discussion in [23], we state the following Lemma. Lemma 1: If R(Θ) is concave, then, Problem (4) is convex.
In this work, we generally consider a single-asset trader under the assumption of negligible impact of the trader's positions on the asset's price, i.e., trading volume is significantly less than that of the overall market. Also, it is worth noting that for the special case when γ = 0, the agent is risk-neutral, and Problem (4) becomes equivalent to Our goal is to search for a decision vector Θ that solves Problem (4). Using CVaR, we have a risk-sensitive representation of the generated profits and incurred losses during the investment horizon T . In Fig. 2, we visualize the sequence of decisions and flow of information. At each time step t, the controller senses the environment through x t , generates a trading signal following the deterministic policy π t , and receives a reinforcing signal R t+1 at the immediate next time step. Hence, the reward signal at each step can be described by: Where r t+1 = p t+1 /p t − 1 is the normalized price return of an asset. For the policy π t that is followed by our agent, we model it by a single-unit neural network that is defined by: Where: represents the system with κ states at time t, and Θ = [θ 1 θ 2 · · · θ κ θ κ+1 ] ∈ R κ+1 is the decision vector where θ κ+1 is the bias parameter. From the reward (6) and the policy in (7), we can describe R t+1 explicitly as a function of Θ and the asset's return as: We can see that, under the general case of κ states, the reward in (9) is a multivariate function such that R t+1 (Θ) : R κ+1 → R. Note that the definition of the reward in (9) forms the basis of a "batch" algorithm where the decision variable is only updated after a full sweep over the data within the investment horizon T . Similar to Moody and Saffell in [5], we do online parameter updates, for consistency with real finance applications, and we have an adaptive trading system that can robustly detect financial market regime-switching. Such practical considerations will be discussed later in Section IV. The following result, whose proof can be found in the Appendix, provides sufficient conditions for the convexity of Problem (4). Theorem 1: Problem (4) is convex in Θ if, for each t, one of the following conditions hold: 1) r t+1 ≥ 0 and f is concave.
2) r t+1 ≤ 0 and f is convex. Theorem 1 elucidates that the convexity of the problem depends on the asset price returns and the convexity of the selected activation. In particular, to ensure that one of the conditions hold at each t, one must have an activation that can be either concave or convex, depending on the sign of r t+1 . The hyperbolic tangent (or sigmoid function in long-only trading) and linear activations are obvious selections that may achieve those requirements and are suitable for trading. Satisfying one of the conditions in Theorem 1 is certain with the linear activation. However, with the hyperbolic tangent, one can fulfill one of the conditions only under the case of profitable trades, i.e., π t , r t+1 ≥ 0 or π t , r t+1 ≤ 0, otherwise the problem becomes non-convex. To enforce convexity, one may consider clipping the reward function, i.e., R t+1 = 0, when the trade is unprofitable. With that, however, the controller only receives feedback about its sound decisions. Nevertheless, we will show later in Section IV that both selections are effective under our formulation. We emphasize here that, as we mentioned in Section I-A, convexity is rare in quantitative trading, and it has not been explored before under the DRL notion.
Noteworthy, so far, our formulation of the reward function considers the ideal case in which all associated trading frictions, e.g., transaction costs, are neglected. Incorporating such factors into the model requires perturbations of the reward function. However, as we will show later, such perturbations do not violate convexity.

A. Online Computation of the Optimal Policy
The market environment can be represented by macroeconomic variables [24] or technical indicators [25]. To simplify the discussion, one can consider representing it by a series of past filtered price returns, i.e., x t = [y t , y t−1 , . . . y t−n , 1] T where y t is the return of the filtered price signal at time t. We note here that the use of past returns in quantitative finance applications is commonplace; see for example [26], [27]. For the policy activation f (·), we use a bounded linear function to represent the allowable range of the trading signal, i.e., [−1, 1]. As we discussed, convexity is guaranteed with linear activation while it is not with the hyperbolic tangent and sigmoid functions, which might make the system very sensitive to initialization. Furthermore, as we demonstrate later, this allows us to consider trading frictions while preserving the convexity (see Section III-B). We use a unity investment capital W 0 = 1. Therefore, the received reward signal by the agent is purely the normalized return of the traded asset scaled by the trading signal π t , with the final wealth, or cumulative return over the investment horizon is W T = W 0 R.
As we discussed earlier, we aim to learn the optimal policy in an online manner where the decision π t is immediately evaluated when receiving R t+1 . We now show how to compute the objective in Problem (4) at each time step and how we recursively learn the optimal policy. We use the subscript i to represent our iterative computation and distinguish it from the market time step t.
Our objective described in Problem (4) mandates computing CVaR γ to solve it. Since the reward samples arrive sequentially during the trading process, we can estimate CVaR γ at each time step using all captured rewards up to t + 1, i.e., R 1 , R 2 , ..., R t+1 and we denote it by CVaR γ,t+1 . Our estimation follows the Monte Carlo approach proposed by Hong and Liu in [28], which proposed the following convergent Monte Carlo estimation of CVaR γ,t+1 [−W 0 R(Θ t )], denoted byĉ γ,i (We drop the constant W 0 for brevity): Where [x] + = max(x, 0) andv γ,i is the estimation of VaR γ,t+1 [−W 0 R(Θ t )], which is given by: Where −R k:(t+1) is the k th order statistic from the (t + 1) samples. Once the estimation in (10) is computed, we can directly apply stochastic gradient descent (SGD) to update the policy's parameters Θ: Where α ∈ (0, 1) is the learning rate. We need to point out that optimization with SGD has an attractive privilege in our problem. Since SGD provides "noisy" gradient information, it enhances the exploratory behavior of the controller. That behavior can be altered by tuning the learning rate. However, the online update of Θ governed by (10), (11), and (12) has two challenges. The first challenge is vanishing gradient information in the case of −R t+1 <v γ,i whereĉ γ,i is no longer a function of Θ i−1 . That problem becomes even worse as γ → 1 since the number of samples that fall belowv γ,i grows with higher γ. To overcome the first challenge, we add the second norm of Θ as a regularization term to Problem (4); thus the problem becomes: Where λ ∈ [0, 1] is the regularization constant. The regularization term guarantees the availability of gradient information in all time steps. Moreover, as stated by Bishop in [29], the regularization term enhances the generalization performance of learning systems with objectives that do not involve error minimization. The second challenge we have is a biased estimatê c γ,i as t increases. Having a biased estimate is problematic in our particular application since we expect the distribution of the reward to vary over time due to the non-stationary behavior of the financial market. To circumvent the second issue, we propose an adaptive estimation for CVaR γ,t+1 . In that sense, the estimate at each step is derived using only a predetermined N + 2 past samples of the reward. Thus, the estimates in (10) and (11) become: With that approach, we ensure the estimates are adaptive and reflect any potential market-regime switching. In addition, the proposed approach enhances the computational efficiency of deriving the estimates since with the original formulation the computational cost increases with t. We now can update Θ recursively as follows: The estimates in (14), (15) and the update rule in (16) form the basis of our online learning algorithm that optimizes Problem (4) under frictionless setup. Due to the convexity of our problem, our experiments demonstrate that the learning algorithm can adaptively discover a lucrative strategy through a single run over the data. Besides that, the proposed model is significantly more efficient than other methods in computing the solution. To the best of our knowledge, this is the first work that proposes a trading system under a machine learning paradigm that learns on the go with well-performance.

B. Including Market Frictions
In the finance literature, trading frictions, such as transaction costs, can be incorporated into the problem in several ways. For example, Davis and Norman in [2] modeled the transaction Algorithm 1 CVaR-Sensitive Online Optimal Policy Select: W 0 , γ, α, λ, N, n, I Initialize: Θ 0 , ϑ 0 , η 0 and t = 0, i = 1 for t < T do Environment Sense the environment: x t ← h t (p t , ..., p t−n ) Take action: charges as a linear function of the transacted assets amount in a portfolio selection problem. Morton and Pliska in [30], on the other hand, implemented a fixed cost that depends on the portfolio value. Here we follow the approach in [2] since it is consistent with the pioneering DRL trading systems [5], [16]. To this end, the reward function in (6) can be altered as follows: Where δ is a fixed percentage that counts for half of the roundtrip cost (only opening or closing a position), and the argument inside the absolute value represents the traded amount of the asset at time t. With linear activation function, the argument inside the absolute value is linear in Θ t . Thus, with the use of an auxiliary decision variable ϑ t , we can reformulate the absolute value and add linear constraints to Problem (13). Hence, the reward function becomes: While Problem (13) is now reformulated as: Since Problem (19) is convex, we unfold it using the wellknown log barrier method [31]. We thus can have an augmented objective described by: Where η > 0 is a parameter that determines the accuracy of the approximation to the original Problem (19), and it should grow with time during computing the solution, i.e., 1/η → 0 as i → ∞. We now can compute Θ update recursively as follows: We similarly update the auxiliary variable ϑ: The estimates in (14) and (15) considering the reward in (18) with the update rules in (21) and (22) form the basis of our online algorithm under frictional market, which is depicted in Algorithm 1.

IV. EXPERIMENTAL RESULTS
We assess our proposed model on actual financial market data. We, in particular, use one of the largest US trust funds, the SPDR (ticker: SPY) [32] price signal from 06/08/2018 to 20/08/2021 with a trading interval of ∆t = 15 minutes. That forms an investment horizon of T = 20000 steps. As indicated in the SPY price signal shown in Fig. 3, the price experienced severe fluctuation and had several market regime-switching during that period. Therefore, we believe that the selected out-of-sample data is reasonable for testing the robustness of our proposed trading system. Our numerical experiments were conducted using a standard computer equipped with a 3.2-GHz 8-core processor and 16-GB RAM, which makes our approach attractive and easily implementable in practice.
We show the results of our trading system over the outof-sample data under a different selection of the risk-aversion parameter γ. We also assess the trading system under conservative transaction costs, i.e., δ = 0.05, 0.1 and 0.15%  First, in Fig. 4, we illustrate the algorithm's effectiveness in risk management and validate that it could uncover lucrative trading strategies under a frictionless market. Over the investment horizon, Fig. 4(a) shows the overall returns, Fig. 4(b) illustrates the variance of negative returns, and Fig.  4(c) demonstrates the MDD. Those figures show the results at different risk preferences γ. Note that we report the variance of negative returns rather than the overall since CVaR γ is concerned about large incurred losses that fall within the (1−γ)-percentile of the reward distribution. Consequently, we can see in Fig. 4(b) a consistent pattern of variance reduction as γ → 1. Further, we see in Fig. 4(a) that the highest total return is achieved when the objective is the reward expectation (i.e., CVaR γ=0 ). However, this high return comes at the cost of large MDD, around 10%. Although we see the lowest return at γ = 0.99, it has the lowest MDD at about 0.7%. Moreover, for γ ≥ 0.9, both the variance and returns are almost steady at around 0.015 and 14%, respectively. That can be attributed to the number of samples used to estimate CVaR γ where we used 50 samples for γ = 0.9, 0.95 and 100 samples for γ = 0.99. Indeed, the result of frictionless trading proves the algorithm's subtlety in extracting trading schemes that strictly comply with the investor's risk preference.
To gain deeper insights into proposed model's practicality, we exhibit the cumulative returns over the investment horizon under different transaction costs in Fig. 5 where Fig. 5(a) shows the results of expectation as an objective, and Fig. 5(b) shows the case of risk-adjusted returns with CVaR γ=0. 9 . Under the expectation case illustrated in Fig. 5(a), we observe that the trading system was learning in the first 1000 steps where no profits were made before that point. Note that with higher round-trip (2δ) trading charges of 0.3%, the system even took a longer time than the case of 0.1 and 0.2% to learn and did not discover a profitable trading scheme before the 2000 th step. Most importantly, we can notice the robustness of the controller within its achieved profits through detecting the primary market-regime switching occurred at the significant price pullback (around step 10,000 in Fig. 3) and price rise (step 10,500 in Fig. 3). Further, our trading system outperforms the baseline strategy of buying and holding (B&H) the asset over the investment horizon under all considered trading chargers. For the case of risk-adjusted returns with γ = 0.9 shown in Fig. 5(b), the controller seems conservative in trading unless it uncovers a clear pattern within the price signal, and this justifies why its total return is lower than the case of expectation. In addition, with γ = 0.9, the controller tries to lower its trading positions to avoid significant losses, and this indeed comes at the cost of lower total returns over the investment horizon. To this end, we see that the proposed algorithm proves its practicality where it shows that it can have lucrative strategies even in the case of most conservative trading costs. At the same time, it avoids risky decisions at higher values of the risk-aversion parameter.
Finally, in Fig. 5(c), we compare the performance of a policy with linear activation where the problem is convex against the case of non-convex formulation with the hyperbolic tangent as an activation. Under that case, we consider optimizing CVaR γ=0.9 at a round-trip transaction cost of 0.2%, with δ = 0.1. We can see the privilege of convex formulation, where the total return of the linear policy is about fourfold of the hyperbolic tangent.

V. GENERALIZATIONS
Our proposed convex Problem (4) can easily be generalized to consider risk-constrained and assets allocation problems.
Here we discuss the theoretical setup of those generalizations, but we leave validating them through numerical experiments for future work. In some instances, a trader may seek to maximize the expectation of the returns amid avoidance of potentially large losses. In that sense, we can consider the following alternative to Problem (4): Where µ β represents the investor's tolerable expected loss that may exceed VaR γ . The conditions for the convexity of Problem (23) are the same as those in Problem (4) and are given by Theorem 1. Noteworthy, recent developments in the literature of risk-sensitive constrained optimization makes solving Problem (23) achievable even in more general setups, see for example [33].
The second, and more important generalization, is extending the formulation to an asset allocation problem. In that setup, we consider a long-only policy where short selling is not allowed, i.e., π t ∈ [0, 1]. Also, the controller follows a policy that can re-balance its investment capital at each time step among risky (e.g., stocks) or risk-less (e.g., Treasury yields) assets. We then can reformulate the reward function as follows: Where r t+1 and r f t+1 represent the risky and risk-less asset returns, respectively. We then optimize Problem (4) based on the reward function in (24). Similar to Theorem 1, we have the following result, whose proof can be found in the Appendix.
Theorem 2: With the reward function in (24) in a long-only setup, Problem (4) is convex in Θ t if, for each t, one of the following conditions is true: 1) r t+1 − r f t+1 ≥ 0 and f is concave. 2) r t+1 − r f t+1 ≤ 0 and f is convex.

VI. CONCLUSION
In this manuscript, we demonstrated the effectiveness of convex trading systems with CVaR as a risk-adjusted performance measure following the concept of DRL. Due to convexity, the proposed controller illustrated its capability in learning and updating its policy in a pure online manner. In that sense, the proposed approach showed its robustness in detecting primary market-regime switching while generating profits under a realistic frictional market for three years. Further, the numerical experiment revealed that the algorithm effectively manages risk based on the investor's risk preference γ. The trading system could outperform the market under the risk-neutral case, i.e., γ = 0, while it could achieve a minimal MDD with the most risk-averse trader of γ = 0.99. Lastly, we theoretically showed that our proposed convex formulation could be generalized to consider risk-constrained and asset allocation problems. Still, we left validating them through numerical experiments for future work.