<?xml version="1.0" encoding="UTF-8"?>
<article xmlns:xlink="http://www.w3.org/1999/xlink">
<front><article-meta>
<title-group><article-title>Dynamic Portfolio Optimization in the Tehran Stock Exchange Using Machine Learning and Deep Earning</article-title></title-group>
<contrib-group>
<contrib contrib-type="author"><name><surname>Pira</surname><given-names>Hossein</given-names></name><xref ref-type="aff" rid="aff1"/></contrib>
<aff id="aff1">Department of Computer Engineering, Ayandegan University, Tonkabon, Iran.</aff>
</contrib-group>
<abstract><p>Classical optimization models are applicable for portfolio optimization when capital market constraints and portfolio construction criteria are limited. However, given the existing complexities in capital markets, intricate relationships, and nonlinear issues, classical models exhibit significant weaknesses and limitations. To address and solve such problems, computers and Machine Learning (ML)-based models have emerged to assist human decision-makers. Recently, techniques based on hybrid ML models have been developed, demonstrating robust capabilities for handling nonlinear problems. This paper proposes a hybrid ML model for portfolio optimization based on specific historical data in the capital market. For this purpose, daily returns from 20 high-liquidity companies listed on the Tehran Stock Exchange (TSE) over a specific timeframe were utilized. The proposed framework integrates Random Forest (RF) for feature importance analysis, Extreme Gradient Boosting (XGBoost) for return prediction, and a Deep Reinforcement Learning (DRL) agent using Proximal Policy Optimization (PPO) for dynamic asset allocation. Portfolio performance is evaluated across four distinct risk metrics: Variance, Mean Absolute Deviation (MAD), Semi-Variance, and Conditional Value at Risk (CVaR). Based on evaluations of portfolio returns, risk indices, and other key indicators, the results of this research indicate that the performance of the proposed ML model is optimal and desirable.</p></abstract>
<kwd-group kwd-group-type="author"><kwd>Portfolio optimization</kwd><kwd>Machine learning</kwd><kwd>Deep reinforcement learning</kwd><kwd>Tehran stock exchange</kwd><kwd>Random forest</kwd><kwd>XGBoost</kwd><kwd>Risk management</kwd></kwd-group>
</article-meta></front>
<body>
<sec id="sec-1"><label>1</label><title>Introduction</title>
<p>The stock market, as one of the fundamental pillars of the global economic system, plays a critical role in allocating financial resources to enterprises and channeling liquidity to productive sectors. In recent years, the Tehran Stock Exchange (TSE) has emerged as one of the most significant investment platforms; however, operating in this market entails unique challenges <xref ref-type="bibr" rid="ref-1">[1]</xref>. Numerous structural characteristics, such as price limits (trading bands), &quot;base volume&quot; requirements, widespread information asymmetry, and investors&apos; emotional behavior, coupled with the market&apos;s acute, rapid sensitivity to political news and macroeconomic variables, have created a volatile, complex environment. In such a landscape, the precise analysis and prediction of stock returns have become a primary concern for market participants and financial researchers.</p>
<p>Historically, Modern Portfolio Theory (MPT) and Harry Markowitz&apos;s Mean-Variance model have been the most influential frameworks for portfolio management and asset allocation <xref ref-type="bibr" rid="ref-2">[2]</xref>. While these models offer a systematic approach to balancing risk and return, they rely on rigid assumptions that often conflict with the realities of the TSE. By assuming normal returns and linear relationships among assets in a market characterized by skewness, non-stationarity, and chaotic behavior, these classical methods can lead to inaccurate risk assessments and inefficient portfolios <xref ref-type="bibr" rid="ref-3">[3]</xref>.</p>
<p>In recent years, significant advancements in Artificial Intelligence (AI) and Machine Learning (ML) have established a new paradigm in financial markets and portfolio optimization. Unlike traditional models, ML algorithms such as Random Forest (RF), Extreme Gradient Boosting (XGBoost), and Deep Neural Networks (DNN) offer high flexibility in discovering hidden patterns and nonlinear relationships <xref ref-type="bibr" rid="ref-4">[4]</xref>. These algorithms can process vast amounts of time-series and qualitative data to predict severe market fluctuations with greater accuracy <xref ref-type="bibr" rid="ref-5">[5]</xref>.</p>
<p>This research adopts an innovative approach by coupling the predictive power of ML algorithms with the capabilities of Deep Reinforcement Learning (DRL) to perform dynamic optimization. The XGBoost algorithm is used for stock selection and return prediction, while the RF algorithm captures nonlinear features for price prediction. Subsequently, a DRL agent using Proximal Policy Optimization (PPO) dynamically allocates portfolio weights based on predicted returns and risk considerations <xref ref-type="bibr" rid="ref-6">[6]</xref>.</p>
</sec>
<sec id="sec-2"><label>2</label><title>Related Works</title>
<sec id="sec-3"><label>2.1</label><title>Portfolio Optimization Theory</title>
<p>The concept of portfolio optimization was formalized by Harry Markowitz <xref ref-type="bibr" rid="ref-7">[7]</xref>, introducing the Mean-Variance framework that considers risk and return simultaneously <xref ref-type="bibr" rid="ref-2">[2]</xref>. A central theme is selecting an optimal investment portfolio relative to its risk-return profile. Markowitz demonstrated that portfolio risk depends not only on the variance of individual assets but also on the correlation between their returns. Therefore, two high-risk stocks, when combined, can create a lower-risk portfolio provided their correlation is low. The primary objective is to find specific asset weights that minimize portfolio variance while maximizing expected return.</p>
</sec>
<sec id="sec-4"><label>2.2</label><title>Machine Learning in Finance</title>
<p>RF, introduced by Breiman <xref ref-type="bibr" rid="ref-8">[8]</xref>, is recognized as one of the most robust ML algorithms for both classification and regression tasks. By using multiple decision trees and ensemble learning techniques, this algorithm can model complex, nonlinear patterns with high precision. Its stability, resistance to noise, and ability to handle outliers make it an exceptional performer in analyzing complex financial data in volatile markets.</p>
<p>XGBoost, introduced by Chen and Guestrin <xref ref-type="bibr" rid="ref-9">[9]</xref>, has attracted significant attention in the financial sector for its ability to process and predict data within an optimal timeframe. Its sequential gradient boosting hierarchy and optimized decision trees capture complex, nonlinear interactions and cross-correlations among financial variables more effectively than classical models. For stock return forecasting, volatility prediction, trend identification, and risk analysis, XGBoost has demonstrated superior performance.</p>
</sec>
<sec id="sec-5"><label>2.3</label><title>Deep Reinforcement Learning for Portfolio Management</title>
<p>DRL has emerged as a powerful framework for sequential decision-making in financial markets <xref ref-type="bibr" rid="ref-6">[6]</xref>. Unlike supervised learning approaches that predict returns independently, DRL agents learn optimal policies by interacting with the market environment, receiving rewards based on portfolio performance. PPO provides stable policy updates with guaranteed monotonic improvement, making it particularly suitable for the non-stationary dynamics of financial markets <xref ref-type="bibr" rid="ref-10">[10]</xref>.</p>
</sec>
</sec>
<sec id="sec-6"><label>3</label><title>Research Methodology</title>
<sec id="sec-7"><label>3.1</label><title>Data Collection and Stock Selection</title>
<p>The statistical database for this study comprises companies listed on the TSE between the years 2013 and 2022 (1392 to 1401 SH). Following data collection and preliminary calculations, 20 high-liquidity companies were selected based on liquidity, trading volume, transaction volume, and market impact. Daily adjusted returns were calculated for all selected companies.</p>
</sec>
<sec id="sec-8"><label>3.2</label><title>Feature Engineering</title>
<p>The feature engineering process involves extracting relevant financial indicators from raw price and volume data:</p>
<p>I. Daily returns and log returns II. Moving averages (5-day, 10-day, 20-day, 50-day) III. Relative Strength Index (RSI) IV. Moving Average Convergence Divergence (MACD) V. Bollinger Bands (upper and lower) VI. Volume-Weighted Average Price (VWAP) VII. Historical volatility measures</p>
</sec>
<sec id="sec-9"><label>3.3</label><title>Stock Selection Using Extreme Gradient Boosting</title>
<p>The stock selection process is conducted in several stages. First, the XGBoost model is trained to predict future returns of all stocks within the research sample. Subsequently, the predicted return for each stock is calculated. The XGBoost model&apos;s output ranks stocks, and only those in the upper percentiles of the predicted return distribution are considered selected. Furthermore, XGBoost allows the extraction of Feature Importance, which identifies which technical indicators played the most significant role in predicting stock returns.</p>
<p>The XGBoost objective function consists of two primary components: the loss function (prediction error) and the regularization term controlling model complexity:</p>
<p>ℒ(φ) = ∑i ∗ l(ŷi, yi) + ∑kΩ( fk), (1)</p>
<p>where l is the loss function measuring the difference between the predicted value ŷi and the actual value yi, and Ω is the regularization term preventing overfitting by penalizing model complexity.</p>
</sec>
<sec id="sec-10"><label>3.4</label><title>Return Prediction Using Random Forest</title>
<p>The RF algorithm complements XGBoost by capturing nonlinear features for price prediction. Each decision tree is constructed by classifying bootstrap samples of the input data. The ensemble output is determined by averaging each tree&apos;s votes, providing robust predictions that are resistant to noise and outliers.</p>
</sec>
<sec id="sec-11"><label>3.5</label><title>Deep Reinforcement Learning for Portfolio Optimization</title>
<p>The optimization algorithm is based on DRL using PPO. The DRL framework is defined as follows:</p>
<p>I. State space: the state at time t includes predicted returns from ML models, current portfolio weights, historical volatility measures, and market indicators.</p>
<p>II. Action space: the action is a vector of portfolio weights w = (w1, w2, … , wN) where ∑wi = 1 and wi ≥ 0 for all i.</p>
<p>III. Reward function: the reward is defined as the risk-adjusted portfolio return, incorporating the selected risk metric (Variance, Mean Absolute Deviation (MAD), Semi-Variance, or Conditional Value at Risk (CVaR)). The PPO agent learns to dynamically adjust portfolio weights by continuously interacting with historical market data, optimizing the trade-off between return maximization and risk minimization. The PPO objective function is given by:</p>
<p>LCLIP(θ) = t[ min( rt(θ)Ât, clip( rt(θ), 1 − ε, 1 + ε )Ât)], (2)</p>
<p>where rt(θ) is the probability ratio between the new and old policy, Ât is the estimated advantage function, and ε is the clipping hyperparameter.</p>
</sec>
<sec id="sec-12"><label>3.6</label><title>Risk Measurement Metrics</title>
<p>Four distinct risk metrics are employed for comprehensive risk assessment:</p>
<p>Variance: The variance of returns is computed as</p>
<p>σi2 = ∑( ri − r̄ ) ∗ (2/ N), (3)</p>
<p>representing the degree of dispersion of actual returns around the expected return.</p>
<p>MAD:</p>
<p>MAD = ∑| ri− r̄ | / N , (4)</p>
<p>which is less sensitive to outliers than variance, allowing simpler calculations in large-scale optimization models.</p>
<p>Semi-Variance:</p>
<p>SV = { min( ri − r̄, 0 ) ∗ 2}, (5)</p>
<p>focusing only on downside risk by considering only returns that fall below the mean.</p>
<p>CVaR: addresses the limitations of standard VaR by accounting for the severity of losses in the tail of the distribution, defined as the expected loss given that the loss exceeds the VaR threshold:</p>
<p>CvaRα = [ −R | R ≤ −VaRα]. (6)</p>
<table-wrap id="tab1"><label>Table 1</label><caption><p>Descriptive statistics of selected companies.</p></caption><graphic content-type="pdf-region" xlink:href="pdf-region:3:66,85.1,537.1,177.3"/><graphic content-type="pdf-region" xlink:href="pdf-region:4:66,521.6,537.1,759.1"/><p content-type="note">This table is shown in the PDF version of the article.</p></table-wrap>
</sec>
</sec>
<sec id="sec-13"><label>4</label><title>Results and Analysis</title>
<sec id="sec-14"><label>4.1</label><title>Model Training and Validation</title>
<p>The dataset was divided into training (2013–2019) and testing (2020–2022) periods. Both XGBoost and RF models were trained on the training set with cross-validation to prevent overfitting. The DRL agent was trained using the PPO algorithm with the following hyperparameters: learning rate = 0.0003, batch size = 64, epochs = 500, discount factor γ = 0.99, clip ratio ε = 0.2.</p>
</sec>
<sec id="sec-15"><label>4.2</label><title>Prediction Performance</title>
<p>The combined ML pipeline (XGBoost + RF) achieved strong prediction accuracy. The algorithm&apos;s error rate was close to zero, indicating accurate learning and prediction. Feature importance analysis revealed that volume-related features, momentum indicators, and historical volatility were the most discriminative predictors.</p>
</sec>
<sec id="sec-16"><label>4.3</label><title>Portfolio Performance</title>
<p>The portfolio optimization results demonstrate that the expected rate of return across all four risk models is 0.001, with risk indices of 0.01 for Variance, Semi-Variance, and MAD, and 0.03 for CVaR. The CVaR model shows a higher risk index because it accounts for tail risks more conservatively, providing a more comprehensive view of extreme loss scenarios.</p>
<table-wrap id="tab2"><label>Table 2</label><caption><p>Portfolio performance across risk metrics.</p></caption><graphic content-type="pdf-region" xlink:href="pdf-region:4:66,201.9,537.1,270.3"/><p content-type="note">This table is shown in the PDF version of the article.</p></table-wrap>
</sec>
<sec id="sec-17"><label>4.4</label><title>Comparative Analysis</title>
<p>The proposed hybrid model outperforms all benchmark strategies across every metric. The combination of ML-based stock selection with DRL-based dynamic allocation achieves the highest annual return (22.3%), the lowest volatility (13.2%), and the maximum drawdown (−11.8%). The Sharpe ratio of 1.69 indicates a significantly superior risk-adjusted return profile compared to the traditional Mean-Variance approach (0.94) and individual ML models (1.16 and 1.24 for RF and XGBoost, respectively).</p>
<table-wrap id="tab3"><label>Table 3</label><caption><p>Comparison with benchmark strategies.</p></caption><graphic content-type="pdf-region" xlink:href="pdf-region:5:66,645.2,537.1,756.3"/><p content-type="note">This table is shown in the PDF version of the article.</p></table-wrap>
</sec>
</sec>
<sec id="sec-18"><label>5</label><title>Conclusion</title>
<p>In this research, portfolio optimization was studied using the RF and XGBoost algorithms combined with DRL. According to the results of evaluating the portfolio return, risk index, and other desired indicators across all criteria, the results obtained in this model were satisfactory. The model demonstrates an acceptable ability to construct an optimal stock portfolio.</p>
<p>By combining these models and algorithms with linear features, the portfolio can be optimized and selected based on nonlinear features such as political news and macroeconomic variables. However, due to the abundance of features governing the market and factors affecting companies&apos; portfolio decisions, decision-making in this case is highly complex, and the optimization process is completely unstructured.</p>
<p>Although classical models have met investors&apos; information needs to some extent, they are useful only when the factors affecting the capital market are limited. In reality, many factors affecting the capital market are nonlinear and complex, requiring advanced computational approaches. Using ML models, data can be collected in very short time periods, and hundreds of stocks can be monitored in real time, providing the best investment insights.</p>
<p>The key contributions of this research are: 1) integration of XGBoost and RF for robust return prediction in an emerging market context, 2) application of PPO-based DRL for dynamic portfolio rebalancing, 3) comprehensive risk evaluation across four distinct metrics, and 4) demonstration of superior performance compared to traditional optimization approaches in the TSE environment.</p>
<p>Future work should focus on: incorporating transaction costs and market impact models; extending the framework to multi-market portfolio optimization; exploring alternative DRL architectures such as Soft Actor-Critic (SAC) and TD3; and investigating the integration of sentiment analysis from news and social media as additional features.</p>
</sec>
<sec id="sec-19"><title>Authors&apos; Contributions</title>
<p>The author solely conducted the research and prepared the manuscript and has approved its final version.</p>
</sec>
<sec id="sec-20"><title>Data Availability</title>
<p>The data are available from the corresponding author upon reasonable request.</p>
</sec>
<sec id="sec-21"><title>Funding</title>
<p>This work was carried out without financial support from any public, commercial, or non-profit organizations.</p>
</sec>
<sec id="sec-22"><title>Conflict of Interest</title>
<p>There are no competing interests to declare.</p>
</sec>
<sec id="sec-23"><title>Consent for Publication</title>
<p>The author confirms consent for the publication of this work</p>
</sec>
<sec id="sec-24"><title>Ethics Approval and Consent to Participate</title>
<p>This article does not include experiments involving humans or animals.</p>
</sec>
</body>
<back><ref-list><title>References</title>
<ref id="ref-1"><label>1</label><mixed-citation>Zare, H. (2021). Political uncertainty and stock market fluctuations in Iran: With consideration of international political changes. Journal of development and capital, 6(1), 123–145. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.22103/jdc.2021.15440.1091">https://doi.org/10.22103/jdc.2021.15440.1091</ext-link></mixed-citation></ref>
<ref id="ref-2"><label>2</label><mixed-citation>Fabozzi, F. J., Markowitz, H. M., &amp; Gupta, F. (2008). Portfolio selection. In Handbook of finance (pp. 3–13). Wiley. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.1002/9780470404324.HOF002001">https://doi.org/10.1002/9780470404324.HOF002001</ext-link></mixed-citation></ref>
<ref id="ref-3"><label>3</label><mixed-citation>Fahimi, A., &amp; Shahbandarzadeh, H. (2021). Developing the Markowitz portfolio optimization model concerning investor non-financial considerations and supporting domestic products. Industrial management journal, 13(1), 53-79. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.22059/imj.2021.316204.1007811">https://doi.org/10.22059/imj.2021.316204.1007811</ext-link></mixed-citation></ref>
<ref id="ref-4"><label>4</label><mixed-citation>Ghasempour, A., Khodamipour, A., Zainali, H., &amp; Taebi Naghandari, A. (2025). Designing an optimal model for predicting stock liquidity using the random forest. Journal of accounting knowledge, 16(2), 1-26. (In Persian). <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.22103/jak.2025.24973.4156">https://doi.org/10.22103/jak.2025.24973.4156</ext-link></mixed-citation></ref>
<ref id="ref-5"><label>5</label><mixed-citation>Ghods, M., Amiry, M., Peymani Forooshani, M., &amp; Dehghan Dehnavi, M. (2025). Prediction of Tehran stock exchange total index using natural gradient boosting and SHAP values. Financial management perspective, 15(2), 34–53. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.48308/jfmp.2025.239954.1498">https://doi.org/10.48308/jfmp.2025.239954.1498</ext-link></mixed-citation></ref>
<ref id="ref-6"><label>6</label><mixed-citation>Jiang, Z., Xu, D., &amp; Liang, J. (2017). A deep reinforcement learning framework for the financial portfolio management problem. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.48550/arXiv.1706.10059">https://doi.org/10.48550/arXiv.1706.10059</ext-link></mixed-citation></ref>
<ref id="ref-7"><label>7</label><mixed-citation>Markowitz, H. (1952). Modern portfolio theory. Journal of finance, 7(11), 77–91. <ext-link ext-link-type="uri" xlink:href="https://www.raymondjames.com/-/media/rj/advisor-sites/sites/s/t/sturgeonellett/files/february-2023.pdf">https://www.raymondjames.com/-/media/rj/advisor-sites/sites/s/t/sturgeonellett/files/february-2023.pdf</ext-link></mixed-citation></ref>
<ref id="ref-8"><label>8</label><mixed-citation>Breiman, L. (2001). Random forests. Machine learning, 45(1), 5–32. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.1023/A:1010933404324">https://doi.org/10.1023/A:1010933404324</ext-link></mixed-citation></ref>
<ref id="ref-9"><label>9</label><mixed-citation>Chen, T., &amp; Guestrin, C. (2016). Xgboost: A scalable tree boosting system. Proceedings of the 22nd acm sigkdd international conference on knowledge discovery and data mining (pp. 785-794). Association for Computing Machinery (ACM). <ext-link ext-link-type="uri" xlink:href="https://dl.acm.org/doi/abs/10.1145/2939672.2939785">https://dl.acm.org/doi/abs/10.1145/2939672.2939785</ext-link></mixed-citation></ref>
<ref id="ref-10"><label>10</label><mixed-citation>Schulman, J., Wolski, F., Dhariwal, P., Radford, A., &amp; Klimov, O. (2017). Proximal policy optimization algorithms. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.48550/arXiv.1707.06347">https://doi.org/10.48550/arXiv.1707.06347</ext-link></mixed-citation></ref>
</ref-list></back>
</article>