<?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 Saksham Solanki on Medium]]></title>
        <description><![CDATA[Stories by Saksham Solanki on Medium]]></description>
        <link>https://medium.com/@saksham.solanki?source=rss-f3bc24a20519------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E4rNp5-uVDtnlY2yLMc4qQ.jpeg</url>
            <title>Stories by Saksham Solanki on Medium</title>
            <link>https://medium.com/@saksham.solanki?source=rss-f3bc24a20519------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:51:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saksham.solanki/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[Python for Finance: Implementing Modern Portfolio Theory]]></title>
            <link>https://wire.insiderfinance.io/python-for-finance-implementing-modern-portfolio-theory-df3e10b911ba?source=rss-f3bc24a20519------2</link>
            <guid isPermaLink="false">https://medium.com/p/df3e10b911ba</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Saksham Solanki]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 14:17:35 GMT</pubDate>
            <atom:updated>2025-01-29T14:17:35.568Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last post we learned what risk was, explored different measures of risk and how to calculate risk metrics using Python. In this post we will learn about Modern Portfolio Theory, the main concepts behind Modern Portfolio Theory and implementing it all in Python.</p><p><a href="https://wire.insiderfinance.io/python-for-finance-risk-adjusted-returns-92af4789321d">Python for Finance: Risk adjusted returns</a></p><h3>Introduction</h3><p>Modern Portfolio Theory (MPT), developed by <strong>Harry Markowitz</strong> in 1952, is a framework for constructing a portfolio of assets to maximize the expected return for a given level of risk or minimize risk for a given level of expected return. The theory is based on the idea of diversification, where combining assets with varying levels of risk and return can reduce the overall risk of the portfolio.</p><h4>Portfolio Expected Returns</h4><p>Portfolio Expected Returns are just the sum of the expected returns of the assets in the portfolio multiplied by the weights of those assets in that portfolio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*cxUPtnzXlYenDxQARQusUA.png" /><figcaption>Portfolio Expected Returns Formula</figcaption></figure><p>Where:</p><ul><li>E(Rp​): Portfolio’s expected return</li><li>wi​: Weight of asset i in the portfolio</li><li>E(Ri​): Expected return of asset i</li><li>n: Number of assets</li></ul><p>Let us take an example portfolio with three Assets A, B and C</p><ul><li>Asset A: Expected Return = 8%, Weight = 40%.</li><li>Asset B: Expected Return = 12%, Weight = 40%.</li><li>Asset C: Expected Return = 15%, Weight = 20%</li></ul><pre>import numpy as np<br><br># Step 1: Define the expected returns for each asset<br># Example: Expected returns are in decimal form (e.g., 10% = 0.10)<br>expected_returns = np.array([0.08, 0.12, 0.15])  # Asset 1: 8%, Asset 2: 12%, Asset 3: 15%<br><br># Step 2: Define the portfolio weights for each asset<br># The weights should sum to 1<br>weights = np.array([0.4, 0.4, 0.2])  # 40% in Asset 1, 40% in Asset 2, 20% in Asset 3<br><br># Step 3: Calculate the portfolio&#39;s expected return<br># Portfolio Expected Return = Sum of (Weight * Expected Return) for each asset<br>portfolio_expected_return = np.dot(weights, expected_returns)<br><br># Output the result<br>print(&quot;Asset Expected Returns: &quot;, expected_returns)<br>print(&quot;Portfolio Weights:       &quot;, weights)<br>print(f&quot;Portfolio Expected Return: {portfolio_expected_return:.2%}&quot;)</pre><p><strong>Output</strong></p><pre>Asset Expected Returns:  [0.08 0.12 0.15]<br>Portfolio Weights:        [0.4 0.4 0.2]<br>Portfolio Expected Return: 11.00%</pre><h4>Portfolio Risk and Covariance Matrix</h4><p>Covariance captures the relationship between two assets. A <strong>positive covariance</strong> means that the returns of two assets tend to move in the same direction. A <strong>negative covariance</strong> means that the returns tend to move in opposite directions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*THKaAApwDTtqZmZ9pcR3Zw.png" /><figcaption>Covariance Formula</figcaption></figure><ul><li>Ri,t​: Return of asset i at time t</li><li>Rˉi​: Mean return of asset i</li><li>n: number of observations</li></ul><p>When we have multiple assets we can use a <strong>Covariance Matrix, </strong>it’s a square matrix where each element (i,j) represents the covariance between the returns of asset i and asset j.</p><p>For a portfolio with n assets, the covariance matrix is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*9AEgPrqyDns5c-Qa1OuKtQ.png" /><figcaption>Covariance Matrix</figcaption></figure><p>The covariance matrix is crucial for calculating the <strong>portfolio’s risk (volatility)</strong>, which depends not only on the variances of individual assets but also on how those assets are correlated. <strong>Portfolio Variance Formula</strong>: The variance (or squared risk) of a portfolio is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*vc2HwiJTZsk8snwZgSkRxA.png" /><figcaption>Portfolio Variance Formula</figcaption></figure><p>In python we can simply calculate the covariance matrix and the portfolio volatility simply by</p><pre>cov_matrix = returns.cov()<br>portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))</pre><p>We can now create a simple function that calculates the performance of a portfolio</p><pre>def portfolio_performance(weights, mean_returns, cov_matrix):<br>    &quot;&quot;&quot;<br>    Calculate portfolio performance (return and volatility)<br>    based on weights.<br>    &quot;&quot;&quot;<br>    portfolio_return = np.dot(weights, mean_returns)<br>    portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))<br>    return portfolio_return, portfolio_volatility</pre><h4>Efficient Frontier</h4><p>The efficient frontier represents the set of portfolios that offer the highest expected return for a given level of risk</p><p>To calculate the efficient frontier in python we will need to use the scipy library. specifically its minimize function, because it allows us to solve optimization problems numerically with constraints, such as minimizing portfolio risk while ensuring the portfolio&#39;s weights sum to 1 and achieving a specified target return.</p><pre>from scipy.optimize import minimize<br><br>def calculate_efficient_frontier(mean_returns, cov_matrix, num_points=100):<br>    results = {&quot;returns&quot;: [], &quot;volatility&quot;: [], &quot;weights&quot;: []}<br>    for target_return in np.linspace(mean_returns.min(), mean_returns.max(), num_points):<br>        constraints = [<br>            {&quot;type&quot;: &quot;eq&quot;, &quot;fun&quot;: lambda x: portfolio_performance(x, mean_returns, cov_matrix)[0] - target_return},<br>            {&quot;type&quot;: &quot;eq&quot;, &quot;fun&quot;: lambda x: np.sum(x) - 1},<br>        ]<br>        bounds = tuple((0, 1) for _ in range(len(mean_returns)))<br><br>        result = minimize(<br>            lambda x: portfolio_performance(x, mean_returns, cov_matrix)[1],  # Minimize risk<br>            len(mean_returns) * [1.0 / len(mean_returns)],  # Initial guess for weights<br>            method=&quot;SLSQP&quot;,<br>            bounds=bounds,<br>            constraints=constraints,<br>        )<br>        if result.success:<br>            results[&quot;returns&quot;].append(target_return)  # Store target return<br>            results[&quot;volatility&quot;].append(result.fun)  # Store volatility (minimized risk)<br>            results[&quot;weights&quot;].append(result.x)      # Store weights for the portfolio<br>    return resultsFunction Inputs:</pre><ul><li>mean_returns: The expected returns of individual assets.</li><li>cov_matrix: The covariance matrix of the asset returns.</li><li>num_points: Number of target returns to evaluate along the frontier.</li></ul><p>We use np.linspace to create a range of target returns from the minimum to the maximum mean return.</p><p><strong>Constraints</strong>:</p><ul><li>The portfolio return equals the target return.</li><li>The weights sum to 1 (fully invested portfolio).</li></ul><p><strong>Bounds:</strong></p><p>The bounds prevent short selling, meaning weights must lie between 0 and 1:</p><pre>bounds = tuple((0, 1) for _ in range(num_assets))</pre><p>The initial guess for the optimizer is an equally weighted portfolio</p><h4>Optimization with scipy.optimize.minimize:</h4><ul><li><strong>Objective Function</strong>: Minimize portfolio volatility.</li><li><strong>Method</strong>: SLSQP (Sequential Least Squares Quadratic Programming), which supports constraints and bounds.</li><li><strong>Constraints</strong>: The two constraints (weights sum to 1, portfolio return matches target).</li><li><strong>Bounds</strong>: Ensure no short selling.</li></ul><p>The optimizer returns the result:</p><pre>result = minimize(<br>    lambda x: np.sqrt(np.dot(x.T, np.dot(cov_matrix, x))),  # Minimize volatility<br>    num_assets * [1.0 / num_assets],  # Initial guess<br>    method=&quot;SLSQP&quot;,<br>    bounds=bounds,<br>    constraints=constraints<br>)</pre><h4>Optimized Portfolio</h4><p>The <strong>optimized portfolio</strong> is the portfolio that maximizes the Sharpe ratio, which is a measure of risk-adjusted return.</p><pre>def optimize_portfolio(mean_returns, cov_matrix, risk_free_rate):<br>    num_assets = len(mean_returns)<br>    args = (mean_returns, cov_matrix, risk_free_rate)<br>    constraints = {&quot;type&quot;: &quot;eq&quot;, &quot;fun&quot;: lambda x: np.sum(x) - 1}  # Sum of weights = 1<br>    bounds = tuple((0, 1) for _ in range(num_assets))  # No short selling<br><br>    result = minimize(<br>        negative_sharpe_ratio,<br>        num_assets * [1.0 / num_assets],  # Initial weights<br>        args=args,<br>        method=&quot;SLSQP&quot;,<br>        bounds=bounds,<br>        constraints=constraints<br>    )<br>    return result</pre><ul><li>mean_returns: The expected returns of individual assets.</li><li>cov_matrix: The covariance matrix of the asset returns.</li><li>risk_free_rate: The return of a risk-free investment (e.g., government bonds).</li></ul><p><strong>negative_sharpe_ratio</strong>: This function calculates the negative Sharpe ratio, as minimize works by minimizing the objective function.</p><pre>def negative_sharpe_ratio(weights, mean_returns, cov_matrix, risk_free_rate):<br>    p_return, p_volatility = portfolio_performance(weights, mean_returns, cov_matrix)<br>    sharpe_ratio = (p_return - risk_free_rate) / p_volatility<br>    return -sharpe_ratio</pre><p>By minimizing the negative Sharpe ratio, we effectively maximize the positive Sharpe ratio.</p><p>The result includes the optimal weights for the portfolio, along with other details like the minimized value of the objective function.</p><h3>Full implementation</h3><p>Now we can create the full implementation of Modern Portfolio Theory. Below we use yahoo finance api to get stock data from 2020 to 2023 and create the efficient frontier and optimized portfolio and plot them using matplotlib.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from scipy.optimize import minimize<br>import yfinance as yf<br><br># 1. Download Historical Data from Yahoo Finance<br>def get_stock_data(tickers, start_date, end_date):<br>    &quot;&quot;&quot;<br>    Fetches adjusted close prices for a list of tickers from Yahoo Finance.<br>    &quot;&quot;&quot;<br>    data = yf.download(tickers, start=start_date, end=end_date)[&quot;Close&quot;]<br>    return data<br><br># 2. Calculate Daily Returns<br>def calculate_daily_returns(data):<br>    &quot;&quot;&quot;<br>    Calculates daily returns from price data.<br>    &quot;&quot;&quot;<br>    returns = data.pct_change().dropna()<br>    return returns<br><br># 3. Portfolio Performance Calculation<br>def portfolio_performance(weights, mean_returns, cov_matrix):<br>    &quot;&quot;&quot;<br>    Calculate portfolio performance (return and volatility) based on weights.<br>    &quot;&quot;&quot;<br>    portfolio_return = np.dot(weights, mean_returns)<br>    portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))<br>    return portfolio_return, portfolio_volatility<br><br># 4. Optimization Functions<br>def negative_sharpe_ratio(weights, mean_returns, cov_matrix, risk_free_rate):<br>    &quot;&quot;&quot;<br>    Minimize the negative Sharpe ratio.<br>    &quot;&quot;&quot;<br>    p_return, p_volatility = portfolio_performance(weights, mean_returns, cov_matrix)<br>    sharpe_ratio = (p_return - risk_free_rate) / p_volatility<br>    return -sharpe_ratio<br><br>def optimize_portfolio(mean_returns, cov_matrix, risk_free_rate):<br>    &quot;&quot;&quot;<br>    Optimize portfolio to maximize Sharpe ratio.<br>    &quot;&quot;&quot;<br>    num_assets = len(mean_returns)<br>    args = (mean_returns, cov_matrix, risk_free_rate)<br>    constraints = {&quot;type&quot;: &quot;eq&quot;, &quot;fun&quot;: lambda x: np.sum(x) - 1}  # Sum of weights = 1<br>    bounds = tuple((0, 1) for _ in range(num_assets))  # No short selling<br><br>    result = minimize(<br>        negative_sharpe_ratio,<br>        num_assets * [1.0 / num_assets],  # Initial weights<br>        args=args,<br>        method=&quot;SLSQP&quot;,<br>        bounds=bounds,<br>        constraints=constraints<br>    )<br>    return result<br><br># 5. Efficient Frontier<br>def calculate_efficient_frontier(mean_returns, cov_matrix, num_points=100):<br>    &quot;&quot;&quot;<br>    Generate portfolios for the efficient frontier.<br>    &quot;&quot;&quot;<br>    results = {&quot;returns&quot;: [], &quot;volatility&quot;: [], &quot;weights&quot;: []}<br>    for target_return in np.linspace(mean_returns.min(), mean_returns.max(), num_points):<br>        constraints = [<br>            {&quot;type&quot;: &quot;eq&quot;, &quot;fun&quot;: lambda x: portfolio_performance(x, mean_returns, cov_matrix)[0] - target_return},<br>            {&quot;type&quot;: &quot;eq&quot;, &quot;fun&quot;: lambda x: np.sum(x) - 1},<br>        ]<br>        bounds = tuple((0, 1) for _ in range(len(mean_returns)))<br><br>        result = minimize(<br>            lambda x: portfolio_performance(x, mean_returns, cov_matrix)[1],<br>            len(mean_returns) * [1.0 / len(mean_returns)],<br>            method=&quot;SLSQP&quot;,<br>            bounds=bounds,<br>            constraints=constraints,<br>        )<br>        if result.success:<br>            results[&quot;returns&quot;].append(target_return)<br>            results[&quot;volatility&quot;].append(result.fun)<br>            results[&quot;weights&quot;].append(result.x)<br>    return results<br><br># Main Function<br>if __name__ == &quot;__main__&quot;:<br>    # Specify stock tickers and date range<br>    tickers = [&quot;AAPL&quot;, &quot;MSFT&quot;, &quot;GOOGL&quot;, &quot;AMZN&quot;, &quot;TSLA&quot;]<br>    start_date = &quot;2020-01-01&quot;<br>    end_date = &quot;2023-12-31&quot;<br><br>    # Fetch data and calculate daily returns<br>    price_data = get_stock_data(tickers, start_date, end_date)<br>    returns = calculate_daily_returns(price_data)<br><br>    # Calculate statistics<br>    mean_returns = returns.mean()<br>    cov_matrix = returns.cov()<br>    risk_free_rate = 0.02 / 252  # Annualized risk-free rate converted to daily<br><br>    # Optimize Portfolio<br>    optimized_portfolio = optimize_portfolio(mean_returns, cov_matrix, risk_free_rate)<br><br>    # Calculate Efficient Frontier<br>    efficient_frontier = calculate_efficient_frontier(mean_returns, cov_matrix)<br><br>    # Extract Optimized Portfolio Results<br>    optimal_weights = optimized_portfolio.x<br>    optimal_return, optimal_volatility = portfolio_performance(optimal_weights, mean_returns, cov_matrix)<br>    optimal_sharpe_ratio = (optimal_return - risk_free_rate) / optimal_volatility<br><br>    # Visualization<br>    plt.figure(figsize=(10, 7))<br>    # Efficient Frontier<br>    plt.plot(<br>        efficient_frontier[&quot;volatility&quot;],<br>        efficient_frontier[&quot;returns&quot;],<br>        label=&quot;Efficient Frontier&quot;,<br>        linestyle=&quot;--&quot;,<br>        color=&quot;green&quot;<br>    )<br>    # Simulated Portfolios<br>    plt.scatter(<br>        np.sqrt(np.diag(cov_matrix)),<br>        mean_returns,<br>        color=&quot;blue&quot;,<br>        label=&quot;Individual Assets&quot;,<br>        s=50<br>    )<br>    # Optimal Portfolio<br>    plt.scatter(<br>        optimal_volatility,<br>        optimal_return,<br>        color=&quot;red&quot;,<br>        label=f&quot;Optimal Portfolio\nSharpe Ratio: {optimal_sharpe_ratio:.2f}&quot;,<br>        s=100<br>    )<br><br>    plt.title(&quot;Efficient Frontier and Optimal Portfolio&quot;)<br>    plt.xlabel(&quot;Volatility (Risk)&quot;)<br>    plt.ylabel(&quot;Return&quot;)<br>    plt.legend()<br>    plt.grid()<br>    plt.show()<br><br>    # Display Results<br>    print(&quot;Optimal Portfolio Weights:&quot;)<br>    for asset, weight in zip(tickers, optimal_weights):<br>        print(f&quot;{asset}: {weight:.2%}&quot;)<br>    print(f&quot;Expected Return: {optimal_return:.2%}&quot;)<br>    print(f&quot;Volatility: {optimal_volatility:.2%}&quot;)<br>    print(f&quot;Sharpe Ratio: {optimal_sharpe_ratio:.2f}&quot;)</pre><h3>Results</h3><p>Terminal Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*sp3qahFsXFj4kFMkwISfnQ.png" /></figure><p>Matplotlib Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpOlV52pnmj79924qpKJaQ.png" /></figure><h3>Conclusion</h3><p>We covered what modern portfolio theory is, explained the main concepts behind modern portfolio theory is and how to implement all of it in Python and run it on real world stock data.</p><h4>A Message from InsiderFinance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*10x5_2smmKq8oIlf.png" /></figure><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a></li><li>📚 Take our <a href="https://learn.insiderfinance.io/p/mastering-the-flow">FREE Masterclass</a></li><li><strong>📈 Discover </strong><a href="https://insiderfinance.io/?utm_source=wire&amp;utm_medium=message"><strong>Powerful Trading Tools</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df3e10b911ba" width="1" height="1" alt=""><hr><p><a href="https://wire.insiderfinance.io/python-for-finance-implementing-modern-portfolio-theory-df3e10b911ba">Python for Finance: Implementing Modern Portfolio Theory</a> was originally published in <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deepseek: A Sputnik moment or a MiG-25 moment]]></title>
            <link>https://medium.com/@saksham.solanki/deepseek-a-sputnik-moment-or-a-mig-25-moment-40512c867e91?source=rss-f3bc24a20519------2</link>
            <guid isPermaLink="false">https://medium.com/p/40512c867e91</guid>
            <category><![CDATA[usa]]></category>
            <category><![CDATA[geopolitics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[china]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Saksham Solanki]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 17:30:49 GMT</pubDate>
            <atom:updated>2025-01-27T17:30:49.047Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*C2j2MEJU1BmLo7o5hM1ctw.jpeg" /></figure><p>Deepseek-R1 is the newest model released by a Chinese quant firm which is beating all other models by any AI Lab and is completely open source. However, the biggest talking point isn’t the performance against other SOTA models but the drastically lower training cost that the company is claiming it took to train this model. The company claims it only took about 5 million dollars to train their model which is a fraction of what other companies like OpenAI spend to train their models. The results of the model are also impressive given the low amount of computing they had to work with because of the export controls of GPUs to China.</p><p>The release of this model has sparked a lot of controversies and debates around Artificial Intelligence, its role in geopolitics, and a race between the US and China for AI dominance. Many have compared the release of this model with the Sputnik moment. On October 4, 1957, the Soviet Union successfully launched Sputnik 1, the world’s first artificial satellite. The launch of Sputnik marked the beginning of the Space Race, where both nations in an attempt to show their superiority tried to outcompete each other. The Soviets followed Sputnik 1 with further successes, including the launch of Sputnik 2 with the first living creature in space, Laika, and Yuri Gagarin’s orbital flight in 1961, making him the first human in space. The Space Race culminated in the US landing Apollo 11 on the Moon in July 1969, a demonstration of technological and political power. The space race accelerated technological advancements in many fields and had lasting impacts on both geopolitics and global science and technologies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F7DQRivZbYtpmx6E" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=medium&amp;utm_medium=referral">NASA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Like the space race, the release of Deepseek might mark the beginning of a new AI race where the US is now competing with China this time in the realm of AI. But is the release of Deepseek truly a Sputnik moment or something else</p><p>Another event in the Cold War that spooked the US was the introduction of the MiG-25 Foxbat by the Soviets. It was the most advanced fighter aircraft of its time breaking many speed and altitude records. The US at that time had no aircraft that was equipped to deal with the soviet MiG-25. It also caused panic as the MiG-25 could threaten the air superiority of the US. In response to this, the US started the development of advanced fighter jets like the F-15 Eagle, designed specifically to counter the MiG-25. Like the Sputnik moment spurred investments in science and technology, the MiG-25 led to advancements in military aviation and radar systems in the US. The mystique and allure of the MiG-25 remained for a long time partly due to its superior capabilities and partly due to the propaganda of the soviet union.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*eEszIJVLQPxlzkxUZNUT-Q.jpeg" /></figure><p>The MiG-25’s mystique diminished after a Soviet pilot, Viktor Belenko, defected by flying his MiG-25 to Japan. This gave the Americans a chance to examine the MiG-25. Their analysis revealed it was optimized for specific roles (high speed, high altitude), with trade-offs in maneuverability and versatility. It was not the game-changing aircraft it initially appeared to be.</p><p>Deepseek is causing shock and panic, just like the initial shock and panic caused by both Sputnik and the MiG-25, and raising questions about the future of AI and who will dominate. If the claims of the training cost are true then it represents a new paradigm shift in how models are trained shattering the myth that you need a huge budget to train a new SOTA model to compete with, making training new models accessible to a lot more people and increasing competition. On the other hand, it could be that the company behind Deepseek is not revealing the actual cost to train the model and may be underinflating the cost of training their model. This can be because they don’t want to reveal how many GPUs they have or be seen circumventing export controls to train their models. Like the MiG-25 we will only be able to know after close examination whether it is truly a breakthrough innovation that will change the AI landscape or that its capabilities, while impressive, might be overblown.</p><p>It remains to be seen whether this will play as a Sputnik moment or a MiG-25 moment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40512c867e91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Finance: Risk adjusted returns]]></title>
            <link>https://wire.insiderfinance.io/python-for-finance-risk-adjusted-returns-92af4789321d?source=rss-f3bc24a20519------2</link>
            <guid isPermaLink="false">https://medium.com/p/92af4789321d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[quant]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[market]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[Saksham Solanki]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 19:38:55 GMT</pubDate>
            <atom:updated>2024-12-26T19:38:55.702Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous post we learned basics of returns, how to download real world stock data and calculating its daily and annual returns. In this post we will continue and learn about average returns, risk and risk measures like standard deviation, sharpe ratios and how to calculate those in Python</p><p><a href="https://wire.insiderfinance.io/python-for-finance-basics-of-returns-869393f9d8eb">Python for Finance: Basics of Returns</a></p><h4>Mean (Average) Returns</h4><p>The mean of an asset is simply the average return of the asset for a given time period. It is a baseline for what an Investor might expect investing into that asset.</p><p>For example, if a stock’s average return is 8%, you would expect, on average, an 8% gain over the period analyzed. However, the mean alone does not capture the <strong>variability</strong> or <strong>volatility</strong> of those returns. The actual returns can fluctuate significantly around the mean, which is why measures like <strong>standard deviation</strong> are essential to understand the <strong>risk</strong> associated with the asset.</p><p>In python we can simply calculate the mean using the .mean() function a pandas dataframe.</p><pre># Calculate mean (average) returns<br>mean_returns = daily_returns.mean()</pre><h3>Risk</h3><p>Investing always entails taking some degree of risks, the risk of stock prices falling, the risk that a borrower (such as a bond issuer) will default on their obligations and fail to pay interest or principal, the risk that an investor may not be able to sell an investment quickly enough or at a fair price due to a lack of buyers. These are just a few examples of the risks an investor might need to keep in mind while investing. Different assets may come with one or more types of risks each added risk increasing the required rate of return demanding by the investor. These types of risks are:</p><ul><li><strong>Default Risk: </strong>The risk that the borrower will not make the promised payments.</li><li><strong>Liquidity Risk: </strong>The risk of receiving less than the fair market price for the asset when it is sold quickly</li><li><strong>Maturity Risk: </strong>This risk is mostly associated with the time horizon of a debt instrument, such as a bond, due to changes in interest rates and other market conditions over its term bonds can fluctuate in price.</li></ul><p>Next we will look at ways we can quantify and calculate risk.</p><h4>Standard Deviation (Volatility)</h4><p>It measures how far the returns are distributed to its mean. Higher standard deviation indicates higher risk, as prices fluctuate more and also returns fluctuate more.</p><p>The formula for calculating standard deviation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*yyknJH3ASnTV0t3GIt8uNg.png" /></figure><p>Where:</p><ul><li>σ is the standard deviation.</li><li>N is the number of data points.</li><li>x_i represents each data point.</li><li>μ is the mean (average) of the data points.</li></ul><p>In python we can simply use the .std() function on a dataframe to calculate the volatility</p><pre># Calculate standard deviation (volatility)<br>std_deviation = daily_returns.std()</pre><p>Two assets can have the same mean, but can have different Standard Deviations.</p><p>An example to demonstrate this, I generate two synthetic time series data for two assets. Both assets have the same mean return but different standard deviations (volatility). The code will plot both time series to highlight the impact of higher volatility.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Set the random seed for reproducibility<br>np.random.seed(42)<br><br># Generate synthetic data<br>dates = pd.date_range(start=&quot;2023-01-01&quot;, end=&quot;2023-12-31&quot;, freq=&quot;D&quot;)<br>n = len(dates)<br><br># Asset 1: Low volatility, same mean return<br>mean_return = 0.0005  # 0.05% daily return<br>std_dev_low = 0.01  # 1% daily volatility<br>returns_asset1 = np.random.normal(mean_return, std_dev_low, n)<br><br># Asset 2: High volatility, same mean return<br>std_dev_high = 0.03  # 3% daily volatility<br>returns_asset2 = np.random.normal(mean_return, std_dev_high, n)<br><br># Create a DataFrame for the two assets<br>data = pd.DataFrame({<br>    &quot;Asset 1 (Low Volatility)&quot;: returns_asset1,<br>    &quot;Asset 2 (High Volatility)&quot;: returns_asset2<br>}, index=dates)<br><br># Calculate the cumulative returns for both assets<br>cumulative_returns = (1 + data).cumprod()<br><br># Plot the cumulative returns<br>plt.figure(figsize=(12, 6))<br>plt.plot(cumulative_returns, label=[&quot;Asset 1 (Low Volatility)&quot;, &quot;Asset 2 (High Volatility)&quot;])<br>plt.title(&quot;Cumulative Returns: Same Mean, Different Volatility&quot;)<br>plt.xlabel(&quot;Date&quot;)<br>plt.ylabel(&quot;Cumulative Return&quot;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><h4>Output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*FARkKW_g0i1T3VRhQ_CJBQ.png" /></figure><p>Both assets have the same mean return but different volatility. Even with the same mean return, the higher volatility in Asset 2 creates a much bumpier growth trajectory. In practice, investors might prefer the smoother path (Asset 1) if they are risk-averse, even if the mean returns are identical.</p><h3>Sharpe Ratio</h3><p>While mean returns and volatility (standard deviation) give investors a sense of the average performance and risk of an asset, they don’t fully capture whether the risk taken is justified by the returns. This is where the <strong>Sharpe Ratio</strong> becomes crucial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*mNv0thdcBvUHKnjR1yRSqg.png" /></figure><p>The <strong>Sharpe ratio</strong> is essentially a measure of the <strong>excess return per unit of risk</strong> that an investor is taking for an asset. The Sharpe ratio tells you how much extra return you’re earning for each additional unit of risk you’re taking on.</p><p>A higher Sharpe ratio means you’re getting more return for the risk you’re exposed to, making the investment more attractive from a risk-adjusted perspective.</p><p>Taking an example, suppose we have two Stocks A and B with mean returns of 10% and 8% and the risk free rate is at 2%. Stock A has a standard deviation of 15% and Stock B has a standard deviation of 5%.</p><p>Looking at the mean returns we can clearly see that stock A has a higher return of 10%, but calculating their Sharpe ratios we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*2v0FqyXuNg4m8Ye0o0sIBA.png" /></figure><p>Even though Stock A has a higher return (10%), Stock B has a much better Sharpe ratio (1.2 vs. 0.53), meaning that it offers a much better <strong>risk-adjusted return</strong>. Stock B gives you more return for each unit of risk.</p><pre>import pandas as pd<br>import numpy as np<br><br># Assuming you have daily returns for two assets in a DataFrame<br># Replace this with your actual returns data<br>np.random.seed(42)<br>dates = pd.date_range(start=&quot;2023-01-01&quot;, end=&quot;2023-12-31&quot;, freq=&quot;D&quot;)<br>n = len(dates)<br><br># Asset 1: Low volatility<br>mean_return_1 = 0.0005<br>std_dev_low = 0.01<br>returns_asset1 = np.random.normal(mean_return_1, std_dev_low, n)<br><br># Asset 2: High volatility<br>mean_return_2 = 0.0005<br>std_dev_high = 0.03<br>returns_asset2 = np.random.normal(mean_return_2, std_dev_high, n)<br><br># Create a DataFrame of returns<br>returns_data = pd.DataFrame({<br>    &quot;Asset 1 (Low Volatility)&quot;: returns_asset1,<br>    &quot;Asset 2 (High Volatility)&quot;: returns_asset2<br>}, index=dates)<br><br># Define the risk-free rate (e.g., 2% annualized, which translates to daily ~0.00008)<br>risk_free_rate = 0.00008<br><br># Calculate the mean return and standard deviation for each asset<br>mean_returns = returns_data.mean()<br>std_devs = returns_data.std()<br><br># Calculate the Sharpe Ratio for each asset<br>sharpe_ratios = (mean_returns - risk_free_rate) / std_devs<br><br># Output the Sharpe Ratios<br>print(&quot;Mean Returns:\n&quot;, mean_returns)<br>print(&quot;\nStandard Deviations (Volatility):\n&quot;, std_devs)<br>print(&quot;\nSharpe Ratios:\n&quot;, sharpe_ratios)</pre><h3>Conclusion</h3><p>Congratulations! You have now learned what risk is, explored different measures of risk such as standard deviation and Sharpe ratios, and discovered how to calculate these risk metrics using Python on real-world stock data.</p><h4>A Message from InsiderFinance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*10x5_2smmKq8oIlf.png" /></figure><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a></li><li>📚 Take our <a href="https://learn.insiderfinance.io/p/mastering-the-flow">FREE Masterclass</a></li><li><strong>📈 Discover </strong><a href="https://insiderfinance.io/?utm_source=wire&amp;utm_medium=message"><strong>Powerful Trading Tools</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92af4789321d" width="1" height="1" alt=""><hr><p><a href="https://wire.insiderfinance.io/python-for-finance-risk-adjusted-returns-92af4789321d">Python for Finance: Risk adjusted returns</a> was originally published in <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Finance: Basics of Returns]]></title>
            <link>https://wire.insiderfinance.io/python-for-finance-basics-of-returns-869393f9d8eb?source=rss-f3bc24a20519------2</link>
            <guid isPermaLink="false">https://medium.com/p/869393f9d8eb</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Saksham Solanki]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 20:50:44 GMT</pubDate>
            <atom:updated>2024-08-19T13:26:51.277Z</atom:updated>
            <content:encoded><![CDATA[<p>Returns are what investors are looking for when investing in an asset. It is simply the percentage of gain or loss on the amount of money invested in the asset. Returns can be calculated for any time periods e.g return over 1 day, 1 week, 1 month or 1 year.</p><p>The Return over any period can be easily calculated as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*Ep_AtZZJLxAvMlyuCQb3nQ.png" /></figure><p>Or,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*m3N3pC-P7viXYVZqocsTOA.png" /></figure><p>Where Pₜ, Pₜ ₊ ₁ is price of an asset at a time t and time t + 1 and Rₜ,ₜ ₊ ₁ is the return for the time period t and t + 1</p><p>An example, if you bought a share for $10 and sold it for $12 you would have made a 20% profit. 12/10–1 = 0.2 or 20%.</p><p>Now, if you had returns for time period t to t + 1 and t + 1 to t + 2 the return over the combined time period that is from t to t + 2 is simply</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*QhCmvsFwY5LGtHmAOLqDQw.png" /></figure><p>This is called <strong>multi period returns</strong>.</p><p>An Example of this is suppose you bought a stock and the first day it went up by 10% and the next day it went down by 3%, the total return would be</p><p>(1 + 0.1)(1–0.03)-1 = 0.067 = 6.7%</p><h3>Annualized Returns</h3><p>If you want to compare returns of different assets with different time frames you can convert the returns into annualized returns. Annualized Returns is the average annual return an investment generated. It provides us a standardized way to compare assets with returns over different time spans.</p><p>For example an asset returns 1% every month. The annual return of this asset would be</p><p>(1 + 0.01)¹² - 1 = 0.1268 = 12.68%</p><p>or another example would be,</p><p>If you invested $10,000 and after 3 years the investment grew to $15,000, the annualized return would be:</p><p>(15000 / 10000)¹/³ — 1 = 0.145 = 14.5%</p><h3>Calculating Returns in Python</h3><p>To calculate returns we need to have a list of prices of an asset</p><pre># List of daily prices of an asset<br>prices = [15, 15.9, 16.536, 16.04, 16.2]<br><br># We can calculate daily prices we take prices from the current day and<br># divide by the previous day prices and subtract 1. <br># 15.9 / 15 - 1 = 0.06 or 6%</pre><p>We can write a simple function that takes in the list of prices and returns a list for the daily returns of the asset.</p><pre>def cal_pct_change(prices):<br>    # Initialize an empty list to store the percentage changes<br>    pct_change = []<br><br>    # Shift the prices list by one position to align current and previous prices<br>    prices_shifted = prices[1:]  # This contains all prices except the first one<br>    previous_prices = prices[:-1]  # This contains all prices except the last one<br><br>    # Calculate percentage change for each period<br>    for i in range(len(prices_shifted)):<br>        pct_change.append(prices_shifted[i] / previous_prices[i] - 1)<br><br>    return pct_change<br><br># Running this function on our prices list<br>cal_pct_change(prices)<br><br># Output<br># [0.06000000000000005,0.040000000000000036, -0.029995162070633907,0.009975062344139696]</pre><p>And to calculate the compounded return over the whole period we use the multi period return formula and multiply all the daily returns to get the compounded return over the time period</p><pre>def compounded_rate(daily_returns):<br>    # Initialize compounded_return to 1, as it acts as the base for multiplication<br>    compounded_return = 1<br><br>    # Loop through each daily return and apply compounding<br>    for i in range(len(daily_returns)):<br>        compounded_return *= (1 + daily_returns[i])<br><br>    # Subtract 1 at the end to get the overall compounded return<br>    return compounded_return - 1<br><br># Example usage:<br>daily_returns = cal_pct_change(prices) # Gives us list of daily return from list of prices<br>compounded_rate(daily_returns)<br><br># Output:<br># 0.08000000000000007</pre><p>Or alternatively, if we know the prices at the start and end of the period we can simply get the return by</p><p>16.2 / 15 - 1 = 0.08 or 8%</p><h3>Using Pandas</h3><p>Till now we have used regular python to do our calculation but real financial data often involves thousands of rows (e.g., daily prices over several years). Python would be very slow if we wanted to work with actual financial data, so we instead use pandas. Pandas is a python package that can efficiently handle large datasets and perform analysis on them. Financial calculations like percentage change or cumulative product are very common in data analysis. <strong>Pandas</strong> already has these functions built-in, so you don’t need to manually write the logic for them.</p><h4>Installing Pandas and other libraries</h4><p>To use pandas we first install it, we install it using package manager of python pip. Along with python we will download 2 more packages matplotlib, a package that we can use to plot data and yfinacne, a package that lets us download stock market data from yahoo finance.</p><p>Copy this command in your terminal</p><pre>$ pip install pandas yfinance matplotlib </pre><p>After you have installed the packages you can import them on top of your program as</p><pre>import pandas as pd<br>import matplotliib.pyplot as plt<br>import yfinance as yf</pre><p>Now we can use these packages in our program. We can now use a dataframe for prices instead of using a regular python list.</p><h4>Implementing the Percentage Change in Prices using Pandas</h4><pre># Example price data<br>prices = pd.Series([100, 105, 102, 110, 115])<br><br># Calculate percentage change using pandas<br>pct_change = prices.pct_change()<br><br>print(pct_change)</pre><p>This will return a dataframe with all the daily percent changes. The .pct_change() method in pandas directly computes the percentage change between each consecutive element in the series. The first element in the dataframe will be a Nan or not a number since we cannot compute the percent change as we do not have the previous days price.</p><h4>Implementing Compounded Rate of Return using Pandas</h4><pre># Example daily returns data<br>daily_returns = pd.Series([0.01, -0.005, 0.002, 0.004])<br><br># Calculate compounded rate of return<br>compounded_return = (1 + daily_returns).cumprod().iloc[-1] - 1<br><br>print(compounded_return)</pre><ul><li>(1 + daily_returns).cumprod() calculates the cumulative product to get the compounded return over time.</li><li>.iloc[-1] retrieves the last value, which represents the final compounded result. Subtracting 1 gives the overall compounded return.</li></ul><h4>Pandas Code to Calculate Annualized Returns</h4><pre># Example daily returns data<br>daily_returns = pd.Series([0.001, -0.002, 0.003, 0.0015, -0.0005])<br><br># Calculate the compounded return<br>compounded_return = (1 + daily_returns).cumprod().iloc[-1]<br><br># Number of periods (in this example, assume we have daily returns)<br>total_periods = len(daily_returns)<br><br># Assume 252 trading days in a year<br>periods_per_year = 252<br><br># Calculate annualized return<br>annualized_return = compounded_return ** (periods_per_year / total_periods) - 1<br><br>print(f&quot;Annualized Return: {annualized_return:.2%}&quot;)</pre><p>In daily data, the number of periods in a year is typically 252 trading days (for stock markets).</p><h3>Downloading Real Stock Data</h3><p>Now that we know how to calculate returns, we will now use real stock data and calculate their daily and annualized returns. We will also plot the results using matplotlib.</p><p>We use yfinance to download historical data for both stocks. The data is accessed using the [&#39;Adj Close&#39;] column.</p><pre># Download historical stock data for Apple (AAPL) and Microsoft (MSFT)<br>stocks = [&quot;AAPL&quot;, &quot;MSFT&quot;]<br>stock_data = yf.download(stocks, start=&quot;2023-01-01&quot;, end=&quot;2024-01-01&quot;)<br>stock_data = stock_data[&#39;Adj Close&#39;]</pre><p>This downloads the stock prices for Apple and Microsoft from 2023 to 2024</p><h4>Calculate returns for both stocks</h4><pre># 1. Calculate percentage change in prices for both stocks<br>pct_change = stock_data.pct_change()<br><br># 2. Calculate the compounded rate of return for both stocks<br>compounded_return = (1 + pct_change).cumprod() - 1<br><br># 3. Calculate the annualized return for both stocks<br>total_periods = len(pct_change.dropna())<br>periods_per_year = 252  # Trading days in a year<br>annualized_return = (1 + compounded_return.iloc[-1]) ** (periods_per_year / total_periods) - 1<br><br># Print annualized returns<br>print(&quot;\nAnnualized Returns:&quot;)<br>for stock in stocks:<br>    print(f&quot;{stock}: {annualized_return[stock]:.2%}&quot;)<br><br># Output<br># Annualized Returns:<br># AAPL: 55.62%<br># MSFT: 59.23%# Plotting the percentage change and compounded returns</pre><h4>Plotting the Results</h4><p>Using matplotlib we can visualise the daily returns and compounded returns on both the stocks.</p><pre># Plotting the percentage change and compounded returns<br>plt.figure(figsize=(14, 8))<br><br># Subplot 1: Percentage Change<br>plt.subplot(2, 1, 1)<br>plt.plot(pct_change, label=stocks)<br>plt.title(&quot;Daily Percentage Change in Prices&quot;)<br>plt.ylabel(&quot;Percentage Change&quot;)<br>plt.legend(stocks)<br><br># Subplot 2: Compounded Returns<br>plt.subplot(2, 1, 2)<br>plt.plot(compounded_return, label=stocks)<br>plt.title(&quot;Compounded Returns Over Time&quot;)<br>plt.ylabel(&quot;Compounded Return&quot;)<br>plt.legend(stocks)<br><br># Show the plots<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gxwa4qoNd4fpJpx6Kf5w8Q.png" /></figure><h4>Full code</h4><pre>import yfinance as yf<br>import pandas as pd<br>import matplotlib.pyplot as plt<br><br># Download historical stock data for Apple (AAPL) and Microsoft (MSFT)<br>stocks = [&quot;AAPL&quot;, &quot;MSFT&quot;]<br>stock_data = yf.download(stocks, start=&quot;2023-01-01&quot;, end=&quot;2024-01-01&quot;)[&#39;Adj Close&#39;]<br><br># 1. Calculate percentage change in prices for both stocks<br>pct_change = stock_data.pct_change()<br><br># 2. Calculate the compounded rate of return for both stocks<br>compounded_return = (1 + pct_change).cumprod() - 1<br><br># 3. Calculate the annualized return for both stocks<br>total_periods = len(pct_change.dropna())<br>periods_per_year = 252  # Trading days in a year<br>annualized_return = (1 + compounded_return.iloc[-1]) ** (periods_per_year / total_periods) - 1<br><br># Print annualized returns<br>print(&quot;\nAnnualized Returns:&quot;)<br>for stock in stocks:<br>    print(f&quot;{stock}: {annualized_return[stock]:.2%}&quot;)<br><br># Plotting the percentage change and compounded returns<br>plt.figure(figsize=(14, 8))<br><br># Subplot 1: Percentage Change<br>plt.subplot(2, 1, 1)<br>plt.plot(pct_change, label=stocks)<br>plt.title(&quot;Daily Percentage Change in Prices&quot;)<br>plt.ylabel(&quot;Percentage Change&quot;)<br>plt.legend(stocks)<br><br># Subplot 2: Compounded Returns<br>plt.subplot(2, 1, 2)<br>plt.plot(compounded_return, label=stocks)<br>plt.title(&quot;Compounded Returns Over Time&quot;)<br>plt.ylabel(&quot;Compounded Return&quot;)<br>plt.legend(stocks)<br><br># Show the plots<br>plt.tight_layout()<br>plt.show()</pre><h3>Conclusion</h3><p>Congratulations, you have now learned the basics of returns of assets, how to calculate daily returns and annualized returns in Python and how to download real world stock data to calculate and visualise their returns.</p><h4>A Message from InsiderFinance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*10x5_2smmKq8oIlf.png" /></figure><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a></li><li>📚 Take our <a href="https://learn.insiderfinance.io/p/mastering-the-flow">FREE Masterclass</a></li><li><strong>📈 Discover </strong><a href="https://insiderfinance.io/?utm_source=wire&amp;utm_medium=message"><strong>Powerful Trading Tools</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=869393f9d8eb" width="1" height="1" alt=""><hr><p><a href="https://wire.insiderfinance.io/python-for-finance-basics-of-returns-869393f9d8eb">Python for Finance: Basics of Returns</a> was originally published in <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What makes Bitcoin different from other cryptocurrencies]]></title>
            <link>https://medium.com/coinmonks/what-makes-bitcoin-different-from-other-cryptocurrencies-5e0b58e9b7ae?source=rss-f3bc24a20519------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e0b58e9b7ae</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Saksham Solanki]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 15:40:12 GMT</pubDate>
            <atom:updated>2024-08-05T15:40:12.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZQksjh8LIewxcGLQ" /><figcaption>Photo by <a href="https://unsplash.com/@traxer?utm_source=medium&amp;utm_medium=referral">Traxer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Bitcoin was the first cryptocurrency to be created, solving the long-unsolved problem of digital money. Before Bitcoin, any online transaction required the use of an intermediary like PayPal or a bank. These intermediaries could block transactions, reverse payments, and generally control the flow of money. With Bitcoin, true digital money emerged, allowing users to transact without restrictions, control their private keys, and spend their Bitcoin without fear of confiscation or censorship. Bitcoin introduced the first true permissionless and decentralized currency.</p><p>Bitcoin’s creation in 2009 by the pseudonymous Satoshi Nakamoto was a revolutionary moment in the history of finance and technology. At its core, Bitcoin operates on a decentralized ledger known as the blockchain, which ensures transparency and security without the need for a central authority. This breakthrough has profound implications for financial sovereignty and privacy, challenging traditional banking systems and offering a new paradigm for value transfer.</p><p>Today, there are thousands of cryptocurrencies, many claiming to be better than Bitcoin, offering features like faster transaction speeds or increased programmability. However, many of these are simply pump-and-dump schemes designed to defraud investors. Despite the influx of these new cryptocurrencies, Bitcoin remains at the top. Why is this? Is it merely because of its first-mover advantage, or is there something else that has kept Bitcoin in the number-one spot for over 16 years?</p><p>After Bitcoin, many other cryptocurrencies emerged, commonly known as altcoins. These altcoins were created for various reasons. Some developers identified features they believed were lacking in Bitcoin or perceived flaws in its design, leading them to make their cryptocurrencies address these issues. Others simply created altcoins as a joke or a meme like dogecoin.</p><p>To understand what makes Bitcoin remains the most dominant cryptocurrency in the market, we need to understand the features that make it unique among all other cryptocurrencies. Let’s explore these unique elements to understand why Bitcoin remains the undisputed leader in the cryptocurrency market.</p><h4>Bitcoin does not have a leader</h4><p>One of the most distinguishing features of Bitcoin is that it does not have a leader. There is no single person who can be identified as the leader of Bitcoin. While there are core developers who contribute to the Bitcoin Core software, they do not hold sway over the network itself. Users are not compelled to run any particular code, and there are multiple Bitcoin clients to choose from.</p><p>Historically, Bitcoin has had influential figures such as Satoshi Nakamoto, the pseudonymous creator, and early developers like Gavin Andresen and Roger Ver. However, none of these individuals or any other person or company currently significantly influence Bitcoin’s development or network operations.</p><p>In contrast, many other cryptocurrencies have central figures or entities with considerable control over their blockchain. A prominent example is the Ethereum DAO hack, where a buggy smart contract led to a loss of over $100 million. Ethereum’s creator, Vitalik Buterin, chose to reverse the blockchain to restore the lost funds, demonstrating his significant influence over the network.</p><p>Bitcoin does not have any influential developer or company that can forcefully change the code, or disrupt network operations.</p><h4>Bitcoin is decentralized</h4><p>Bitcoin is genuinely decentralized, unlike many altcoins. Anyone can run Bitcoin Core and verify that the network is enforcing all the rules and ensuring all transactions are correct and in consensus. Bitcoin core and other implementations can be easily run on laptops, or commodity hardware. This can be done without specialized hardware or reliance on any third party. Bitcoin nodes are the backbone of this decentralization, allowing anyone to participate in the network and verify its operations independently.</p><p>Bitcoin’s decentralization makes it highly resilient to attacks and failures. With no single point of control or failure, the network can withstand attempts at censorship, shutdowns, and regulatory pressures. The distribution of nodes and miners around the world ensures that the network remains operational</p><h4>Supply</h4><p>Bitcoin has a fixed supply cap of 21 million coins that will ever be issued, a feature embedded in its protocol since its inception. New coins are introduced through block rewards, which miners receive for adding new blocks to the blockchain. This process follows a predictable, predefined schedule, known as the halving cycle, where the reward for mining new blocks is halved approximately every four years.</p><p>Users can independently verify the number of coins in existence at any time using their nodes. This transparency ensures trust and reliability, as anyone can audit the Bitcoin network to confirm that the rules are being followed and that the supply cap is adhered to.</p><p>In contrast, other cryptocurrencies often do not have a stable monetary policy like Bitcoin. For example, Ethereum does not have a fixed supply cap. The issuance schedule for the new Ether has changed multiple times since its creation. Initially, Ethereum had an infinite supply, with a yearly issuance of 18 million Ether. This policy was adjusted with the introduction of Ethereum Improvement Proposals (EIPs) such as EIP-1559, which implemented a fee-burning mechanism to reduce the effective issuance rate. However, the lack of a hard cap and the ability to change the issuance schedule introduces uncertainty regarding Ethereum’s monetary policy.</p><h4>Proof of Work Security</h4><p>Bitcoin is the most secure cryptocurrency thanks to its proof-of-work mining system. The Bitcoin blockchain is the most mined cryptocurrency with most amount of miners trying to mine and secure the Bitcoin network. All of these miners ensure that the network is secure and no one can go and change the blockchain once it has been updated to carry out a double spend attack. The extensive network of miners adds a layer of robustness to the network.</p><h4>Conclusion</h4><p>Bitcoin’s unique characteristics — leaderless operation, true decentralization, fixed supply, established history, and consistent rules — set it apart from other cryptocurrencies. Bitcoin’s position at the top is not just a result of being first but of being fundamentally sound and revolutionary.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e0b58e9b7ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/what-makes-bitcoin-different-from-other-cryptocurrencies-5e0b58e9b7ae">What makes Bitcoin different from other cryptocurrencies</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Bitcoin’s Volatility]]></title>
            <link>https://medium.com/@saksham.solanki/understanding-bitcoins-volatility-8789e81c0577?source=rss-f3bc24a20519------2</link>
            <guid isPermaLink="false">https://medium.com/p/8789e81c0577</guid>
            <category><![CDATA[money]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Saksham Solanki]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 18:37:32 GMT</pubDate>
            <atom:updated>2024-06-20T18:37:32.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M81IHf_Z-_-lNx13" /><figcaption>Photo by <a href="https://unsplash.com/@enginakyurt?utm_source=medium&amp;utm_medium=referral">engin akyurt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Bitcoin has transitioned from a niche digital experiment into a global financial phenomenon. Its market capitalization has soared to over $1 trillion, and with the approval of Bitcoin ETFs, Wall Street and other financial institutions have started to embrace this digital asset. However, despite the increasing market cap and acceptance from the financial world, Bitcoin remains volatile. This volatility stems from unique characteristics intrinsic to Bitcoin’s design and protocol, setting it apart from traditional commodities and financial instruments.</p><p>Bitcoin’s supply is strictly regulated by its protocol, which limits the total number of Bitcoins that can ever be mined to 21 million. New Bitcoins are introduced every time a new block is mined. These rewards are fixed and cannot be changed. After 210,000 blocks are mined (approximately four years) rewards for mining new blocks are halved, this process is known as the “halving”. At the start of the network, mining rewards for mining a new block was 50 Bitcoin. After the first halving event, it became 25 Bitcoin per block, then 12.5, and then 6.25. After the most recent halving, the reward to mine a new block is 3.125 Bitcoin.</p><p>This creates an inelastic supply, meaning the quantity of Bitcoin in circulation does not readily adjust in response to changes in demand. The fixed and predictable supply schedule of Bitcoin creates an inelastic supply curve. When Bitcoin’s demand increases, the supply remains constant, leading to significant price increases. Conversely, when Bitcoin’s demand decreases, the supply remains constant, leading to significant price decreases. This inelasticity is a primary driver of Bitcoin’s price volatility.</p><p>Traditional commodities like gold, oil, or financial instruments such as stocks or bonds, have mechanisms that can moderate volatility. Whenever any commodity’s demand increases in the short term it raises its prices and incentivizes more production/ extraction of that resource, bringing in more supply to the market to meet the demand. For example, an increase in the price of gold can lead to increased mining activity, thus boosting supply to meet demand and stabilize prices over time. Higher prices can also lead to the creation of new extraction methods. In the case of Oil, high oil prices led to the Shale Revolution in the United States, which increased the supply so much that the US went from being a net importer of Oil to a net exporter. This ability to change supply acts as a stability mechanism for prices. In Bitcoin’s case, supply does not change regardless of any increase or decrease in demand.</p><p>Even if new miners join the network to mine new blocks faster than the average 10-minute block time, the network will adjust itself to maintain a 10-minute block time. It does this through the difficulty adjustment mechanism where every 2016 block (approximately 2 weeks) the network readjusts the mining difficulty, which makes it harder to a new block, and brings the time to mine a block back to around 10 minutes. This prevents any significant increase in the rate of new Bitcoin creation, maintaining the fixed supply schedule.</p><p>The same characteristic that drives Bitcoin’s value, its fixed supply, also contributes to its volatility. Because Bitcoin’s supply cannot adjust to changes in demand, any fluctuation in demand leads directly to price volatility.</p><h4>Conclusion</h4><p>The inherent volatility of Bitcoin is largely a consequence of its fixed supply schedule and inelastic supply. Unlike other commodities that can adjust their supply to meet rising demand, Bitcoin’s supply remains constant, causing prices to be highly sensitive to changes in demand. Understanding these dynamics is crucial for anyone investing in Bitcoin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8789e81c0577" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Compile Bitcoin Core from Source]]></title>
            <link>https://medium.com/coinmonks/how-to-compile-bitcoin-core-from-source-5539ff9fbce5?source=rss-f3bc24a20519------2</link>
            <guid isPermaLink="false">https://medium.com/p/5539ff9fbce5</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[open-source-software]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Saksham Solanki]]></dc:creator>
            <pubDate>Sun, 24 Oct 2021 09:21:54 GMT</pubDate>
            <atom:updated>2021-10-26T14:36:59.296Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple guide to compiling bitcoin core from source code for Linux systems</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VSBmc4ShufNlMN7m" /><figcaption>Photo by <a href="https://unsplash.com/@aronpw?utm_source=medium&amp;utm_medium=referral">AronPW</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Step 1: Installing all the dependencies</h3><p>Update your system so that all your packages are up to date</p><pre>$ sudo apt update</pre><p>After all your packages are updated, install all dependencies</p><pre>$ sudo apt-get install build-essential libtool autotools-dev automake pkg-config bsdmainutils python3 libssl-dev libevent-dev libboost-system-dev libboost-filesystem-dev libboost-chrono-dev libboost-test-dev libboost-thread-dev libminiupnpc-dev libzmq3-dev libqt5gui5 libqt5core5a libqt5dbus5 qttools5-dev qttools5-dev-tools libprotobuf-dev protobuf-compiler git libsqlite3-dev ccache</pre><h3>Step 2: Installing Bitcoin Core</h3><p>Once all the dependencies are installed, download the Bitcoin Core repository from GitHub.</p><pre>$ git clone <a href="https://github.com/bitcoin/bitcoin.git">https://github.com/bitcoin/bitcoin.git</a></pre><h3>Step 3: Installing Berkeley DB</h3><p>Enter your local copy of the bitcoin repo:</p><pre>$ cd bitcoin</pre><p>Once you are at the root of your bitcoin repo, run:</p><pre>$ ./contrib/install_db4.sh `pwd`</pre><p>Once Berkeley DB is done downloading, the output should look like this:</p><p>db4 build complete.</p><p>When compiling bitcoind, run `./configure` in the following way:</p><pre>export BDB_PREFIX=’&lt;PATH-TO&gt;/db4&#39;</pre><pre>./configure BDB_LIBS=”-L${BDB_PREFIX}/lib -ldb_cxx-4.8&quot; BDB_CFLAGS=”-I${BDB_PREFIX}/include”</pre><p>Take note of the output in the terminal, it will be required later.</p><h3>Step 4: Compile Bitcoin Core</h3><p>Your local copy of the bitcoin repo will be by default synchronized with the most recent code changes, which can be unstable. That is why, before compiling the code choose a specific version by selecting checking out a tag.</p><p>Run the following command to get a list of tags sorted by the most recent change.</p><pre>$ git tag | sort -V</pre><p>Select a tag like v0.21.0 by running the command</p><pre>$ git checkout v0.21.0</pre><p>Once you have selected the tagged branch, run the following commands</p><pre>$ export BDB_PREFIX=’&lt;PATH-TO&gt;/db4&#39;<br>Use the &lt;PATH-TO&gt; value from the output script from install_db4.sh</pre><pre>$ /autogen.sh<br>$ ./configure BDB_LIBS=”-L${BDB_PREFIX}/lib -ldb_cxx-4.8&quot; BDB_CFLAGS=”-I${BDB_PREFIX}/include” if using BDB 4.8, otherwise ./configure — with-incompatible-bdb</pre><p>Then run</p><pre>$ make</pre><p>Or, if you have a CPU with multiple cores, you could make use of them and speed up the process by using your cores by</p><pre>$ make -j &quot;$(($(nproc)+1))&quot;</pre><h3>Step 5: Test the build</h3><p>You can check your build (which you should) by running the following commands</p><pre>$ make check</pre><p>Or make use of multiprocessing by</p><pre>$ make -j “$(($(nproc)+1))”</pre><p>Run the function test</p><pre>$ test/functional/test_runner.py --extended</pre><p>Omit the extended if you want to skip a few tests.</p><h3>Step 6: Install Bitcoin</h3><p>At this point, you can start using bitcoin by</p><pre>$ src/bitcoind</pre><p>Or, you can install bitcoin globally by running</p><pre>$ sudo make install</pre><p>This will install bitcoin globally in your system. After installing you can call bitcoind or bitcoin-cli from anywhere in your system.</p><p>Congratulations you have just compiled bitcoin from source, you have just increased the trustlessness of your setup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5539ff9fbce5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/how-to-compile-bitcoin-core-from-source-5539ff9fbce5">How to Compile Bitcoin Core from Source</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>