<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Michal Dufek on Medium]]></title>
        <description><![CDATA[Stories by Michal Dufek on Medium]]></description>
        <link>https://medium.com/@michaldufek?source=rss-a876d2002eb2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*L_NuPtxKXquTG-6m_ldVRQ.jpeg</url>
            <title>Stories by Michal Dufek on Medium</title>
            <link>https://medium.com/@michaldufek?source=rss-a876d2002eb2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:42:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michaldufek/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ML-Powered Factor Models]]></title>
            <link>https://medium.com/@michaldufek/ml-powered-factor-models-1b945c4cf2de?source=rss-a876d2002eb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b945c4cf2de</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[Michal Dufek]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 14:45:07 GMT</pubDate>
            <atom:updated>2023-11-24T14:46:06.992Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>The integration of machine learning into financial modeling represents a noteworthy evolution in the field of asset pricing. While multi-factor models have long been a cornerstone in understanding market dynamics, the addition of machine learning offers new dimensions and possibilities for analysis and strategy development.</p><p>This post explores an approach that combines traditional multi-factor models with advanced machine learning algorithms, including Ridge, Lasso, ElasticNet, and XGBoost. This combination aims to enhance predictive accuracy and offer more nuanced insights into asset pricing and portfolio construction. While some of these techniques, like cross-sectional scaling, are established in the field, their application within a machine-learning framework presents a unique angle in addressing market complexities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KzLIfrPPsldtvJXhc5n_jg.png" /><figcaption>Long-short equity porftolio manager has to make decisions which stocks buy/sell, how tune market exposure and leverage</figcaption></figure><p>Using a suite of technologies such as Python, pandas, and scikit-learn, our model emphasizes rigorous data processing, model training, evaluation, and backtesting. This approach is not about reinventing the wheel, but rather about refining and optimizing existing models to better suit the dynamic nature of today’s financial markets.</p><p>In the upcoming sections, we will walk through the specifics of our methodology, the rationale behind our choice of algorithms, and the practical implementation details. Our goal is to provide insights into how machine learning can complement traditional financial models, rather than to claim a complete overhaul of existing systems.</p><h3>Background</h3><h4>Traditional Multi-Factor Models in Asset Pricing</h4><p>Historically rooted in the Capital Asset Pricing Model (CAPM), these models have been developed to include multiple factors like size, value, and momentum, each representing different aspects of an asset’s characteristics and market behavior.</p><p>The evolution from CAPM to more sophisticated multi-factor models reflects the financial industry’s continuous quest to better understand and predict market movements. These models aim to capture additional aspects of asset returns that CAPM, with its focus solely on market risk, does not address.</p><h4>Limitations of Traditional Models</h4><p>While effective in certain scenarios, traditional factor models have their limitations. One significant challenge is their performance across different market conditions. These models often rely on historical data and fixed factor sets, which may not adapt well to rapid market changes or unprecedented scenarios.</p><p>In today’s data-rich financial environment, traditional models can be overwhelmed by the sheer volume and complexity of information. Managing and extracting meaningful insights from these large datasets requires more advanced analytical techniques than those provided by conventional models.</p><h4>Behind the Horizons</h4><p>The integration of machine learning in factor modeling could improve predictive accuracy. Machine learning algorithms excel in identifying complex patterns in data, offering a more nuanced understanding of market dynamics.</p><p>Another compelling aspect of machine learning is its adaptability. Algorithms can be trained to adjust to new data, making them particularly suited for the fluid nature of financial markets. This flexibility allows models to stay relevant and effective even as market conditions shift.</p><p>Acknowledging these limitations and the potential of machine learning, our approach seeks to blend traditional factor analysis with advanced machine learning techniques. This combination promises not only to retain the strengths of conventional models but also to extend their capabilities, making them more suited for the complexities of modern financial markets.</p><p><strong>Data Preparation</strong></p><p>Our model is powered by a dataset encompassing 1269 features, derived from a wide array of sources. These include price data, fundamental data from financial statements, various technical indicators, and a range of statistical measures. This comprehensive feature set allows for a detailed and multifaceted analysis of assets.</p><p>Analysis uses monthly data for selected group of stocks including: ‘ADBE’, ‘ADSK’, ‘ANSS’, ‘DT’, ‘EPAM’, ‘HUBS’, ‘ISRG’, ‘MBLY’, ‘MSFT’, ‘NVDA’, ‘PANW’, ‘PATH’, ‘PLTR’, ‘SNPS’, ‘TRI’, ‘TWLO’, ‘WDAY’, and ‘ZBRA’.</p><p>The diversity of features ensures that our model captures various aspects of market behavior and company performance. From price momentum to balance sheet health, each feature contributes a unique perspective, enabling a holistic view of the financial markets.</p><p><strong>Cross-Sectional Normalization</strong></p><p>To address potential biases and scale discrepancies across features, we employ cross-sectional normalization using standard scaling. This process involves adjusting data on a per-feature basis, ensuring that each variable contributes equally to the model without being dominated by those with larger magnitudes.</p><p>Such normalization is crucial in a dataset with diverse feature types. It not only standardizes the range of values but also enhances the model’s ability to discern subtle patterns and relationships among different assets and indicators.</p><p><strong>Preparing Data for Machine Learning</strong></p><p>Given the complexity of financial data, careful cleaning and preprocessing are essential. This step involves handling missing values, correcting anomalies, and ensuring data consistency, setting a solid foundation for accurate model training and analysis.</p><p>To evaluate our model effectively, we divide our dataset into training and testing sets where the training period is taken from 2009 to 2019. The training set is used to build and tune the model, while the testing set (2020–2023) provides an unbiased evaluation of its performance and stability.</p><h3><strong>Bridging Theory with Practice</strong></h3><p>As usual let’s start with importing a suite of essential libraries.</p><pre>import pandas as pd<br>import numpy as np<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.linear_model import RidgeCV, LassoCV, ElasticNetCV<br>import xgboost as xgb<br>from sklearn.metrics import mean_squared_error, r2_score</pre><p>The first step is always about preparing the data. For this purpose we start with reading our dataset and setting the groundwork for analysis.</p><pre># Assuming the data is stored in &#39;data/features.csv&#39;<br>df = pd.read_csv(&#39;data/features.csv&#39;)</pre><p>To ensure that all features contributes equally to the analysis we normalize data cross-sectionaly.</p><pre>def scale(pdf):<br>    excluded_cols = [&#39;Date&#39;, &#39;Symbol&#39;]<br>    scaled_cols = [col for col in pdf.columns if col not in excluded_cols]<br>    if pdf[&#39;Symbol&#39;].nunique() &gt; 1:<br>        scaler = StandardScaler()<br>        to_scaling = pdf[scaled_cols]<br>        scaled = pd.DataFrame(scaler.fit_transform(to_scaling), columns=scaled_cols)<br>        out = pd.concat([pdf[excluded_cols].reset_index(drop=True), scaled], axis=&#39;columns&#39;)<br>        return out.reindex(pdf.columns, axis=&#39;columns&#39;)<br>    return pdf</pre><p>Now we are ready to start training our machine learning model. The following solution provide us an option which algorithm is used. The set consists of penalized linear model (Lasso, Ridge, ElasticNet) and XGBoost. Each algorithm has its own merits, and the choice depends on specific requirements of the analysis.</p><pre>def train_model(X_train, y_train, algorithm):<br>    if algorithm == &quot;ridge&quot;:<br>        model = RidgeCV(alphas=[0.1, 1.0, 100.0], cv=10)<br>    elif algorithm == &quot;lasso&quot;:<br>        model = LassoCV(alphas=np.logspace(-6, 6, 13), cv=5, random_state=42)<br>    elif algorithm == &quot;elasticnet&quot;:<br>        model = ElasticNetCV(alphas=np.logspace(-4, 4, 10), l1_ratio=[.1, .5, .7, .9, .95, .99, 1], cv=5, random_state=42)<br>    elif algorithm == &quot;xgboost&quot;:<br>        model = xgb.XGBRegressor(objective=&#39;reg:squarederror&#39;, colsample_bytree=0.3, learning_rate=0.1, max_depth=3, alpha=10, n_estimators=100, random_state=42)<br>    else:<br>        raise ValueError(&quot;Invalid algorithm choice&quot;)<br>    model.fit(X_train, y_train)<br>    return model</pre><p>After training the model one can check statistical assessment of the model which includes predictions generation, and calculation basic metrics like (root) mean square error and R-square.</p><pre>def evaluate_model(model, X_test, y_test):<br>    y_pred = model.predict(X_test)<br>    mse = mean_squared_error(y_test, y_pred)<br>    rmse = np.sqrt(mse)<br>    r2 = r2_score(y_test, y_pred)<br>    return mse, rmse, r2</pre><p>With the foundation set, we now proceed to the final level of the implementation where we can see ultimate business results. Following codes snippets are demonstrating a complete workflow that brings together data preparation, model training and evaluation.</p><p>First let’s start by setting up our initial parameters.</p><pre># Example parameters - these can be adjusted based on your requirements<br>frequency = &#39;M&#39;<br>backtest_period = &#39;2023-01-01&#39;<br>number_of_stocks = 6<br>long_only = False<br>simul_random_backtest = False<br>exposure = 0.5<br>leverage = 1.5</pre><p>A mandatory step in any machine learning project is dividing the data into training and testing sets. This separation allows us to train our model on one subset of the data and test its performance on the another, completely unseen data.</p><pre># Load and scale data<br>df_filled = pd.read_csv(&#39;data/features.csv&#39;).dropna()<br>normalized_df = df_filled.groupby(&#39;Date&#39;).apply(scale).reset_index(drop=True)<br><br># Data Splitting<br>start, insample = &quot;2009-12-31&quot;, &quot;2019-12-31&quot;<br>X, y = normalized_df.iloc[:, 3:], normalized_df.iloc[:, 0]<br>X_train, y_train = X[(normalized_df.Date &gt; start) &amp; (normalized_df.Date &lt;= insample)], y[(normalized_df.Date &gt; start) &amp; (normalized_df.Date &lt;= insample)]<br>X_test, y_test = X[normalized_df.Date &gt; insample], y[normalized_df.Date &gt; insample]</pre><p>Captions can be used for filtering dataset and reducing dimensionality. Since we have 1269 totally, penalized linear regression hardly converge and therefore there is a need of some kind of preselection. Preselection itself is out of scope of this post and we have have proceeded the selection before.</p><p>With our data prepared, we move on to training the model and evaluating its performance.</p><pre>algorithm = &quot;xgboost&quot;  # Options: &quot;ridge&quot;, &quot;lasso&quot;, &quot;elasticnet&quot;, &quot;xgboost&quot;<br>model = train_model(X_train, y_train, algorithm)<br>mse, rmse, r2 = evaluate_model(model, X_test, y_test)<br>print(f&quot;Algorithm: {algorithm}, MSE: {mse}, RMSE: {rmse}, R-squared: {r2}&quot;)</pre><p>The final steps involves backtesting and assessing the model’s performance.</p><pre># Additional Processing...<br># Make predictions on the test set<br>y_pred = model.predict(X_test)<br>predictions = pd.DataFrame(y_pred)<br><br># Prepare data for testing perions assesment<br>market_data = df_filled[df_filled.Date &gt; insample].iloc[:, :3]<br><br># Calculate long and short positions from choosen leverage and market exposure<br>longs_share = (leverage + exposure) / 2<br>shorts_share = leverage -longs_share<br>print(f&#39;long rate: {longs_share} and short rate: {shorts_share} and leverage  {leverage}&#39;)<br><br>risk_free_rate = calculate_risk_free_rate(frequency)<br><br># Prepare market data for backtesting purposes<br>predictions.reset_index(drop=True,inplace=True)<br>market_data.reset_index(drop=True,inplace=True)<br>rebalances = pd.concat([market_data, predictions], axis=&#39;columns&#39;)<br>rebalances.columns = [&#39;Log_Return&#39;, &#39;Date&#39;, &#39;Symbol&#39;, &#39;Score&#39;]<br><br># Calculate rebalances used for decision which stocks go long/short<br>rebalances_for_backtest = rebalances.loc[rebalances.Date &gt;= backtest_period]<br>backtest_data = rebalances_for_backtest.groupby(&#39;Date&#39;, as_index=False).apply(lambda x: make_backtest(x, leverage, number_of_stocks, longs_share,shorts_share)).reset_index(drop=True)<br>backtest_data = add_benchmark(backtest_data, start_from=backtest_period)<br><br># Calculate performance metrics for final representation<br>equity_curves = proces_results(backtest_data).assign(Date=lambda df: pd.to_datetime(df[&#39;Date&#39;]))<br>metrics = calculate_performance_portfolio_metrics(equity_curves, risk_free_rate, frequency)</pre><p>Let’s break down backtesting logic for multi-factor model utilization. Our approach focuses on a long-short portfolio, a popular approach in quantitative finance. The core lays in taking long those stocks with higher “score” (estimated cross-sectionally scaled logarithmic return) and short those with the lowest value. Just reminding that this scaled values have mean 0 and standard deviation 1. The number of stocks to take long and short positions is in set by the user.</p><h3>Results and Discussion</h3><pre>| Metric                | LongOnly | LongTheShort | LongShort | Universe | SP500    |<br>|-----------------------|----------|--------------|-----------|----------|----------|<br>| Final-Equity          | 2.1465   | 1.3776       | 1.8288    | 1.6430   | 1.2772   |<br>| Volatility            | 0.3280   | 0.3352       | 0.2131    | 0.3076   | 0.1984   |<br>| Sharpe                | 0.8289   | 0.4378       | 0.9138    | 0.6292   | 0.4509   |<br>| Alpha-Universe        | 0.0787   | -0.0490      | 0.0997    | 0.0000   | 0.0981   |<br>| Alpha-SP500           | 0.2642   | 0.1683       | 0.1770    | 0.2032   | 0.0000   |<br>| Beta-Universe         | 0.9980   | 1.0113       | 0.4911    | 1.0000   | -0.0444  |<br>| Beta-SP500            | 0.0864   | -0.2395      | 0.1991    | -0.1068  | 1.0000   |<br>| CAGR                  | 0.2205   | 0.0872       | 0.1706    | 0.1383   | 0.0659   |<br>| Max-Drawdown          | -0.4602  | -0.4276      | -0.3253   | -0.4993  | -0.2497  |<br>| Average-Drawdown      | -0.1691  | -0.1634      | -0.1071   | -0.1880  | -0.0762  |<br>| Win-Rate              | 0.6444   | 0.4889       | 0.6667    | 0.5333   | 0.6000   |<br>| Skewness              | -0.1638  | 0.1170       | -0.2674   | -0.0845  | -0.2529  |<br>| Kurtosis              | 0.1531   | -0.8159      | 0.5162    | -0.5389  | -0.4112  |<br>| VaR95                 | -0.1461  | -0.1343      | -0.1046   | -0.1314  | -0.0872  |<br>| CVaR95                | -0.1618  | -0.1580      | -0.1189   | -0.1548  | -0.1022  |<br>| Max-Drawdown-Duration | 24.0000  | 24.0000      | 25.0000   | 25.0000  | 22.0000  |<br>| Calmar                | 0.4791   | 0.2038       | 0.5242    | 0.2770   | 0.2640   |<br>| Sterling              | 0.6822   | 0.2509       | 0.7117    | 0.3528   | 0.3392   |<br>| Sortino               | 1.5452   | 0.8933       | 1.6909    | 1.2241   | 0.8020   |</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*XQmpdr3LC5ZoYiO57FM15g.png" /></figure><h4>Overall Performance Metrics</h4><ol><li><strong>Final Equity:</strong> Represents the final value of the portfolio after the backtesting period. Higher values indicate better performance. The ‘LongOnly’ strategy leads here, suggesting it maximized the portfolio value most effectively.</li><li><strong>Volatility:</strong> Measures the degree of variation in portfolio returns. Lower volatility is generally preferred as it indicates less risk. ‘LongShort’ shows the lowest volatility, suggesting a more stable return profile.</li><li><strong>Sharpe Ratio:</strong> A measure of risk-adjusted return. Higher Sharpe ratios are better, indicating more return per unit of risk. ‘LongShort’ has the highest Sharpe ratio, highlighting its superior risk-adjusted performance.</li><li><strong>CAGR (Compound Annual Growth Rate):</strong> Indicates the mean annual growth rate of the investment. ‘LongOnly’ has the highest CAGR, showing strong growth over the period.</li></ol><h4>Risk and Drawdown Metrics</h4><ol><li><strong>Max Drawdown:</strong> The largest peak-to-trough drop in portfolio value. Lower values are better as they indicate lower potential losses. ‘LongShort’ strategy experienced the lowest maximum drawdown, suggesting a lower risk of significant losses.</li><li><strong>Average Drawdown:</strong> Average of the drawdowns during the backtesting period. Again, lower values are preferable. ‘LongShort’ maintains a lead with the lowest average drawdown.</li></ol><h4>Comparative Metrics with Benchmarks</h4><ol><li><strong>Alpha (Universe and SP500):</strong> Measures the portfolio’s excess return compared to a benchmark. Positive alpha indicates outperformance. ‘LongOnly’ shows a notable alpha compared to both Universe and SP500, suggesting it outperformed these benchmarks.</li><li><strong>Beta (Universe and SP500):</strong> Indicates the portfolio’s sensitivity to market movements. A beta close to 1 suggests the portfolio closely follows the market. ‘LongShort’ has a lower beta with the universe, indicating less sensitivity to market swings.</li></ol><h4>Other Statistical Metrics</h4><ol><li><strong>Skewness and Kurtosis:</strong> Measure the asymmetry and tail heaviness of the return distribution, respectively. The ‘LongOnly’ strategy shows a slight negative skewness, indicating a tendency for more frequent small gains and fewer large losses.</li><li><strong>VaR95 and CVaR95 (Value at Risk and Conditional Value at Risk):</strong> Indicate the maximum expected loss over a specified period at a 95% confidence interval. ‘LongShort’ exhibits lower VaR and CVaR values, suggesting lower potential losses under typical market conditions.</li></ol><h4>Efficiency Ratios</h4><ol><li><strong>Calmar and Sterling Ratios:</strong> Measure return per unit of downside risk. Higher values are preferable. ‘LongShort’ shows the highest Calmar and Sterling ratios, indicating efficient performance considering the risks involved.</li><li><strong>Sortino Ratio:</strong> Similar to the Sharpe ratio but focuses solely on downside volatility. ‘LongShort’ has the highest Sortino ratio, reaffirming its strong risk-adjusted performance focusing on downside risks.</li></ol><p>Overall, these results suggest that while the ‘LongOnly’ strategy had the highest final equity and growth rate, the ‘LongShort’ strategy demonstrated superior risk-adjusted returns, lower volatility, and drawdowns, making it potentially more appealing for risk-averse investors. Each strategy has its strengths and could be suited for different investment styles and risk appetites. Analyzing these metrics helps in making informed decisions about strategy selection and potential adjustments for future implementations.</p><p>For full implementation check out my <a href="https://github.com/michaldufek/factor_ml">github</a> for this use case. Next time, we are about to address the model instability.</p><p>Your feedback is highly appreciate. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b945c4cf2de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamline Your Portfolio: A One-Click Optimization Use Case]]></title>
            <link>https://medium.com/@michaldufek/streamline-your-portfolio-a-one-click-optimization-use-case-1ef119fbd09?source=rss-a876d2002eb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ef119fbd09</guid>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Michal Dufek]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 11:08:17 GMT</pubDate>
            <atom:updated>2023-04-13T11:11:16.751Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction:</strong></p><p>Investing in the stock market can be both exhilarating and overwhelming. As an investor, you might find yourself constantly evaluating and adjusting your portfolio to maximize returns and minimize risks. But what if you want to make changes without knowing which stock to remove? That’s where a one-click optimization solution comes in, designed to enhance your investment decisions.</p><p><strong>Making A Single Change Without Specifying a Stock</strong></p><p>One of the most innovative features of portfolio optimization tools is the ability to modify your portfolio while optimizing for specific financial goals — all without specifying a stock to remove. This use case is perfect for investors seeking to improve their portfolio’s performance but unsure of which stock to let go.</p><p><strong>Step 1: Review Your Current Portfolio</strong></p><p>Before diving into the optimization process, it’s essential to have a clear understanding of your current portfolio. For instance, let’s say your portfolio consists of four stocks: Amazon (AMZN), Ford (F), Raytheon Technologies (RTX), and Tesla (TSLA), all equally weighted.</p><p><strong>Step 2: Set Your Objectives</strong></p><p>Next, choose an objective function that best aligns with your investment goals. Options include minimizing volatility, maximizing the Sharpe ratio, or maximizing returns. This decision will guide the optimization process and help identify the most effective changes for your portfolio.</p><p><strong>Step 3: Optimize With One Click</strong></p><p>With your objective function selected, start the optimization process. The tool will analyze your existing portfolio and your saved pool of stocks (make sure this pool includes more stocks than those in your portfolio) to find the best replacement that aligns with your selected objective function.</p><p><strong>Step 4: Review Results and Iterate as Needed</strong></p><p>Once the optimization is complete, review the new stock suggestion, updated weights, and performance metrics. If you’re not satisfied with the results, you can easily change inputs and run the optimization process again, exploring different outcomes or adjusting the objective function to better suit your needs.</p><p><strong>Conclusion:</strong></p><p>One-click portfolio optimization solutions empower investors to make data-driven decisions and strategically adjust their portfolios for maximum performance. By offering a simplified process for making changes without specifying a stock to remove, these tools streamline the investment process and allow investors to focus on what truly matters — achieving their financial goals.</p><p>In our upcoming post, we will delve into the practical implementation of this use case using Python, a versatile programming language popular among finance professionals and data analysts. We will demonstrate how to leverage Python libraries and techniques to manage and optimize your portfolio with ease. Stay tuned for this guide that will help you harness the power of Python to achieve your investment objectives and build a stronger, more efficient portfolio. Happy investing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ef119fbd09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Portfolio Adjustment: A Practical Guide to Smart Optimization with Python]]></title>
            <link>https://medium.com/@michaldufek/efficient-portfolio-adjustment-a-practical-guide-to-smart-optimization-with-python-603dd3dec932?source=rss-a876d2002eb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/603dd3dec932</guid>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Michal Dufek]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 07:33:12 GMT</pubDate>
            <atom:updated>2023-04-06T07:39:48.265Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In our previous post, we delved into the concept of advanced portfolio management, focusing on a specific use case: smart stock replacement. By selectively replacing stocks in an existing portfolio, investors can optimize their investments while minimizing transaction costs associated with frequent rebalancing. This approach allows for more precise adjustments to a portfolio, catering to an individual’s risk profile and investment objectives.</p><p>Building on that foundation, we now present a practical guide to implementing this smart stock replacement strategy using Python programming. In this post, we provide a step-by-step tutorial and code snippets to empower investors with the tools necessary to optimize their portfolios and make data-driven decisions. By following this guide, you can enhance your investment outcomes and achieve a more efficient and risk-adjusted portfolio.</p><p>Join us as we explore how to implement advanced portfolio management techniques using Python, bridging the gap between theory and practice to help you take control of your investments.</p><ol><li>Install required libraries:</li></ol><pre>!pip install pandas numpy yfinance</pre><p>2. Import required libraries:</p><pre>import pandas as pd<br>import numpy as np<br>import yfinance as yf<br>from scipy.optimize import minimize<br>import matplotlib.pyplot as plt</pre><p>3. Define a function to download stock data:</p><pre>def download_stock_data(tickers, start_date, end_date):<br>    data = yf.download(tickers, start=start_date, end=end_date)[&#39;Adj Close&#39;]<br>    return data</pre><p>4. Calculate daily returns:</p><pre>daily_returns = stock_data.pct_change().dropna()</pre><p>5. Define a function to calculate the portfolio performance:</p><pre>def portfolio_performance(weights, mean_returns, cov_matrix):<br>    returns = np.sum(mean_returns * weights) * 252<br>    std_dev = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights))) * np.sqrt(252)<br>    return std_dev, returns</pre><p>6. Define a function to optimize the portfolio:</p><pre>def optimize_portfolio(mean_returns, cov_matrix, num_assets, target_return=None):<br>    def objective_function(weights):<br>        return -1 * (np.sum(mean_returns * weights) * 252) / (np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights))) * np.sqrt(252))<br><br>    constraints = [{&#39;type&#39;: &#39;eq&#39;, &#39;fun&#39;: lambda x: np.sum(x) - 1}]<br>    if target_return is not None:<br>        constraints.append({&#39;type&#39;: &#39;eq&#39;, &#39;fun&#39;: lambda x: target_return - portfolio_performance(x, mean_returns, cov_matrix)[1]})<br><br>    bounds = [(0, 1) for _ in range(num_assets)]<br>    initial_guess = np.array(num_assets * [1. / num_assets])<br><br>    optimized = minimize(objective_function, initial_guess, bounds=bounds, constraints=constraints)<br>    return optimized[&#39;x&#39;]</pre><p>7. Remove RTX from the portfolio and add potential replacement stocks:</p><pre>current_portfolio = [&#39;AMZN&#39;, &#39;F&#39;, &#39;TSLA&#39;]<br>potential_replacements = [&#39;AAPL&#39;, &#39;GOOGL&#39;, &#39;MSFT&#39;]</pre><p>8. Optimize the portfolio with different combinations of replacement stocks:</p><pre>portfolio_weights = []<br>for i in range(len(potential_replacements) + 1):<br>    for combo in itertools.combinations(potential_replacements, i):<br>        new_portfolio = current_portfolio + list(combo)<br>        portfolio_weight = optimize_portfolio(mean_returns[new_portfolio], cov_matrix.loc[new_portfolio, new_portfolio], len(new_portfolio))<br>        portfolio_weights.append((new_portfolio, portfolio_weight))</pre><p>9. Calculate and plot the efficient frontier:</p><pre>portfolio_returns = []<br>portfolio_volatility = []<br><br>for portfolio, weights in portfolio_weights:<br>    vol, ret = portfolio_performance(weights, mean_returns[portfolio], cov_matrix.loc[portfolio, portfolio])<br>    portfolio_returns.append(ret)<br>    portfolio_volatility.append(vol)<br><br>plt.figure(figsize=(12, 6))<br>plt.scatter(portfolio_volatility, portfolio_returns, c=(np.array(portfolio_returns) / np.array(portfolio_volatility)), marker=&#39;o&#39;, cmap=&#39;viridis&#39;)<br>plt.colorbar(label=&#39;Sharpe Ratio&#39;)<br>plt.xlabel(&#39;Volatility&#39;)<br>plt.ylabel(&#39;Expected Returns&#39;)<br>plt.title(&#39;Efficient Frontier: Portfolio Optimization&#39;)<br>plt.show()</pre><p><strong>Results</strong></p><pre>Portfolio 1: AMZN, F, TSLA, AAPL<br>  Weights: AMZN: 34.95%, F: 23.54%, TSLA: 16.84%, AAPL: 24.67%<br>  Expected Return: 30.72%<br>  Volatility: 26.35%<br><br>Portfolio 2: AMZN, F, TSLA, GOOGL<br>  Weights: AMZN: 39.67%, F: 26.25%, TSLA: 19.40%, GOOGL: 14.68%<br>  Expected Return: 31.96%<br>  Volatility: 26.33%<br><br>Portfolio 3: AMZN, F, TSLA, MSFT<br>  Weights: AMZN: 38.44%, F: 25.19%, TSLA: 18.17%, MSFT: 18.20%<br>  Expected Return: 32.23%<br>  Volatility: 26.12%<br><br>Portfolio 4: AMZN, F, TSLA, AAPL, GOOGL<br>  Weights: AMZN: 29.87%, F: 21.02%, TSLA: 14.62%, AAPL: 20.69%, GOOGL: 13.80%<br>  Expected Return: 33.05%<br>  Volatility: 25.97%<br><br>Portfolio 5: AMZN, F, TSLA, AAPL, MSFT<br>  Weights: AMZN: 28.87%, F: 19.93%, TSLA: 13.20%, AAPL: 20.46%, MSFT: 17.54%<br>  Expected Return: 33.31%<br>  Volatility: 25.76%<br><br>Portfolio 6: AMZN, F, TSLA, GOOGL, MSFT<br>  Weights: AMZN: 34.47%, F: 23.30%, TSLA: 15.98%, GOOGL: 13.11%, MSFT: 13.14%<br>  Expected Return: 34.55%<br>  Volatility: 25.74%<br><br>Portfolio 7: AMZN, F, TSLA, AAPL, GOOGL, MSFT<br>  Weights: AMZN: 25.87%, F: 17.93%, TSLA: 11.62%, AAPL: 16.46%, GOOGL: 13.96%, MSFT: 14.16%<br>  Expected Return: 35.03%<br>  Volatility: 25.38%</pre><p>This example output displays the expected return and volatility for each possible portfolio combination, considering the stocks from current_portfolio and potential_replacements. The plot of the efficient frontier illustrates the trade-offs between risk and return for these different stock combinations, helping you make an informed decision on which stock(s) to replace RTX with based on your risk profile and investment objectives. Please note that the actual output values may vary depending on the specific stock data and date range used.</p><p><strong>Conclusion</strong></p><p>In conclusion, the provided Python code snippets guide you through the process of implementing a smart stock replacement strategy based on the use case we discussed earlier. Here’s a summary of the steps taken:</p><ol><li>Install and import the required libraries (pandas, numpy, yfinance, and scipy.optimize).</li><li>Define functions for downloading stock data, calculating portfolio performance, and optimizing the portfolio.</li><li>Download stock data for the original portfolio (AMZN, F, TSLA, RTX) and potential replacement stocks.</li><li>Calculate daily returns, mean returns, and the covariance matrix.</li><li>Remove RTX from the portfolio and identify potential replacement stocks.</li><li>Optimize the portfolio with different combinations of replacement stocks.</li><li>Calculate and plot the efficient frontier, illustrating the trade-offs between risk and return for different stock combinations.</li></ol><p>By following these steps, you can analyze the efficient frontier to determine the optimal stock(s) to replace RTX based on your risk profile and investment objectives. The provided code allows you to customize the current_portfolio and potential_replacements variables to suit your specific investment scenario, offering a flexible and powerful tool for advanced portfolio management.</p><p>Utilizing this smart stock replacement strategy, you can make informed decisions on how to adjust your portfolio while minimizing transaction costs associated with frequent rebalancing. This approach enables you to optimize your portfolio according to your risk profile and ultimately achieve a more efficient and risk-adjusted portfolio.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=603dd3dec932" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Portfolio Management: Stock Replacement for More Efficient Portfolio]]></title>
            <link>https://medium.com/@michaldufek/smart-portfolio-management-stock-replacement-for-a-more-efficient-portfolio-42340637c3b0?source=rss-a876d2002eb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/42340637c3b0</guid>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[financial-markets]]></category>
            <category><![CDATA[smart-investment]]></category>
            <category><![CDATA[stocks]]></category>
            <dc:creator><![CDATA[Michal Dufek]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 05:05:35 GMT</pubDate>
            <atom:updated>2023-04-06T07:09:12.147Z</atom:updated>
            <content:encoded><![CDATA[<p>Optimize your portfolio with minimal transaction costs by making informed stock replacement decisions.</p><p><strong>Introduction</strong></p><p>Portfolio management is a critical aspect of investing that involves making strategic decisions to maximize returns while minimizing risks. In our previous post, we discussed portfolio optimization, which is essential for investors seeking to create a balanced and efficient portfolio. In this follow-up article, we delve into a more advanced use case: selectively replacing stocks in an existing portfolio. This approach helps minimize transaction costs associated with frequent rebalancing and allows for a more efficient, risk-adjusted portfolio.</p><p><strong>Use Case: Removing and Replacing a Stock in Your Portfolio</strong></p><p>Imagine you have a portfolio containing four equally-weighted stocks: Amazon (AMZN), Ford (F), Raytheon Technologies (RTX), and Tesla (TSLA). You’ve decided to remove RTX from your portfolio, and you want to make a smart decision about which stock(s) to replace it with. Instead of rebalancing your entire portfolio, you can use a specific optimization tool to recalculate the efficient frontier, taking into account your risk profile and the remaining stocks in your portfolio.</p><p><strong>Steps for Smart Stock Replacement:</strong></p><ol><li>Identify your risk profile: Before making any changes to your portfolio, it’s crucial to understand your risk tolerance. Are you a conservative, moderate, or aggressive investor? Your risk profile will guide your decision-making process when selecting alternative stocks.</li><li>Analyze the remaining stocks: Examine the performance, volatility, and correlation of the three remaining stocks (AMZN, F, TSLA) in your portfolio. This information will help you determine how these stocks interact with one another and how they may impact the overall risk and return of your portfolio.</li><li>Find alternative stocks: Using your risk profile, search for potential replacement stocks that match your investment objectives. Consider factors such as industry, market capitalization, and historical performance when making your selection.</li><li>Recalculate the efficient frontier: With the alternative stocks identified, use the optimization tool to recalculate the efficient frontier. This process will help you visualize the trade-offs between risk and return for different stock combinations, including your original portfolio and the new alternatives.</li><li>Make an informed decision: Based on the efficient frontier and your risk profile, decide which stock(s) to replace RTX with. This may involve replacing RTX with a single stock or diversifying by adding multiple stocks to your portfolio.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7eDva_ja64ZJtYr61aajvQ.png" /><figcaption>Initial and recalculated efficient frontier with respect to the remove stock</figcaption></figure><p><strong>Conclusion</strong></p><p>By employing a smart stock replacement strategy, investors can optimize their portfolios while minimizing transaction costs associated with frequent rebalancing. This approach allows for more precise adjustments to a portfolio, catering to an individual’s risk profile and investment objectives. By carefully analyzing the efficient frontier and potential alternative stocks, investors can make well-informed decisions that ultimately lead to a more efficient and risk-adjusted portfolio.</p><p>In our upcoming post, we will demonstrate how to implement this advanced portfolio management strategy using Python programming. By providing step-by-step guidance and sample code, we aim to empower investors with the tools necessary to optimize their portfolios, make data-driven decisions, and enhance their investment outcomes. Stay tuned for this practical and insightful guide to applying smart stock replacement techniques using Python.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42340637c3b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing Custom Portfolios to the Efficient Frontier: A Python Workflow]]></title>
            <link>https://medium.com/@michaldufek/comparing-custom-portfolios-to-the-efficient-frontier-a-python-workflow-fa4ed9270eac?source=rss-a876d2002eb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa4ed9270eac</guid>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[investing]]></category>
            <dc:creator><![CDATA[Michal Dufek]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 14:21:36 GMT</pubDate>
            <atom:updated>2023-04-06T05:01:02.636Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>When it comes to investing, one of the most important decisions you’ll make is how to allocate your assets across different securities. There are many approaches to portfolio construction, each with its own advantages and drawbacks. One common method is to create a custom portfolio, where you hand-pick a selection of securities based on your investment goals and risk tolerance. However, how do you know if your custom portfolio is performing as well as it could be? In this article, we’ll explore how to compare a custom portfolio to the efficient frontier using Python, and see how this analysis can help you optimize your investment strategy.</p><p><strong>Understanding the Efficient Frontier</strong></p><p>To start, we need to understand what the efficient frontier is and why it’s important. The efficient frontier is a graph that shows the optimal portfolios that maximize expected returns for a given level of risk. This means that any portfolio that falls on the efficient frontier represents the best possible risk-return tradeoff for that level of risk. By comparing a custom portfolio to the efficient frontier, we can see how well it’s performing relative to the optimal portfolios.</p><p><strong>Building a Custom Portfolio</strong></p><p>Before we can compare our custom portfolio to the efficient frontier, we need to build it. We can do this using Python and a financial data library like pandas and pypfopt. Here’s an example code snippet:</p><pre># Building a Custom Portfolio<br><br>import pandas as pd<br>import yfinance as  yf<br>from pypfopt import base_optimizer, expected_returns, risk_models<br><br>tickers = [&#39;AAPL&#39;, &#39;AMZN&#39;, &#39;GOOG&#39;, &#39;TSLA&#39;]<br><br>custom_portfolio = {<br>    &#39;AAPL&#39;: 0.25,<br>    &#39;AMZN&#39;: 0.25,<br>    &#39;GOOG&#39;: 0.25,<br>    &#39;TSLA&#39;: 0.25<br>}<br><br>prices = yf.download(tickers)[&#39;Adj Close&#39;]<br>prices = prices.dropna(axis=1, how=&#39;all&#39;).dropna()<br>weights = list(custom_portfolio.values())</pre><p>To compute the efficient frontier, we need to specify the expected returns and covariance matrix for the securities in our portfolio. We can then use a portfolio optimization library like pypfopt to estimate the weights that maximize expected returns for a given level of risk.</p><p><strong>Computing Portfolio Metrics</strong></p><p>Once we have our custom portfolio, we need to compute some metrics to compare it to the efficient frontier. These metrics include expected returns, standard deviation (i.e., volatility or risk), and Sharpe ratio (i.e., risk-adjusted returns). We’ll use Python and library pypfopt to compute these metrics. Here’s an example code snippet:</p><pre># Computing Portfolio Metrics<br><br>returns = prices.pct_change().dropna()<br>exp_returns = expected_returns.ema_historical_return(prices, frequency=252)<br>cov_matrix = risk_models.CovarianceShrinkage(prices).ledoit_wolf()<br>metrics = base_optimizer.portfolio_performance(<br>    weights, exp_returns, cov_matrix, verbose=True<br>)<br><br>performance_metrics = {<br>    &#39;Expected_returns&#39;: metrics[0],<br>    &#39;Volatility&#39;: metrics[1],<br>    &#39;Sharpe&#39;: metrics[2]<br>}<br><br>performance_metrics</pre><pre># For example, the output of this code snippet might be:<br>{&#39;Expected_returns&#39;: -0.0008419897031320123,<br> &#39;Volatility&#39;: 0.2777600762389265,<br> &#39;Sharpe&#39;: -0.07503594463735651}</pre><p>This tells us that for this particular set of securities, we can expect a return of approximately 0% with a volatility of approximately 27.7%. The Sharpe ratio, which measures the risk-adjusted returns, is approximately -0.075. By computing the efficient frontier and comparing our custom portfolio to it, we can determine how well our portfolio is performing relative to the optimal portfolios.</p><p><strong>Computing Efficient Frontier</strong></p><p>Now we need to compute the efficient frontier using Python. To do this, we’ll use the Riskfolio-Lib library, which is a Python library for portfolio optimization and risk management. Here&#39;s an example code snippet:</p><pre># Computing Efficient Frontier<br><br># Building the portfolio object<br>port = rp.Portfolio(returns=returns)<br># Select method and estimate input parameters:<br>port.assets_stats(method_mu=&quot;hist&quot;, method_cov=&quot;hist&quot;)<br># Estimate efficient frontier weights:<br>frontier = port.efficient_frontier(<br>    model=&quot;Classic&quot;, rm=&quot;MV&quot;, kelly=False, points=100, rf=0, hist=True<br>)<br><br>ef_coordinates = pd.DataFrame(columns=[&#39;Expected_returns&#39;, &#39;Volatility&#39;, &#39;Sharpe&#39;])<br>for i in range(len(frontier.T)):<br>    metrics = base_optimizer.portfolio_performance(<br>        frontier.T.iloc[i,:],<br>        exp_returns,<br>        cov_matrix<br>    )<br>    performance_dict = {<br>    &#39;Expected_returns&#39;: metrics[0],<br>    &#39;Volatility&#39;: metrics[1],<br>    &#39;Sharpe&#39;: metrics[2]<br>}<br>coordinate = pd.DataFrame(performance_dict, index=[i])<br>ef_coordinates = pd.concat([ef_coordinates, coordinate])<br>ef_coordinates</pre><p>When we run this code snippet, we get a table of weights for each security on the efficient frontier and a table of performance metrics for each point on the efficient frontier. Here’s an example of what the table might look like:</p><p>Weights for each security in portfolio:</p><pre>          AAPL      AMZN      GOOG      TSLA<br>0     0.395888  0.144665  0.450501  0.008947<br>1     0.419544  0.172137  0.334101  0.074218<br>2     0.429453  0.183645  0.285331  0.101570<br>3     0.437140  0.192567  0.247524  0.122770<br>4     0.443681  0.200164  0.215336  0.140820<br>...        ...       ...       ...       ...<br>95    1.205532e-10 1.212701e-10 9.245806e-11 1.000000</pre><p>And the table of performance metrics for each point on the efficient frontier:</p><pre>    Expected_returns  Volatility     Sharpe<br>0          -0.002782    0.243326 -0.093627<br>1           0.011167    0.246550 -0.035827<br>2           0.017012    0.249853 -0.011960<br>3           0.021543    0.253169  0.006094<br>4           0.025400    0.256491  0.021054<br>..               ...         ...       ...<br>95          0.106800    0.559866  0.155036<br>96          0.106530    0.563203  0.153638<br>97          0.106260    0.566541  0.152258<br>98          0.105992    0.569878  0.150895<br>99          0.105723    0.573216  0.149548</pre><p>This table shows us the expected returns, volatility, and Sharpe ratio for 100 points on the efficient frontier. We can use this table to compare the performance of our custom portfolio to the optimal portfolios.</p><p><strong>Plotting the Efficient Frontier</strong></p><p>With our custom portfolio metrics in hand, we can now plot the efficient frontier. We’ll use Python and the plotly library to do this. The efficient frontier is a curve that shows the optimal portfolios for different levels of risk. Here’s an example code snippet:</p><pre># Plotting the Efficient Frontier<br><br>import plotly.express as px<br>import plotly.graph_objects as go<br><br>fig = px.line(<br>    ef_coordinates, x=&#39;Volatility&#39;, y=&#39;Expected_returns&#39;, title=&#39;Efficient Frontier&#39;<br>)<br>fig.add_trace(go.Scatter(x=[ performance_metrics[&#39;Volatility&#39;] ],<br>                        y=[ performance_metrics[&#39;Expected_returns&#39;] ],<br>                        mode=&#39;markers&#39;, marker=dict(size=15), name=&#39;myPortfolio&#39;))<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LtTxoi9uIJgYpIWtAwMcw.png" /><figcaption>Comparison of the efficient portfolio and custom portfolio. Still do you thing your portfolio is the most efficient?</figcaption></figure><p><strong>Conclusion</strong></p><p>Comparing a custom portfolio to the efficient frontier can help you optimize your investment strategy and ensure that you’re achieving the best possible risk-return tradeoff. With Python and financial data libraries, it’s easy to build a custom portfolio, compute portfolio metrics, and plot the efficient frontier. By following this workflow, you can analyze your current portfolio and make informed decisions about how to improve it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa4ed9270eac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Balanced Portfolio with Constraints and Limits: Practical Tips for Achieving Your…]]></title>
            <link>https://medium.com/@michaldufek/building-a-balanced-portfolio-with-constraints-and-limits-practical-tips-for-achieving-your-cb29a9b8f381?source=rss-a876d2002eb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb29a9b8f381</guid>
            <dc:creator><![CDATA[Michal Dufek]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 21:51:35 GMT</pubDate>
            <atom:updated>2023-04-06T05:02:30.214Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Balanced Portfolio with Constraints and Limits: Practical Tips for Achieving Your Investment Objectives</h3><p>Want to optimize your investment portfolio for maximum returns? Look no further than the power of constraints and limits. By applying these practical techniques to your portfolio, you can achieve a better balance of risk and reward and meet your investment objectives with ease. In this article, we’ll explore the real-world benefits of portfolio optimization with constraints and limits, and show you how to use these tools to build a well-diversified portfolio that delivers results.</p><p>Portfolio optimization is a powerful tool that investors use to build a portfolio of assets that maximizes returns while minimizing risk. One way to achieve this is by applying specific constraints to the portfolio, such as limiting the weight of certain assets, alternating specific companies in the portfolio, or forcing a specific number of companies in the portfolio.</p><p>Here are some specific examples of portfolio optimization use cases that demonstrate the benefits of applying these constraints:</p><ol><li><strong>Limiting the weight of certain assets</strong></li></ol><p>Suppose an investor has a portfolio of tech stocks and wants to limit their exposure to a particular stock, such as Apple. The investor can use portfolio optimization techniques to set a maximum weight constraint on Apple’s stock, ensuring that it doesn’t make up too much of the portfolio. For example, let’s say the investor has $100,000 to invest in tech stocks and wants to limit their exposure to Apple to no more than 20% of the portfolio. The investor could use mean-variance optimization to determine the optimal allocation of assets that meets this constraint.</p><pre>| Asset | Weight | Return | Standard Deviation |<br>|-------|--------|--------|-------------------|<br>| Apple | 20%    | 10%    | 20%               |<br>| Google| 30%    | 8%     | 15%               |<br>| Amazon| 30%    | 12%    | 25%               |<br>| Tesla | 20%    | 15%    | 30%               |</pre><p>In this example, the investor’s optimal allocation would be to invest 20% of their portfolio in Apple, 30% in Google, 30% in Amazon, and 20% in Tesla.</p><p><strong>2. Alternating specific companies in the portfolio</strong></p><p>Some investors may want to build a portfolio that includes exposure to multiple companies in a particular sector or industry. However, they may also want to limit their exposure to any single company in that sector. To achieve this, investors can use portfolio optimization techniques to alternate between specific companies in the portfolio, ensuring that no single company dominates the portfolio.</p><p>For example, suppose an investor has $100,000 to invest in the healthcare sector and wants to include exposure to four companies: Pfizer, Johnson &amp; Johnson, Merck, and Novartis. The investor wants to limit their exposure to any single company to no more than 25% of the portfolio. The investor could use mean-variance optimization to determine the optimal allocation of assets that meets this constraint.</p><pre>| Asset          | Weight | Return | Standard Deviation |<br>|----------------|--------|--------|-------------------|<br>| Pfizer         | 25%    | 5%     | 10%               |<br>| Johnson &amp; Johnson | 25% | 8%     | 12%               |<br>| Merck          | 25%    | 7%     | 15%               |<br>| Novartis       | 25%    | 9%     | 18%               |</pre><p>In this example, the investor’s optimal allocation would be to invest 25% of their portfolio in Pfizer, 25% in Johnson &amp; Johnson, 25% in Merck, and 25% in Novartis.</p><p><strong>3. Forcing a specific number of companies in the portfolio</strong></p><p>Another use case for portfolio optimization is to force a specific number of companies in the portfolio. For example, an investor may want to build a portfolio that includes exposure to ten different companies but wants to ensure that no single company dominates the portfolio. By using portfolio optimization techniques to set constraints on the number of companies in the portfolio, investors can achieve this goal.</p><p>For example, suppose an investor has $100,000 to invest in the energy sector and wants to include exposure to ten different companies. The investor wants to ensure that no single company makes up more than 10% of the portfolio. The investor could use mean-variance optimization to determine the optimal allocation of assets that meets these constraints.</p><pre>| Asset      | Weight | Return | Standard Deviation |<br>|------------|--------|--------|-------------------|<br>| Exxon      | 10%    | 7%     | 15%               |<br>| Chevron    | 10%    | 5%     | 10%               |<br>| ConocoPhillips | 10% | 8%     | 20%               |<br>| BP         | 10%    | 9%     | 18%               |<br>| Royal Dutch Shell | 10% | 6% | 13%               |<br>| Total      | 10%    | 7%     | 12%               |<br>| Eni        | 10%    | 10%    | 25%               |<br>| Gazprom    | 10%    | 12%    | 30%               |<br>| PetroChina | 10%    | 8%     | 22%               |<br>| Sinopec    | 10%    | 11%    | 28%               |</pre><p>In this example, the investor’s optimal allocation would be to invest 10% of their portfolio in each of the ten companies. This ensures that no single company dominates the portfolio and the investor has a well-diversified portfolio.</p><p>In conclusion, portfolio optimization is a powerful technique that can help investors achieve their investment goals. By applying specific constraints, such as limiting the weight of certain assets, alternating specific companies in the portfolio, or forcing a specific number of companies in the portfolio, investors can build a portfolio that is well-diversified and balanced. With the help of portfolio optimization techniques, investors can make more informed investment decisions and maximize their returns while minimizing their risk.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb29a9b8f381" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>