<?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 The Market Whisperer on Medium]]></title>
        <description><![CDATA[Stories by The Market Whisperer on Medium]]></description>
        <link>https://medium.com/@the_market_whisperer?source=rss-f4bcbcdca7ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1kTkNEI50aJrpIuQ.jpg</url>
            <title>Stories by The Market Whisperer on Medium</title>
            <link>https://medium.com/@the_market_whisperer?source=rss-f4bcbcdca7ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:13:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@the_market_whisperer/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[How much of my money should I invest?]]></title>
            <link>https://medium.com/@the_market_whisperer/how-much-of-my-money-should-i-invest-8333a6ef66ac?source=rss-f4bcbcdca7ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/8333a6ef66ac</guid>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[The Market Whisperer]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 17:30:50 GMT</pubDate>
            <atom:updated>2023-01-20T18:26:10.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>How much of my money should I invest? — A easy-to-follow introduction to portfolio optimization with Python</h3><p>This article should be easy to read (at least that was what I was going for) for people with some python or programming knowledge. If anything needs to be clarified, please tell me.</p><p>Let us assume you have found some investment strategies you believe in. But if you always put <strong>all</strong> your money into one asset, you are very exposed to risk. What if your particular investment has a catastrophic failure like the cryptocurrency LUNA did last year? The famous trader Warren Buffet always recommends that beginners invest in an index fund instead of choosing individual assets. An index fund is a basket of assets based on different rules. For example, the FTSE 100 index is the 100 biggest companies on the London stock market. If you buy an index fund that follows that, you buy a bit of 100 companies. This is done so that if one big company catastrophically falls, it will be okay and only be part of the investment.</p><p>But there is potential for a lot more money by picking winners, and if you have found some strategy you like and have calculated that it has a good chance to win, then you probably want to put it to use.</p><p>In this article, I will talk about different methods that can be used to find the optimal size of an investment. I will assume you have some strategy you want to follow. The following are the methods I will discuss and show how to use. If you only want to read one of them, then click the name:</p><ol><li><a href="#8563"><strong>The Kelly Criterion</strong></a>: A math formula to determine the best bet size to maximize long-term wealth growth.</li><li><a href="#f633"><strong>The Markowitz Portfolio Theory</strong></a>: A model to determine the best mix of investments based on expected returns and risks.</li><li><a href="#8aa5"><strong>The Black-Litterman Model</strong></a>: A model that combines market views and equilibrium returns to optimize a portfolio.</li><li><a href="#ca18"><strong>The Hierarchical Risk Parity model</strong></a>: A model that uses the risk distributions of different assets to optimize your portfolio.</li></ol><p>I will not backtest which version works best in this article, but I might do so in the future.</p><h3>The Kelly Criterion</h3><p>This is the simplest and most common method. It was mentioned in the first statistics class we had in university, so it is probably the one most people are exposed to.</p><p>The Kelly Criterion is based on the idea that the optimal bet size is the one that maximises compound growth (where the returns from the initial investments are re-invested). Which is a fantastic way to go about it. So what are the downsides? The Kelly Criterion assumes that the future probabilities of winning and losing and how much you can win is known. That is not always the case, but if you have a strategy, then you might know how many per cent of the trades led to a win (let us call that <strong><em>p</em></strong>) and how much, on average, you can expect to win (let us call that <strong><em>b</em></strong>). Both <strong><em>p</em></strong> and <strong><em>b</em></strong> can be calculated in many ways. You could make <strong><em>b</em></strong> the average return of your strategy overall or the average return when you win; the most conservative approach is to take the average return overall because it is a smaller number. Or you can use the Capital Asset Pricing Model (CAPM) to calculate the expected rate of return or any other number of methods to calculate these; I assume that you have some numbers. If you have <strong><em>b</em></strong> and <strong><em>p,</em></strong> then this is how the Kelly Criterion is calculated using them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*l9HFYhQLa6aKUKXen5ILSQ.png" /><figcaption>The formula for calculating the kelly criterion (f)</figcaption></figure><p>By plugging in <strong><em>p</em></strong> (the fraction of bets you would win) and <strong><em>b</em></strong> (the fraction of the bet gained with a win) into that formula, you will get the fraction of your portfolio that you should allocate to the trade.</p><p>For example, let us say you have $10,000 of available trading capital and a strategy that wins 60% of the time. And the expected return, if you win, is 5% more than you started with. Then we can plot that into the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*X90UTUNVdpkpurKgRcv4rQ.png" /><figcaption>The Kelly criterion shows 22% when a strategy wins 60% of the time and expects to grow 5% if you win</figcaption></figure><p>The Kelly fraction gives us the number 0.22 or 22%, which means you should allocate 22% of your available funds for the trade. If you have $10,000, you should allocate $2200 ( $10,000 multiplied by 0.22).</p><h3>The Markowitz Portfolio Theory</h3><p><strong><em>note:</em></strong><em> If you&#39;re not interested in knowing HOW it works but wants the simplest way to optimise (and you have some idea of what kind of risk you want to minimise). Then look at the bottom of the chapter at the addendum (</em><a href="#ce3a"><em>You can also click here</em></a><em>).</em></p><p>This is a different approach altogether, and instead of looking at trade-by-trade, this is more about allocating your assets. This might be better if you have a more long-term strategy and want to allocate your assets. For example, if you have many different assets that you consider interesting and want to invest in. Then you can go through the following steps:</p><ol><li>Calculate the covariance matrix (<strong>K) </strong>between all the investments.</li><li>Use the expected returns and covariances to determine the efficient frontier (I will come back to how to do this), which is the set of portfolios with the highest expected return for a given level of risk or the lowest risk for a given level of expected return.</li><li>Choose the portfolio that lies on the efficient frontier that best meets your risk-return preferences.</li></ol><p>Let us give some examples of how to do this in Python.</p><h4>Calculating covariances between all investments.</h4><p>You can use the standard library, NumPy or Scipy or pandasto calculate the covariance between investments.</p><p>One important consideration when calculating the covariance of two or more investments, the arrays of returns must have the same length. This is because covariance measures the relationship between two variables; to calculate it, you need to have the same number of observations for each variable. There are different ways to do this: cut them off so they are as long as the shortest array, or you can add observations with a value like zero or the mean of the array. The pros and cons of those are beyond the scope of this article.</p><p>Here is how you do that.</p><pre>returns1 = [0.1, 0.2, 0.15, -0.05]<br>returns2 = [0.05, 0.03, -0.02, 0.1]<br><br># standard library (only works on Python 3.10+)<br>from statistics import covariance<br><br>covariance = covariance(returns1, returns2)<br>print(covariance)<br><br># with numpy<br>import numpy as np<br><br>covariance = np.cov(returns1, returns2)<br>print(covariance)<br><br># with scipy<br>from scipy.stats import pearsonr</pre><p>You might have more than two assets you consider as potential investments here. If that is the case, then you can use the pandas library to calculate the covariance matrix between all the columns. But you can also use NumPy which is what we will use:</p><pre><br>returns = {&#39;stock1&#39;: [0.1, 0.2, 0.15, -0.05],<br>           &#39;stock2&#39;: [0.05, 0.03, -0.02, 0.1],<br>           &#39;stock3&#39;: [-0.1, 0.12, 0.2, 0.05]}<br><br># with pandas<br>import pandas as pd<br><br>returns_df = pd.DataFrame(returns)<br>covariance = returns_df.cov()<br>print(covariance)<br><br># with numpy<br>import numpy as np<br><br>returns_array = np.array(list(stock_returns.values()))<br>covariance = np.cov(returns_array)<br>print(covariance)</pre><h4>Determine the efficient frontier</h4><p>So how do we use the returns ( <strong>E</strong> ) and the calculated covariances ( <strong>K</strong> ) to determine the efficient frontier? The efficient frontier combines the investments in different proportions and calculates each portfolio&#39;s expected return and risk. Unless you have a massive supercomputer, it is tricky to calculate this on ALL possible combinations. Especially if you have many assets. But we can use optimization techniques like Quadratic Programming to find the optimal portfolio weights. I will write an example of how to do it in Python with 3 assets using numpy, pandas,cvxopt libraries and matplotlib to plot.</p><p>First, to generate a few random portfolios, we can generate random weights of length <em>n</em> using this function:</p><pre>import numpy as np<br><br>def generate_random_weights(n: int) -&gt; np.ndarray:<br>    &quot;&quot;&quot;<br>    Generates n random weights that sum to 1.<br>   <br>    Parameters:<br>        n (int): The number of random weights to generate.<br>   <br>    Returns:<br>        np.ndarray: The generated random weights.<br>    &quot;&quot;&quot;<br>    weights = np.random.rand(n)<br>    return weights / sum(weights)</pre><p>This function will be used to generate random portfolios in the following function:</p><pre>import numpy as np<br>import pandas as pd<br><br>def generate_random_portfolio(returns: np.ndarray) -&gt; tuple[float, float]:<br>    &quot;&quot;&quot;<br>    Generates a random portfolio and returns its mean and standard<br>    deviation of returns.<br>    <br>    Parameters:<br>        returns (np.ndarray): The returns of the assets.<br>    <br>    Returns:<br>        Tuple[float, float]: A tuple containing the mean (mu) and<br>             standard deviation (sigma) of returns of the random portfolio.<br>    &quot;&quot;&quot; <br>    p = np.asmatrix(np.mean(returns, axis=1))<br>    w = np.asmatrix(generate_random_weights(returns.shape[0]))<br>    C = np.asmatrix(np.cov(returns))<br>    mu = w * p.T<br>    sigma = np.sqrt(w * C * w.T)<br>    # Avoid outliers to keep plots pretty<br>    if sigma &gt; 2:<br>        return generate_random_portfolio(returns)<br>    return mu, sigma</pre><p>In this case, we used standard deviation (sigma in the last function) as a measure of risk. This is a common definition of risk, but you could use downside risk (standard deviation of only the losses) or upside risk (only the standard deviation of the winning trades) or any other definition of risks like variance or so-called Value at Risk (VaR). Many people will say that you should only use this or that risk measurement, but it is your money, and you know best what you want to use. But when finance people say risk, they <em>usually</em> mean plain standard deviation of the returns. However, if you want to use something else, you can replace the sigma in the last function. To show how that function is used, let us make 500 random portfolios and plot the mean of the return versus the risk.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br><br>stock_returns = {&#39;stock1&#39;: [0.1, 0.2, 0.15, -0.05],<br>           &#39;stock2&#39;: [0.05, 0.03, -0.02, 0.1],<br>           &#39;stock3&#39;: [-0.1, 0.12, 0.2, 0.05]}<br><br># Define the returns (E) as np_array<br>E = np.array(list(stock_returns.values()))<br>n_portfolios = 500<br>means, stds = np.column_stack([<br>    generate_random_portfolio(E) <br>    for _ in range(n_portfolios)<br>])<br>plt.plot(stds, means, &#39;o&#39;, markersize=5)<br>plt.xlabel(&#39;risk (std)&#39;)<br>plt.ylabel(&#39;mean&#39;)<br>plt.title(&#39;Mean and standard deviation of returns of randomly generated portfolios&#39;)<br>plt.show()</pre><p>If you run the code with the returns as shown based on the simple return examples, you should get a plot that looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*LpBunApmsKRL3sWKId-8sg.png" /><figcaption>A plot of random portfolios</figcaption></figure><p>On the y-axis, we can see the means; none of the portfolios we plotted has means under 0, which would lose us money, so all of them would make us money, but you see that some of them have a high risk (high standard deviation) and very low mean return at the same time. But do you see the pattern? The efficient frontier is the top line of the shape, but how do we find the exact weights that follow the top line? We will come to that, but first: Let&#39;s talk a little about what risk to take.</p><p>Standard deviation (<strong>σ</strong>) as a measure of risk is very common for many reasons. It assumes that the returns follow a normal distribution, which many will point out is not true (in reality, it is a “fat-tailed distribution”). But it is a very good approximation most of the time, and it is much simpler to think about, which is why it is used. In statistics, there is something called the 68–95–99.7 rule, also known as the empirical rule. It is very simple to use as a shorthand rule of thumb.</p><p>68% is one standard deviation from the mean, 95% is two standard deviations from the mean, and 99.7% is three standard deviations from the mean. For example, let us say that you choose a portfolio with a mean of 0.08 (+8% return) and a standard deviation of 0.06 (6% <strong>σ</strong>). In that case, we could make a rule of thumb to think that 68% of the time you choose that portfolio, then you will get a return of between +2% (0.08–0.06) and +14% (0.08+0.06) or 95% of the time you get a return of -4% (0.08–2*0.06) and +20% (0.08–2*0.06). Or, at last, you might, 99.7% of the time, get a return of between -10% and +26%. There is only a 0.3% chance (assuming normal distribution) that you will lose more than 10% (0.15% chance of losing less than that) or gain a return higher than 26% (0.15% chance of winning more than that as well). If you want to be more exact than this, you can use the z-score test to figure out the exact values 99% of the time or 74% or whatever percentage you prefer. But remember that when we assume a normal distribution, that is only an approximation. So I don’t know how useful it is to try to be exact. I haven’t done the math on that, but now you’re aware.</p><p>Back to the efficient frontier. We plotted 100 random portfolios and got a strange shape out of it; we can choose a risk we like and find the weights by doing the random way. But we can also use an optimization technique called quadratic programming to find <strong>THE</strong> optimal weights which will give us the most for the least risk. This can be tricky, but very conveniently, there is a python package called cvxopt , which is a convex optimization library that can do this for us. I have taken the thinking from <a href="https://notebook.community/elsdrm/shared_note/.ipynb_checkpoints/The%20Efficient%20Frontier-%20Markowitz%20portfolio%20optimization%20in%20Python-checkpoint">this great article</a> that shows how to do it. I will create a function called calculate_optimal_portfolio which takes in a numpy array and returns a tuple of the weights, the returns and the risk value:</p><pre>import numpy as np<br>import pandas as pd<br>import cvxopt as opt<br><br>def calculate_optimal_portfolio(E: np.ndarray) -&gt; tuple[np.ndarray, list[float], list[float]]:<br>    &quot;&quot;&quot;<br>    Calculates the optimal portfolio using the Markowitz Portfolio Theory and <br>    the efficient frontier method.<br>    <br>    Parameters:<br>        E (np.ndarray): The returns of the assets.<br>    <br>    Returns:<br>        tuple[np.ndarray, List[float], List[float]]: A tuple containing the <br>        weights of the optimal portfolio, the returns of the efficient frontier <br>        and the risks of the efficient frontier.<br>    &quot;&quot;&quot;<br>    number_of_assets = len(E)<br>    returns = np.asmatrix(E)<br>    N = 100<br>    mus = [10**(5.0 * t/N - 1.0) for t in range(N)]<br>    #    <br>    # Convert to cvxopt matrices<br>    S = opt.matrix(np.cov(returns))<br>    p = opt.matrix(np.mean(returns, axis=1))<br>    #<br>    # Create constraint matrices<br>    G = -opt.matrix(np.eye(number_of_assets))   # negative n x n identity matrix<br>    h = opt.matrix(0.0, (number_of_assets ,1)) # column vector of zeros n assets long<br>    A = opt.matrix(1.0, (1, number_of_assets))<br>    b = opt.matrix(1.0) <br>    #<br>    # Calculate efficient frontier weights using quadratic programming<br>    portfolios = [opt.solvers.qp(mu*S, -p, G, h, A, b)[&#39;x&#39;] <br>                  for mu in mus]<br>    #<br>    # Calculate risks and returns for frontier<br>    returns = [opt.blas.dot(p, x) for x in portfolios]<br>    risks = [np.sqrt(opt.blas.dot(x, S*x)) for x in portfolios]<br>    #<br>    # Calculate the 2nd degree polynomial of the frontier curve<br>    m1 = np.polyfit(returns, risks, 2)<br>    x1 = np.sqrt(abs(m1[2] / m1[0]))<br>    #<br>    # calculate THE optimal portfolio<br>    wt = opt.solvers.qp(opt.matrix(x1 * S), -pbar, G, h, A, b)[&#39;x&#39;]<br>    return np.asarray(wt), returns, risks         </pre><p>The optimizer is minimizing the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*z5e3nMQiXoHkFGlljryotg.png" /></figure><p>With the constraints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*7OkfWnBKPPGYpepLNGg8Xg.png" /></figure><p>I need to explain themus vector. The operation 10**(5.0 * t/N - 1.0) is a way to generate a series of expected return values that increases exponentially. The constant 5.0 is used to adjust the rate of increase of the expected returns.</p><p>This is because it allows the function to explore a wide range of expected return values. This can be useful when working with financial data, where the expected return of an asset can be highly uncertain.</p><p>In the previous function, the mus vector is used in the following lines of code:</p><pre># Calculate efficient frontier weights using quadratic programming<br>portfolios = [solvers.qp(mu*S, -pbar, G, h, A, b)[&#39;x&#39;] <br>                  for mu in mus]</pre><p>It’s used to iterate over a range of expected return values and calculate the optimal portfolio. The expected returns are used in the objective function of the optimization problem by using mu*S. This allows the function to explore different risk-return trade-offs and find the optimal portfolio given the expected returns.</p><p>Let us redo the 500 random portfolios plot, add optimal portfolio values, and plot the efficient frontier.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import cvxopt as opt<br><br>returns = {&#39;stock1&#39;: [0.1, 0.2, 0.15, -0.05],<br>           &#39;stock2&#39;: [0.05, 0.03, -0.02, 0.1],<br>           &#39;stock3&#39;: [-0.1, 0.12, 0.2, 0.05]}<br><br># Define the returns (E)<br>E = pd.DataFrame(returns)<br><br># calculate 500 random portfolios<br>n_portfolios = 500<br>means, stds = np.column_stack([<br>    generate_random_portfolio(E) <br>    for _ in range(n_portfolios)<br>])<br><br># find optimal portfolio and efficient frontier<br>weights, returns, risks = calculate_optimal_portfolio(E)<br><br>plt.plot(stds, means, &#39;o&#39;, markersize=5) # plot random portfolios (blue)<br>plt.plot(risks, returns, &#39;y-o&#39;) # plot efficient frontier (yellow)<br>plt.xlabel(&#39;risk (std)&#39;)<br>plt.ylabel(&#39;mean&#39;)<br>plt.show()</pre><p>If you run this code with the functions previously mentioned, then you should get a plot that looks somewhat like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tInbvMmUdlskmUlL1oq8sA.png" /><figcaption>Plot of the mean and risk of random portfolios (blue) and the efficient frontier (yellow) for the desired returns (the ‘mus’ variable)</figcaption></figure><p>In the function named calculate_optimal_portfolio you also get a variable weights that shows the ideal result. Let us see how that looks:</p><pre>print(weights)<br><br># If we do this with the returns example we have used then<br># we will get the results:<br># <br># [[9.99999954e-01]  <br>#  [6.15514649e-09]  <br>#  [3.97608831e-08]]</pre><p>If you’re not used to scientific notation, then that means that the first number is 0.999999954, the second number is 0.00000000615514649 and the third is 0.0000000397608831. In other words, the best portfolio is if you only keep the stock1 asset (or at least 99.9999954% of the portfolio). Of course, this is a toy example with very few return numbers and few assets. You would probably get reasonable weights if you chose real assets and real returns. But this shows that you can remove some assets if they correlate well but has worse returns.</p><h4>Addendum</h4><p>When researching the next article (The Black-Litterman Model), I came across a neat little python library called PyPortfolioOpt (<a href="https://pyportfolioopt.readthedocs.io/en/latest/">documentation here</a>), which simplifies a lot. I spent a lot of time explaining the above, but this is much easier to use. It is powerful, and you can do a lot more advanced stuff than I have shown you. And it is a lot easier to use. If you want the easy-to-use way of doing what I said above, you can check out <a href="https://pyportfolioopt.readthedocs.io/en/latest/MeanVariance.html">the documentation for Mean-Variance Optimization</a> which is the type of optimization I did above. Look, all you need is the expected returns (mean for each asset in <strong>E</strong>, which we will call <strong>mu</strong>) and the covariance matrix (<strong>K</strong>). Which we calculated above.<br>But the library doesn’t <strong>ONLY</strong> let us optimise for Mean-Variance. But also Semivariance (which is like Mean-Variance, except it only looks at returns below the mean. So they minimise downside risk. <a href="https://www.investopedia.com/terms/s/semivariance.asp">More info here</a>) or Conditional-Value-at-Risk (<a href="https://www.investopedia.com/terms/c/conditional_value_at_risk.asp">More info here</a>) or conditional drawdown at risk (<a href="https://breakingdownfinance.com/finance-topics/alternative-investments/conditional-drawdown-at-risk-cdar/">More info here</a>) and many others and it is so easy to use! Let me show you.</p><pre>import numpy as np<br>from pypfopt.efficient_frontier import EfficientFrontier<br>from pypfopt import EfficientSemivariance, EfficientCVaR, EfficientCDaR<br><br>returns = {&#39;stock1&#39;: [0.1, 0.2, 0.15, -0.05],<br>           &#39;stock2&#39;: [0.05, 0.03, -0.02, 0.1],<br>           &#39;stock3&#39;: [-0.1, 0.12, 0.2, 0.05]}<br><br># Define the returns (E) <br>E = np.array(list(returns.values()))<br># Define the expected returns (mu)<br># I use the arithmetic mean, you might use geometric mean or some other<br># Expected value per asset like exponentially-weighted mean<br>mu = E.mean(axis=1)<br># Define the covariance matrix (K)<br>K = np.cov(E)<br><br># Somewhat similar to what we did above, but with different optimization:<br>ef = EfficientFrontier(mu, K)  # setup<br># To get the weights you can one of the many public methods that<br># EfficientFrontier has. See documentation. Here is an example of<br># how to get the weights for the portfolio with maximum Sharpe ratio:<br>max_sharpe_weights = ef.max_sharpe()<br>print(max_sharpe_weights)<br># OrderedDict([(0, 0.2530542697371143), &lt;- stock1<br>#              (1, 0.6507321223917373), &lt;- stock2<br>#              (2, 0.0962136078711484)]) &lt;- stock3<br><br># Here are examples of others, but remember that the objects have<br># a lot more optimization options than these, see documentation:<br><br># optimise based on minimising Semivariance<br>es = EfficientSemivariance(mu, E)<br>min_semivariance_weights = es.min_semivariance()<br><br># optimise based on minimising conditional value-at-risk<br>ecvar = EfficientCVaR(mu, E)<br>min_cvar_weights = ecvar.min_cvar()<br><br># optimise based on minimising conditional drawdown-at-risk<br>ecdar = EfficientCDaR(mu, E)<br>min_cdar_weights = ecdar.min_cdar()</pre><p>Simple! I spent so much time researching the rest of the chapter that I am keeping it, but if you know what risk you want to optimise for, then you’re set.</p><h3><strong>The Black-Litterman Model</strong></h3><p>This model is a little bit peculiar. This model includes the investor&#39;s views, beliefs and opinions as part of the optimization process. It requires a strong understanding of math to understand, but I will walk you through it. What if you don’t have strong knowledge or beliefs? Well, you can always try to use sentiment analysis or indicators like the fear-and-greed index or other methods to add a view. I will talk about how to construct what you need. This model was developed at Goldman Sachs in 1990.</p><p>The Black-Litterman Model is a more advanced version of the Markowitz portfolio optimization model mentioned in the previous part, which only looks at historical returns and the covariance matrix of assets.`We are going to use the library called PyPortfolioOpt to do this more easily. Remember from now on that <strong>n</strong> is the number of assets, and <strong>v</strong> is the number of views. The steps we need to do is:</p><ol><li>Get the returns (<strong>E</strong>) and covariance matrix (<strong>K</strong>) of the assets in the portfolio. Returns and calculating covariance is explained at the beginning of the <em>Markowitz portfolio optimization model</em> part of this article.</li><li>Provide implied prior returns. Traditionally it is represented by an uppercase pi (<strong>Π</strong>), which you can consider the “default” estimate. This is technically optional, however, but I will explain it.</li><li>Provide the views vector (<strong>Q</strong>) and the picking matrix (<strong>P</strong>). This would be tricky, even if we didn&#39;t havePyPortfolioOpt to help us. So I will be careful when explaining this.</li><li>Get the confidence matrix (not to be mistaken with the covariance matrix from step 1), represented with the omega symbol (<strong>Ω</strong>). And then, the tau variable (<strong>τ</strong>) represents the relative weights of the priors. A paper <a href="http://dx.doi.org/10.2139/ssrn.1701467">here</a> talks about what value to choose, but we will choose the default: <strong>τ </strong>= 0.05. These are also optional to add to the formula, but I will discuss them briefly.</li><li>Calculate the so-called “posterior combined return vector” (<strong>E[R]</strong>) with the Black-Litterman formula. This uses linear algebra, but don’t worry if you don’t know it. I will explain.</li><li>Use the posterior combined return vector in the same way as in the previous chapter. The optimal portfolio weights obtained from the optimization problem determine the optimal investment size for each asset also in the same way.</li></ol><h4>the Black-Litterman formula</h4><p>I might start by defining and explaining the Black-Litterman formula and its parts. The formula for the new return vector (<strong>E[R]</strong>) can look a bit scary, but don’t worry since it is mostly calculated for us. I just include it to explain how it works. The formula is like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*WXWbCxaPaE1AL-N85Hu7Ag.png" /></figure><p>where:</p><ul><li><strong>E[R]</strong> is a <strong><em>n </em></strong>x 1 vector of expected returns, where <strong><em>n</em></strong> is the number of assets (mentioned in step 5).</li><li><strong>Q</strong> is a <strong><em>v</em></strong> x 1 vector of views, where <strong><em>v</em></strong> is the number of assets (mentioned in step 3).</li><li><strong>P</strong> is the <strong><em>v</em></strong> x <strong><em>n</em></strong> picking matrix which maps views to the universe of assets. It tells the model which view corresponds to which asset(s) (mentioned in step 3).</li><li><strong>Ω</strong> is the<strong><em> v</em></strong> x <strong><em>v</em></strong> uncertainty or confidence matrix of views (mentioned in step 4).</li><li><strong>Π</strong> is the <strong><em>n</em></strong> x 1 vector of prior expected returns (mentioned in step 2).</li><li><strong>K</strong> is the NxN covariance matrix of asset returns (mentioned in step 1).</li><li><strong>τ</strong> is a scalar tuning constant (mentioned in step 4).</li></ul><p>It seems tricky, but it is a weighted average between the prior estimate and the views. This calculation will be done for us.</p><h4>Priors ( <strong>Π )</strong></h4><p>First, we need the implied prior returns, which is the <strong>Π</strong> in the previous formula. This is the default estimate. You can calculate this in many ways. Usually, this is based on the market-implied risk premium (<strong>δ</strong>), which is the so-called market’s excess return divided by the variance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*fwzSBlMK-zJ5NDk9_6qpwQ.png" /></figure><p>where:</p><ul><li><strong>δ </strong>is the market-implied risk premium</li><li><strong>R </strong>is the return of the market.</li><li><strong>Rₒ</strong> is the “risk-free rate of return”, which is the percentage return you could have gotten “risk-free” which you miss out on if you invest in this. Traditionally something like government bonds or something else “risk-free” that you would have invested instead. Me personally? I always put this number at 0 since I wouldn’t do government bonds or anything, so it wouldn’t be a useful addition to me. But you might have something else. Maybe you get a tax break from keeping it in the bank or something.</li><li><strong>σ²</strong> is the variance</li></ul><p>In the stock market, you might choose the return of an index like the <strong>SPY</strong> as the return of the market (<strong>R</strong>). You might choose the return of bitcoin or something in the cryptocurrency market since it is a good approximation of how the cryptocurrency market overall is doing. But me? I would optimise for a large variety of potential assets when I do this. So I would base it on the returns (<strong>E</strong>) of my assets and calculate <strong>δ </strong>and priors (<strong>Π</strong>) like this:</p><pre>import numpy as np<br><br># get returns of each stock with your strat for equal amount of trades<br>returns =     {&#39;stock1&#39;: [0.1, 0.2, 0.15, -0.05],<br>               &#39;stock2&#39;: [0.05, 0.03, -0.02, 0.1],<br>               &#39;stock3&#39;: [-0.1, 0.12, 0.2, 0.05]}<br># get market cap of each stock<br>market_caps = {&#39;stock1&#39;: 19_000_400,<br>               &#39;stock2&#39;: 34_000_021,<br>               &#39;stock3&#39;: 51_000_000}<br><br># Define the returns (E) <br>E = np.array(list(returns.values()))<br># Define the market-implied risk premium δ )<br>risk_free_rate_for_the_period = 0 # zero for me<br>delta = (np.mean(E)-risk_free_rate_for_the_period)/np.var(E)<br><br># Define the covariance matrix (K)<br>K = np.cov(E)<br># weigh them by marketcap<br>mcap = np.array(list(market_caps.values()))<br>mcap_weight = mcap/np.sum(mcap)<br><br># Define the implied prior returns (Π)<br>priors = delta * np.dot(mcap_weight, K) + risk_free_rate_for_the_period</pre><p>You can, of course, use any default estimate (one number per asset). As long as it has the correct dimension as a <strong><em>n</em></strong> x 1 vector. Use something that makes sense for you.</p><h4>Views ( Q ) &amp; ( P )</h4><p>This is the real genius behind the technique and maybe the most tricky part. There are essentially two types of views. Absolute views are where you think that some asset will grow or go down a certain percentage; for example, you might think that <em>stock1</em> will grow 5%. And relative views, where you express some opinion about the expected returns of one asset relative to another asset. For example, you believe that <em>stock3</em> will do 2% worse than <em>stock2</em>. And also you might have more involved views like you believe that the whole market will grow 10%. I have never seen any examples, but I am sure mathematically, it would be no problem to have some opinion/view which contradicts another view or that isn’t logically consistent with other views. For example, we could have the view that <em>stock2</em> and <em>stock3</em> will underperform <em>stock1</em> by 1%. Although the market of these 3 assets could not grow 10% in total, if it were the case that stock1 would grow 5% and stock2 and stock3 together would only grow 4. But the world is messy, and we might have reasons to hold contradictory views. And they might weaken each other mathematically. Although I do not see why you could not do that if you want, even though nobody mentions it. More details about making views can be found <a href="https://people.duke.edu/~charvey/Teaching/BA453_2006/Idzorek_onBL.pdf">here</a>. But let us say we have the views mentioned:</p><ol><li><em>stock1</em> will grow 5% (absolute view)</li><li><em>stock3</em> will drop 3% (absolute view)</li><li><em>stock3</em> will do 2% worse than <em>stock2</em>. (or <em>stock2 </em>will do 2% better than<em> stock3)</em></li><li>the whole market will grow 10% (absolute)</li><li><em>stock2</em> and <em>stock3</em> will underperform <em>stock1</em> by 1%.</li></ol><p>The views vector (<strong>Q</strong>), a <strong><em>v</em></strong> x 1 vector where v is the number of views, can be created by taking the numbers above and putting them into the column.</p><pre>import numpy as np<br><br>Q = np.array([0.05, -0.03, 0.02, 0.10, 0.01]).reshape(-1, 1)</pre><p>The picking matrix (<strong>P</strong>) is the <strong><em>v</em></strong> x <strong><em>n</em></strong> matrix ( where <strong><em>v</em></strong> is the number of views and <strong><em>n</em></strong> is the number of assets), which maps views to the universe of assets. Which is the most important part of the model, and allows us to translate the views into numbers we can tweak the model with.</p><pre>import numpy as np<br><br># Define picking matrix P<br>P = np.array(<br>    [<br>        [1,0,0],<br>        [0,0,1],<br>        [0,1,-1],<br>        [(1/3),(1/3),(1/3)],<br>        [1,-0.5,-0.5]<br>    ]<br>)</pre><p>So each view has one row in the picking matrix (<strong>P</strong>). Absolute view rows should sum up to one. Relative view rows should sum to 0. I hope this is understandable. Tell me if it isn’t.</p><h4>Confidence matrix (<strong>Ω</strong>)</h4><p>The confidence matrix is a <strong><em>v</em></strong> x <strong><em>v</em></strong> matrix that contains the variances of each view. You can look up details in the library <a href="https://pyportfolioopt.readthedocs.io/en/latest/BlackLitterman.html#confidence-matrix-and-tau">documentation</a> if you want. But to be able to customise we will use the “idzorek” method. We then need a list or NumPy array of percentages of how confident you are per view. Let us say that we are 50% confident that view 1 is true, 40% confident that view 2 is true. 77% confident that view 3 is true, 46% confident that view 4 is true and 12% confident that view 5 is true. We can then make this list of view confidences:</p><pre>view_confidences = [0.50, 0.40, 0.77, 0.46, 0.12]</pre><p>When we have everything, we can put it together to calculate weights using the Black-Litterman model.</p><h3>Calculating weights with the Black-Litterman model</h3><p>Here is an example code which calculates optimal weights using the Black-Litterman model in our example:</p><pre>import numpy as np<br>from pypfopt.black_litterman import BlackLittermanModel<br>from pypfopt.efficient_frontier import EfficientFrontier<br><br># get returns of each stock with your strat for equal amount of trades<br>returns =     {&#39;stock1&#39;: [0.1, 0.2, 0.15, -0.05],<br>               &#39;stock2&#39;: [0.05, 0.03, -0.02, 0.1],<br>               &#39;stock3&#39;: [-0.1, 0.12, 0.2, 0.05]}<br># get market cap of each stock<br>market_caps = {&#39;stock1&#39;: 19_000_400,<br>               &#39;stock2&#39;: 34_000_021,<br>               &#39;stock3&#39;: 51_000_000}<br><br># Define the returns (E) <br>E = np.array(list(returns.values()))<br># Define the covariance matrix (K)<br>K = np.cov(E)<br># Define the market-implied risk premium δ (delta)<br>risk_free_rate_for_the_period = 0 # zero for me<br>delta = (np.mean(E)-risk_free_rate_for_the_period)/np.var(E)<br><br># weigh them by marketcap<br>mcap = np.array(list(market_caps.values()))<br>mcap_weight = mcap/np.sum(mcap)<br><br># Define the implied prior returns (Π)<br>priors = delta * np.dot(mcap_weight, K) + risk_free_rate_for_the_period<br><br># define views Q<br>Q = np.array([0.05, -0.03, 0.02, 0.10, 0.01]).reshape(-1, 1)<br># Define picking matrix P<br>P = np.array(<br>    [<br>        [1,0,0],<br>        [0,0,1],<br>        [0,1,-1],<br>        [(1/3),(1/3),(1/3)],<br>        [1,-0.5,-0.5]<br>    ]<br>)<br><br># define confidence<br>view_confidences = [0.50, 0.40, 0.77, 0.46, 0.12]<br><br># Create BlackLittermanModel, everything except K, Q &amp; P is optional<br># Q &amp; P is not obligatory if you provide absolute_views. See socumentation<br>bl = BlackLittermanModel(K, pi=priors, Q=Q, P=P, omega=&quot;idzorek&quot;,<br>                         view_confidences=view_confidences)<br><br># then you can get the weights with<br>print(bl.bl_weights())<br># OrderedDict([(0, 0.3119946576205076), <br>#              (1, 0.590140564100669), <br>#              (2, 0.09786477827882341)])<br># or for cleaner weights <br>print(bl.clean_weights())<br># OrderedDict([(0, 0.31199), <br>#              (1, 0.59014), <br>#              (2, 0.09786)])<br></pre><h3><strong>The Hierarchical Risk Parity model</strong></h3><p>The Hierarchical Risk Parity (HRP) model is a portfolio optimization method based on spreading risk evenly across different investments. The HRP method uses a hierarchical structure to group assets into different levels, such as individual assets, sub-portfolios, and asset classes. For each level, the HRP method calculates the risk contributions of the assets and allocates portfolio weights based on those risk contributions. This approach helps to balance risk across different assets, sub-portfolios, and asset classes, resulting in a more diversified and stable portfolio.</p><p>This is a fairly new technique that uses new modern mathematics (<a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2708678">white paper here</a>)</p><p>We can use the library called PyPortfolioOpt to do this as well, just like in the previous chapter. This is much simpler to implement. The only thing you need is the returns of your strategy or covariance matrix.</p><pre>import pandas as pd<br>from pypfopt.hierarchical_portfolio import HRPOpt<br><br>returns = {&#39;stock1&#39;: [0.1, 0.2, 0.15, -0.05],<br>           &#39;stock2&#39;: [0.05, 0.03, -0.02, 0.1],<br>           &#39;stock3&#39;: [-0.1, 0.12, 0.2, 0.05]}<br><br># Define the returns (E)<br>E = pd.DataFrame(returns)<br># Define covariance matrix (K)<br>K = E.cov()<br><br># Create HRPOpt model<br>hrp = HRPOpt(E)<br>hrp.optimize()<br>print(hrp.clean_weights())<br># OrderedDict([(&#39;stock1&#39;, 0.12364), <br>#              (&#39;stock2&#39;, 0.78746), <br>#              (&#39;stock3&#39;, 0.0889)])</pre><p>This is fairly short. But it would be important to add it as it is an option in the library.</p><p><em>There are, of course, several other methods. The main thing is what risk to minimize. I tried researching several other techniques like Bayesian Adaptive Asset Allocation and Machine learning methods, but this article is long enough as it is.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8333a6ef66ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Loss & Take Profit strategies.]]></title>
            <link>https://medium.com/@the_market_whisperer/stop-loss-take-profit-strategies-9c6cecea06dc?source=rss-f4bcbcdca7ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c6cecea06dc</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[take-profit]]></category>
            <category><![CDATA[stop-loss]]></category>
            <category><![CDATA[trading-strategy]]></category>
            <dc:creator><![CDATA[The Market Whisperer]]></dc:creator>
            <pubDate>Wed, 18 Jan 2023 20:20:51 GMT</pubDate>
            <atom:updated>2023-01-18T20:20:51.819Z</atom:updated>
            <content:encoded><![CDATA[<p>Stop loss and take profit are two common trading strategies to manage a trade’s risk.</p><p>Stop loss is a trade management technique that involves setting a predetermined price at which a trade will be closed to minimise potential losses. For example, if you buy a stock at $100 and put a stop loss at $90, your trade will be automatically closed if the stock price falls to $90, limiting your potential loss to $10 per share.</p><p>Take profit, on the other hand, is a trade management technique that involves setting a predetermined price at which a trade will be closed to maximise potential profits. For example, if you buy a stock at $100 and put a take profit at $110, your trade will be automatically closed if the stock price rises to $110, allowing you to realise a profit of $10 per share.</p><p>So Stop Loss and Take Profit signals when some asset should be sold. <strong>This article aims to create a python class function that can handle all possible Stop Loss &amp; Take Profit strategies and variations. It is just me coding as I write the article. It starts as a mess, but the result is at the bottom.</strong></p><pre># anticipated imports<br>import pandas as pd<br><br>def add_sl_and_tp(df):<br>    &quot;&quot;&quot;<br>    Add stop loss and take profit levels to a dataframe of OHLCV data,<br>    and return the dataframe with sell signals based on these levels.<br><br>    Parameters:<br>    df (pd.Dataframe):      OHLCV data with at least columns <br>                            &#39;Open&#39;,&#39;High&#39;,&#39;Low&#39;,&#39;Close&#39;, and &#39;Volume&#39; and a<br>                            column called &quot;buySignals&quot; that contain<br>                            buy signals (1 = buy, 0 = not buy).<br><br>    Returns:<br>    pandas dataframe: The original dataframe with one new column added:<br>        - &quot;sellSignal&quot;: The sell signal (1 = sell, 0 = hold) based on the stop loss<br>            and take profit levels.<br>    &quot;&quot;&quot;<br>    # Initialize the &quot;sellSignal&quot; column to 0 (hold position)<br>    df[&#39;sellSignal&#39;] = 0<br><br>    # Create variables for stop loss and take profit levels<br>    # set them to plus and minus infinity so that they won&#39;t<br>    # create sell signal before first buy<br>    stopLoss = float(&quot;-inf&quot;)<br>    takeProfit = float(&quot;inf&quot;)<br>    <br>    # Iterate through the rows of the dataframe to keep track when bought<br>    for index, row in df.iterrows():<br>        if (row[&quot;Close&quot;] &lt; stopLoss) | (row[&quot;Close&quot;] &gt; takeProfit):<br>            # Register sell signal and reset stopLoss &amp; takeProfit<br>            df.at[index, &#39;sellSignal&#39;] = 1<br>            stopLoss = float(&quot;-inf&quot;)<br>            takeProfit = float(&quot;inf&quot;)<br>        elif row[&quot;buySignals&quot;] = 1:<br>            # Asset is bought so set stoploss &amp; takeProfit. As placeholder<br>            # we set it to High and Low prices.<br>            stopLoss = row[&quot;Low&quot;]<br>            takeProfit = row[&quot;High&quot;]<br>     <br>    # Return dataframe<br>    return df<br><br></pre><p>There are several strategies that traders use to set stop loss and take profit levels:</p><ol><li><strong>Fixed stop loss and take profit</strong>: In this strategy, the trader sets a static stop loss and take profit level and does not adjust them during the trade.</li><li><strong>Trailing stop loss &amp; take profit</strong>: In this strategy, the trader adjusts the stop loss level as the trade moves in their favour. For example, if a trader buys a stock at $50 and sets a trailing stop loss at $45, the stop loss will be adjusted to $50 if the stock price increases to $55.</li><li><strong>Time-based stop loss</strong>: In this strategy, the trader sets a stop loss level based on the time they are willing to hold the trade. For example, a trader might put a stop loss to close the trade if it is not profitable within 3 days.</li></ol><p>These facts lead to the first change in my code. I have to consider all these different ways to calculate stop-loss and take-profits. One way I could do it is to have lots of if-else statements inside the function, but that quickly becomes unwieldy, so the best solution is to instantiate a class object and include it as the input. Here is a skeleton code of the class.</p><pre>import pandas as pd<br><br>class StopLossAndTakeProfit:<br>   &quot;&quot;&quot;<br>        This class represents a stop-loss and take-profit strategy.<br>         It takes in three arguments:<br><br>        df: A pd.Dataframe with OHLCV (Open, High, Low, Close, Volume) data.     <br>        stoploss_type: A string indicating the type of stop-loss to use.<br>        takeprofit_type: A string indicating the type of take-profit to use.<br>        It has two methods:<br>        <br>        get_stop_loss(price: float) -&gt; float: Returns the stop loss<br>                                              value for the given price.<br>        get_take_profit(price: float) -&gt; float: Returns the take profit <br>                                              value for the given price.<br>    &quot;&quot;&quot;<br>    def __init__(self,  df: pd.Dataframe, stoploss_type: str,<br>                        takeprofit_type: str):<br>        self.df = df<br>        self.stoploss_type = stoploss_type<br>        self.takeprofit_type = takeprofit_type<br>    <br>    def get_stop_loss(self, price: float) -&gt; float:<br>        &quot;&quot;&quot;Returns the stop loss price based on the stoploss_type.&quot;&quot;&quot;<br>        if self.stoploss_type == &#39;fixed&#39;:<br>            # code for fixed stop loss goes here<br>            pass<br>        elif self.stoploss_type == &#39;trailing&#39;:<br>            # code for trailing stop loss goes here<br>            pass<br>        elif self.stoploss_type == &#39;time-based&#39;:<br>            # code for time-based stop loss goes here<br>            pass<br>        elif self.stoploss_type == &#39;multiple&#39;:<br>            # code for multiple stop loss levels goes here<br>            pass<br>        else:<br>            raise ValueError(&#39;Invalid stoploss_type&#39;)<br>    <br>    def get_take_profit(self, price: float) -&gt; float:<br>        &quot;&quot;&quot;Returns the take profit price based on the takeprofit_type.&quot;&quot;&quot;<br>        if self.takeprofit_type == &#39;fixed&#39;:<br>            # code for fixed take profit goes here<br>            pass<br>        elif self.takeprofit_type == &#39;trailing&#39;:<br>            # code for trailing take profit goes here<br>            pass<br>        elif self.stoploss_type == &#39;time-based&#39;:<br>            # code for time-based take profit goes here<br>            pass<br>        elif self.stoploss_type == &#39;multiple&#39;:<br>            # code for multiple take profit levels goes here<br>            pass<br>        else:<br>            raise ValueError(&#39;Invalid takeprofit_type&#39;)<br><br>   def update_stop_loss(self, index, current_sl) -&gt; float:<br>      &quot;&quot;&quot;Updates the stop loss price based on the stoploss_type.&quot;&quot;&quot;<br>      if self.stoploss_type == &#39;fixed&#39;:<br>            return current_sl<br>        elif self.stoploss_type == &#39;trailing&#39;:<br>            # code for trailing stop loss goes here<br>            pass<br>        elif self.stoploss_type == &#39;time-based&#39;:<br>            # code for time-based stop loss goes here<br>            pass<br>        elif self.stoploss_type == &#39;multiple&#39;:<br>            # code for multiple stop loss levels goes here<br>            pass<br>        else:<br>            raise ValueError(&#39;Invalid stoploss_type&#39;)<br><br>   def update_take_profit(self, index, current_tp) -&gt; float:<br>        &quot;&quot;&quot;Updates the take profit price based on the takeprofit_type.&quot;&quot;&quot;<br>        if self.takeprofit_type == &#39;fixed&#39;:<br>            return current_tp<br>        elif self.takeprofit_type == &#39;trailing&#39;:<br>            # code for trailing take profit goes here<br>            pass<br>        elif self.stoploss_type == &#39;time-based&#39;:<br>            # code for time-based take profit goes here<br>            pass<br>        elif self.stoploss_type == &#39;multiple&#39;:<br>            # code for multiple take profit levels goes here<br>            pass<br>        else:<br>            raise ValueError(&#39;Invalid takeprofit_type&#39;)</pre><p>To include this class, we also need to rewrite the function:</p><pre>import pandas as pd<br><br>def add_sl_and_tp(df: pd.Dataframe, <br>                  stop_loss_take_profit: StopLossAndTakeProfit):<br>    &quot;&quot;&quot;<br>    Add stop loss and take profit levels to a dataframe of OHLCV data,<br>    and return the dataframe with sell signals based on these levels.<br><br>    Parameters:<br>    df (pd.Dataframe):      OHLCV data with at least columns <br>                            &#39;Open&#39;,&#39;High&#39;,&#39;Low&#39;,&#39;Close&#39;, and &#39;Volume&#39; and a<br>                            column called &quot;buySignals&quot; that contain<br>                            buy signals (1 = buy, 0 = not buy).<br>    stop_loss_take_profit (StopLossAndTakeProfit): Instance of the<br>                            StopLossAndTakeProfit class.<br><br>    Returns:<br>    pandas dataframe: The original dataframe with one new column added:<br>        - &quot;sellSignal&quot;: The sell signal (1 = sell, 0 = hold) based on the stop loss<br>            and take profit levels.<br>    &quot;&quot;&quot;<br>    # Initialize the &quot;sellSignal&quot; column to 0 (hold position)<br>    df[&#39;sellSignal&#39;] = 0<br><br>    # Create variables for stop loss and take profit levels<br>    # set them to plus and minus infinity so that they won&#39;t<br>    # create sell signal before first buy<br>    stopLoss = float(&quot;-inf&quot;)<br>    takeProfit = float(&quot;inf&quot;)<br>    <br>    # Iterate through the rows of the dataframe to keep track when bought<br>    for index, row in df.iterrows():<br>        if (row[&quot;Close&quot;] &lt; stopLoss) | (row[&quot;Close&quot;] &gt; takeProfit):<br>            # Register sell signal and reset stopLoss &amp; takeProfit<br>            df.at[index, &#39;sellSignal&#39;] = 1<br>            stopLoss = float(&quot;-inf&quot;)<br>            takeProfit = float(&quot;inf&quot;)<br>        elif row[&quot;buySignals&quot;] = 1:<br>            # Asset is bought so set stoploss &amp; takeProfit. As placeholder<br>            # we set it to High and Low prices.<br>            stopLoss = stoploss_takeprofit.get_stop_loss(row[&quot;Low&quot;])<br>            takeProfit = stoploss_takeprofit.get_take_profit(row[&quot;High&quot;])<br>     <br>    # Return dataframe<br>    return df</pre><p><em>I won’t go into strategies for buy signals in this article. For a comprehensive deep dive into the possible strategies for buy signals, please check my other article called: </em><a href="https://medium.com/@the_market_whisperer/all-types-of-technical-trading-strategies-and-how-they-are-done-be5d5a1b04c5"><strong>All types of technical trading strategies and how they are done</strong></a><em>.</em></p><h3><strong>Fixed stop loss and take profit</strong></h3><p>There are several ways a trader might decide where to set the stop loss and take profit levels when using a fixed stop loss and take profit strategy. Some common ways to calculate these levels include Using technical analysis, Setting a risk-reward ratio, and Using psychological levels. All of which I will discuss in this part. <em>Let’s review some examples to consider what changes we should make to the code.</em></p><h4>Using technical analysis:</h4><p>A trader might use technical analysis techniques such as chart patterns, trend lines, or moving averages to identify the price level likely to experience support or resistance. These levels can be used as the stop loss and take profit levels. Traders may use various technical indicators to set stop loss and take profit levels. Some of the most common ones include:</p><p><strong>Moving averages:</strong> A moving average is a trend-following indicator that calculates the average price of a security over a specified time period. A trader may set a stop loss below a long-term moving average, or above a short-term moving average, as a way to protect against a sudden trend reversal.</p><p>For example, <em>suppose a trader is considering buying stock in XYZ company. They use a 50-day moving average and a 200-day moving average to help them determine when to enter and exit the trade.</em></p><p><em>The trader notices that the 50-day moving average is currently above the 200-day moving average, indicating that the stock is in an uptrend. Therefore, they decide to buy the stock and set their stop loss at a level below the 200-day moving average as a way to protect against a sudden trend reversal.</em></p><p><em>The trader also sets their take profit level at a level above the 50-day moving average as a way to take advantage of the upward trend.</em></p><p><em>As the trade progresses, the stock price rises and eventually reaches the take profit level. Finally, the trader sells the stock and closes the trade, realising a profit.</em></p><p>This is just one example of a trader using moving averages to set stop loss and take profit levels. Traders may use many other technical indicators in combination with moving averages to make trade decisions.</p><p><strong>Stochastic oscillator:</strong> The stochastic oscillator is a momentum indicator that compares the closing price of a security to its price range over a specified time period. A trader may set a stop loss above or below the overbought or oversold levels of the stochastic oscillator, depending on the direction of the trade. Here is an example of a trade where a stop loss and take profit levels were decided based on their relationship with the stochastic oscillator:</p><p><em>Let’s say that a trader is considering buying XYZ stock. The trader looks at the chart and sees that the stochastic oscillator is currently in oversold territory (below 20). So, the trader enters a long position and sets a stop loss below the oversold level (around 15). The trader also decides to set a take profit level at overbought (around 80).</em></p><p><em>The trade goes in the trader’s favour, and the price of XYZ stock increases. As the price rises, the stochastic oscillator moves closer to the overbought level. When the stochastic oscillator reaches the overbought level, the take-profit order is triggered, and the trader closes the position for a profit.</em></p><p><strong>Fibonacci</strong> retracement levels: Fibonacci retracement levels are horizontal lines drawn at certain critical levels based on the Fibonacci sequence. A trader may set a stop loss at a key Fibonacci retracement level as a way to protect against a sudden trend reversal.</p><p><em>Let’s say that a trader is long on security and want to set a stop loss and take a profit level using Fibonacci retracement levels.</em></p><p><em>The trader has identified that the security is in an uptrend, and they want to enter a long position at the 38.2% Fibonacci retracement level. They decide to set their stop loss at the 50% Fibonacci retracement level and their take profit at the 23.6% Fibonacci retracement level.</em></p><p><em>The trader enters their long position at the 38.2% Fibonacci retracement level and sets their stop-loss and take-profit levels accordingly.</em></p><p><em>If the security continues to rise and reaches the 23.6% Fibonacci retracement level, the take profit level is triggered, and the trade is closed at a profit.</em></p><p><em>However, if the security starts to decline and reaches the 50% Fibonacci retracement level, the stop loss level is triggered, and the trade is closed at a loss.</em></p><p><strong>Trend lines:</strong> Trend lines are diagonal lines drawn across the price chart to identify the direction of the trend. A trader may set a stop loss above or below a trend line, depending on the direction of the trade.</p><p><em>Let’s say we are trading a stock and have identified an uptrend on the chart. We could draw a trend line connecting the lows of the stock’s price. If we enter a long position and the stock’s price rises, we could set our stop loss below the trend line. This way, if the stock’s price falls and breaks through the trend line, it would trigger our stop loss, and we would exit the trade. For the take-profit level, we could set it at a specific price target or use a similar ( a trend line connecting the highs of the stock’s price ) or a different technical indicator to determine an appropriate level to exit the trade. For example, we could set the take profit level at a resistance level or use the Fibonacci retracement levels to determine an appropriate level to take profit.</em></p><h4>Setting a risk-reward ratio:</h4><p>A trader might set the stop loss at a certain distance from the entry price and the take-profit at a certain multiple of that distance. For example, <em>a trader might set the stop loss at 10% below the entry price and the take profit at 20% above the entry price, resulting in a risk-reward ratio of 1:2.</em></p><h4>Using psychological levels:</h4><p>Some traders believe that specific round numbers or other “psychological” levels can act as strong support or resistance. These levels can be used as the stop-loss and take-profit levels.</p><p>So there is a lot of variation in calculating the stop-loss and take-profit even though it is only about the “fixed” stop-losses and take-profits. We could make a different “type” of stop-loss and take-profit and have if-else statements for every single one. But another alternative would be to include a function when initialising the class so that we can call the process. Each function might have its own need for input; some might need more than others, so we might use the **kwargs attribute, which is a variable length of named attributes that people can add. It turns into a dictionary, so every function should be able to have such a dictionary as input. But this might also be a lot more work, so we <strong>could</strong> (and maybe should) include the dataframe we already have and an index when iterating. We could completely replace the price info since we already have the index.</p><p>So we need to update the class, added variables to track buy_price and current stop-loss and take-profit value.</p><pre>import pandas as pd<br><br>class StopLossAndTakeProfit:<br>   &quot;&quot;&quot;<br>        This class represents a stop-loss and take-profit strategy.<br>         It takes in three arguments:<br>        df: A pd.Dataframe with OHLCV (Open, High, Low, Close, Volume) data.     <br>        stoploss_type: A string indicating the type of stop-loss to use.<br>        stoploss_func: A function that calculates the stop-loss.<br>        takeprofit_type: A string indicating the type of take-profit to use.<br>        takeprofit_func: A function that calculates the take-profit.<br>        It has two methods:<br>        <br>        get_stop_loss(price: float, **kwargs) -&gt; float:         Returns the<br>                                       stop-loss value for the given price.<br>        get_take_profit(price: float, **kwargs) -&gt; float:  Returns the take <br>                                          profit value for the given price.<br>    &quot;&quot;&quot;<br>    def __init__(self,  df: pd.Dataframe,<br>                 stoploss_type: str, stoploss_func: function,<br>                 takeprofit_type: str, takeprofit_func: function):<br>        self.df = df<br>        self.stoploss_type = stoploss_type<br>        self.stoploss_func = stoploss_func<br>        self.takeprofit_type = takeprofit_type<br>        self.takeprofit_func = takeprofit_func<br>        self.buy_price = None<br>        self.current_stoploss = float(&quot;-inf&quot;)<br>        self.current_takeprofit = float(&quot;inf&quot;)<br><br>    <br>    def set_stop_loss(self, index: int):<br>        &quot;&quot;&quot; Updates the stop loss price based on the stoploss_type.&quot;&quot;&quot;<br>        if self.stoploss_type == &#39;fixed&#39;:<br>            self.current_stoploss = self.stoploss_func(df, index)<br>        elif self.stoploss_type == &#39;trailing&#39;:<br>            # code for trailing stop loss goes here<br>            pass <br>        elif self.stoploss_type == &#39;time-based&#39;:<br>            # code for time-based stop loss goes here<br>            pass<br>        elif self.stoploss_type == &#39;multiple&#39;:<br>            # code for multiple stop loss levels goes here<br>            pass<br>        else:<br>            raise ValueError((&#39;Invalid stoploss_type. Only valid values &#39;<br>                              &#39;are &quot;fixed&quot;, &quot;trailing&quot;, &quot;time-based, &#39;<br>                              &#39;and &quot;multiple&quot;.&#39;))<br>    <br>    def set_take_profit(self, index: int) -&gt; float:<br>        &quot;&quot;&quot; Updates the take profit price based on the takeprofit_type.&quot;&quot;&quot;<br>        if self.takeprofit_type == &#39;fixed&#39;:<br>            self.current_takeprofit = self.takeprofit_func(df, index)<br>        elif self.takeprofit_type == &#39;trailing&#39;:<br>            # code for trailing take profit goes here<br>            pass<br>        elif self.stoploss_type == &#39;time-based&#39;:<br>            # code for time-based take profit goes here<br>            pass<br>        elif self.stoploss_type == &#39;multiple&#39;:<br>            # code for multiple take profit levels goes here<br>            pass<br>        else:<br>            raise ValueError((&#39;Invalid takeprofit_type. Only valid values &#39;<br>                              &#39;are &quot;fixed&quot;, &quot;trailing&quot;, &quot;time-based, &#39;<br>                              &#39;and &quot;multiple&quot;.&#39;))<br><br>    def get_stop_loss(self, index: int = None) -&gt; float:<br>        if index is not None:<br>            return self.stoploss_func(df, index)<br>        else:<br>            return self.current_stoploss<br><br>    def get_take_profit(self, index: int = None) -&gt; float:<br>        if index is not None:<br>            return self.takeprofit_func(df, index)<br>        else:<br>            return self.current_takeprofit<br><br>    def update_stop_loss(self, index) -&gt; float:<br>        &quot;&quot;&quot; Updates the stop loss price based on the stoploss_type.&quot;&quot;&quot;<br>        if self.stoploss_type == &#39;fixed&#39;:<br>            pass # no change needed when fixed<br>        elif self.stoploss_type == &#39;trailing&#39;:<br>            # code for trailing stop loss goes here<br>            pass<br>        elif self.stoploss_type == &#39;time-based&#39;:<br>            # code for time-based stop loss goes here<br>            pass<br>        elif self.stoploss_type == &#39;multiple&#39;:<br>            # code for multiple stop loss levels goes here<br>            pass<br>        else:<br>            raise ValueError((&#39;Invalid stoploss_type. Only valid values &#39;<br>                              &#39;are &quot;fixed&quot;, &quot;trailing&quot;, &quot;time-based, &#39;<br>                              &#39;and &quot;multiple&quot;.&#39;))<br><br>   def update_take_profit(self, index) -&gt; float:<br>        &quot;&quot;&quot; Updates the take profit price based on the takeprofit_type.&quot;&quot;&quot;<br>        if self.takeprofit_type == &#39;fixed&#39;:<br>            pass # no change needed when fixed<br>        elif self.takeprofit_type == &#39;trailing&#39;:<br>            # code for trailing take profit goes here<br>            pass<br>        elif self.stoploss_type == &#39;time-based&#39;:<br>            # code for time-based take profit goes here<br>            pass<br>        elif self.stoploss_type == &#39;multiple&#39;:<br>            # code for multiple take profit levels goes here<br>            pass<br>        else:<br>            raise ValueError((&#39;Invalid takeprofit_type. Only valid values &#39;<br>                              &#39;are &quot;fixed&quot;, &quot;trailing&quot;, &quot;time-based, &#39;<br>                              &#39;and &quot;multiple&quot;.&#39;))</pre><p>We might need to use some type checks in the function to add relevant inputs (like the index) in the previous code. Also removed df from the input in the function since it already exists in the StopLossAndTakeProfit class.</p><pre>import pandas as pd<br><br>def add_sl_and_tp(stop_loss_take_profit: StopLossAndTakeProfit):<br>    &quot;&quot;&quot;<br>    Add stop loss and take profit levels to a dataframe of OHLCV data,<br>    and updates the dataframe in it with sell signals based on these levels.<br><br>    Parameters:<br>    stop_loss_take_profit (StopLossAndTakeProfit): Instance of the<br>                            StopLossAndTakeProfit class.<br><br>    This function updates the original dataframe in stop_loss_take_profit with<br>                         one new column added:<br>        - &quot;sellSignal&quot;:  The sell signal (1 = sell, 0 = hold) based on the <br>                         stop loss and take profit levels.<br>    &quot;&quot;&quot;<br>    # Initialize the &quot;sellSignal&quot; column to 0 (hold position)<br>    stoploss_takeprofit.df[&#39;sellSignal&#39;] = 0<br>    <br>    # Iterate through the rows of the dataframe to keep track when bought<br>    for index, row in stoploss_takeprofit.df.iterrows():<br>        in_buy_state = stoploss_takeprofit.buy_price is not None<br>        activate_sl_or_tp = (<br>                              (row[&quot;Close&quot;] <br>                              &lt; stoploss_takeprofit.update_stop_loss) <br>                              | (row[&quot;Close&quot;] <br>                              &gt; stoploss_takeprofit.current_takeprofit)<br>                            )<br>        if in_buy_state &amp; activate_sl_or_tp:<br>            # Register sell signal and reset stopLoss &amp; takeProfit<br>            stoploss_takeprofit.df.at[index, &#39;sellSignal&#39;] = 1<br>            stoploss_takeprofit.current_takeprofit = float(&quot;inf&quot;)<br>            stoploss_takeprofit.current_stoploss = float(&quot;-inf&quot;)<br>            stoploss_takeprofit.buy_price = None <br>        elif row[&quot;buySignals&quot;] = 1 and not in_buy_state:<br>            # Asset is bought so set stoploss &amp; takeProfit. <br>            stoploss_takeprofit.set_stop_loss(index)<br>            stoploss_takeprofit.set_take_profit(index)<br>            stoploss_takeprofit.buy_price = row[&quot;Close&quot;]<br>        else:<br>            # Updates stop-loss and take-profit values if needed<br>            stoploss_takeprofit.update_stop_loss(index)<br>            stoploss_takeprofit.update_take_profit(index)<br>            if (row[&quot;Close&quot;] &lt; stopLoss) | (row[&quot;Close&quot;] &gt; takeProfit):<br>                stoploss_takeprofit.df.at[index, &#39;sellSignal&#39;] = 1<br>                stoploss_takeprofit.current_takeprofit = float(&quot;inf&quot;)<br>                stoploss_takeprofit.current_stoploss = float(&quot;-inf&quot;)<br>                stoploss_takeprofit.buy_price = None<br>            <br>     <br>    # Return dataframe<br>    return df</pre><p>This code should allow for all possible fixed prices. The add_sl_and_tp() function could be added when initialising the rapport. Will consider that later when I get more possible variations through.</p><h3><strong>Trailing stop-loss &amp; take-profit</strong></h3><p>A trailing stop loss is a stop-loss order that adjusts the stop-loss level as the trade moves in the trader’s favour. For example, if a trader buys a stock at $50 and sets a trailing stop loss at $45, the stop-loss will be adjusted to $50 if the stock price increases to $55. This allows the trader to lock in profits as the trade moves in their favour while also protecting against a sudden trend reversal.</p><p>A trailing take profit works in a similar way, except that it adjusts the take profit level as the trade moves in the trader’s favour. For example, if a trader buys a stock at $50 and sets a trailing take profit at $65, the take profit will be adjusted to $70 if the stock price increases to $60. This allows the trader to capture more profits as the trade moves in their favour while also protecting against a sudden trend reversal if it is done together with a trailing stop-loss. The trailing take-profit will only be hit if there is a sudden violent rise in price. So a trailing take-profit will often rely on a good trailing stop-loss.</p><p>There are several factors that a trader may consider when deciding where to set a trailing stop loss and take profit level:</p><h4><strong>Risk tolerance:</strong></h4><p>The trader may want to set a wider stop loss to allow for more volatility in the market or a tighter stop loss to minimise risk.</p><p><em>For example, a trader has a risk tolerance of 2%. This means the trader is willing to accept a 2% loss on their trade if the market moves against them. The trader may set a stop loss at 2% below their entry price to protect against a sudden market move against them. This would be a wider stop loss compared to a trader with a lower risk tolerance, who might set a stop loss at 1% below their entry price, for example. On the other hand, a trader with a higher risk tolerance might set a stop loss at 3% below their entry price, allowing for more volatility in the market. Similarly, the trader may set a take profit level at 2% above their entry price to lock in a profit if the market moves in their favour. This would be a tighter take profit compared to a trader with a higher risk tolerance, who might set a take profit at 3% above their entry price, for example.</em></p><p><em>The stop-loss will then move whenever the price goes up so that the stop-loss is never more than 2% or 1% below the latest close price, so that if the price goes up 5%, then the stop-loss will go up 3%. The stop-loss will not, however, be adjusted down.</em></p><h4>Time horizon:</h4><p>The trader may want to set a wider stop-loss if they are holding the position for a longer period or a tighter stop-loss if they are only holding the position for a short period.</p><p><em>Imagine a trader is considering buying a stock that has been steadily increasing in price over the past few months. They believe the trend will continue, and they want to hold onto the stock for the long term (i.e. several years). In this case, the trader might set a wider stop loss level because they are willing to allow for more volatility in the market over the long term. For example, they might set the stop loss at 10% below the purchase price. This gives the stock more room to fluctuate without triggering a sell signal. And if the</em></p><p><em>On the other hand, imagine a trader is considering buying a stock that has been highly volatile over the past few weeks. They believe the stock is oversold and will bounce back soon, but they are not confident in the company’s long-term prospects. In this case, the trader might set a tighter stop loss level because they are only holding onto the stock for a short period of time. For example, they might set the stop loss at a level that is only 2% below the purchase price. This minimises the trade risk, as the stock will need to drop significantly before the stop loss is triggered.</em></p><p><em>In both these cases, the stop-loss is adjusted if the price continues to go up.</em></p><h4>Market conditions:</h4><p>The trader may want to set a wider stop loss in a more volatile market or a tighter stop loss in a less volatile market.</p><p><em>Imagine a trader considering buying a stock currently trading at $50. The trader believes that the stock has good potential for growth but is aware that the market is currently very volatile due to recent events. In this case, the trader may set a wider stop loss to allow for more volatility in the market. For example, the trader may set a stop loss at $45, which is 10% below the entry price of $50. This allows the trader to stay in the trade for longer, even if the stock experiences short-term price fluctuations. On the other hand, if the market was less volatile, the trader may set a tighter stop loss, such as $47.5, to minimise risk.</em></p><p><em>Volatility can be measured in various ways. Some common methods include:</em></p><ol><li><em>Standard deviation: This measures the dispersion of a set of data from its mean and can be used to indicate how much a security’s price fluctuates over a given time period.</em></li><li><em>Average true range (ATR): This is a technical analysis indicator that measures the degree of price movement, considering both price and volatility. It is often used to set stop loss levels.</em></li><li><em>Historical volatility: This is a measure of the past price movements of a security and can be used to predict future volatility.</em></li><li><em>Implied volatility: This is a measure of the expected volatility of a security’s price, based on the prices of options on that security. It can be used to set stop-loss levels in options trading.</em></li></ol><p><em>The stop-loss can be adjusted with consideration of volatility, or at least it can be adjusted up. I can not imagine a situation where it would make sense to adjust the stop-loss down.</em></p><h4><strong>Bollinger bands:</strong></h4><p>Bollinger bands are a volatility indicator consisting of a moving average and two standard deviation bands above and below. A trader may set a stop loss above or below the Bollinger bands at the time, depending on the direction of the trade.</p><p>For example,<em> suppose a trader is bullish on a particular stock and wants to buy it. The trader notices that the stock’s price has recently been trading within a narrow range, as indicated by the Bollinger bands. The trader sets a stop loss just below the lower Bollinger band in case the stock’s price drops. The trader also sets a take profit level just above the upper Bollinger band, as the trader believes that a breakout above this level could signal that the trend reverses and will go down again.</em></p><p><em>If the trade is successful, the trader could capture any upward price movement within the Bollinger bands and exit the trade before the stock’s price declines. However, if the stock’s price falls below the lower Bollinger band, the stop loss would be triggered, and the trader would exit the trade with a small loss.</em></p><h4><strong>Break-even stop loss</strong>:</h4><p>In this strategy, the trader sets the stop loss at the trade’s entry price once the trade becomes profitable. This ensures that the trader will at least break even on the trade.</p><p><em>Imagine a trader buys a stock at $50 and sets a take profit at $55. The trader may also set a break-even stop loss at $50, which means that once the stock price increases to $50 or more, the stop loss will be adjusted to $50. If the stock price increases to $55 and the take profit is triggered, the trader will have made a profit of $5. If the stock price decreases and the stop loss is triggered at $50, the trader will break even on the trade, as they sold the stock at the same price they bought it for.</em></p><p>How do we change the code to account for all trailing stop-losses and take-profits? To implement a trailing stop-loss/take-profits, you need to keep track of the highest price reached since the position was opened and update the stop-loss level to be a certain percentage below the highest price reached. We could instead keep track of the highest or lowest close price or lowest Low price. Instead of having all these alternatives, we would need to include the index of when the asset last was bought. We could replace <em>self.buy_price</em> with <em>self.buy_index</em> since the buy price can be found with the index. The highest or lowest prices since then can also easily be found.</p><p>The “update” method should also include trailing stop-losses and take-profits. The relevant functions would need to include the current index and the index when bought. I also see that we can get less code by joining together some methods. We can join “fixed” and “trailing” if all the functions accept a buy index. And time-based stop-losses should also be able to decide based on the current index and buy-index. So we can remove the types. The class then gets much simpler.</p><h3>Conclusion</h3><p>The class and function get much simpler with the last changes. Now that I figured out we don’t need the types.</p><pre>import pandas as pd<br><br>class StopLossAndTakeProfit:<br>   &quot;&quot;&quot;<br>        This class represents a stop-loss and take-profit strategy.<br>         It takes in three arguments:<br>        df: A pd.Dataframe with OHLCV (Open, High, Low, Close, Volume) data.<br>        stoploss_func: A function that calculates the stop-loss.<br>                       This function needs to handle three input variables.<br>                       A pandas dataframe, index of the dataframe and the<br>                       buy-index when it was last bought. And should return a<br>                       float which represents the current stoploss price.<br>        takeprofit_func: A function that calculates the take-profit.<br>                       This function needs to handle three input variables.<br>                       A pandas dataframe, index of the dataframe and the<br>                       buy-index when it was last bought. And should return a<br>                       float which represents the current stoploss price.<br> <br>    &quot;&quot;&quot;<br>    def __init__(self,  df: pd.Dataframe,<br>                 stoploss_func: function,<br>                 takeprofit_func: function):<br>        self.df = df<br>        self.stoploss_func = stoploss_func<br>        self.takeprofit_func = takeprofit_func<br>        self.buy_index = None<br>        self.current_stoploss = float(&quot;-inf&quot;)<br>        self.current_takeprofit = float(&quot;inf&quot;)<br><br>    def get_stop_loss(self, index: int = None) -&gt; float:<br>            if self.buy_index is None:<br>                return float(&quot;-inf&quot;)<br>            return self.stoploss_func(self.df, index, self.buy_index)<br><br>    def get_take_profit(self, index: int = None) -&gt; float:<br>            if self.buy_index is None:<br>                return float(&quot;inf&quot;)<br>            return self.takeprofit_func(self.df, index, self.buy_index)<br><br>    def update_stop_loss(self, index) -&gt; float:<br>        &quot;&quot;&quot; Updates the stop loss price.&quot;&quot;&quot;<br>        self.current_stoploss = self.get_stop_loss(index)<br>        return self.current_stoploss<br><br>   def update_take_profit(self, index) -&gt; float:<br>        &quot;&quot;&quot; Updates the take profit price based on the takeprofit_type.&quot;&quot;&quot;<br>        self.current_takeprofit = self.get_take_profit(index)<br>        return self.current_takeprofit<br>        </pre><p>and the function also is much simpler</p><pre>import pandas as pd<br><br>def add_sl_and_tp(stop_loss_take_profit: StopLossAndTakeProfit):<br>    &quot;&quot;&quot;<br>    Add stop loss and take profit levels to a dataframe of OHLCV data,<br>    and updates the dataframe in it with sell signals based on these levels.<br><br>    Parameters:<br>    stop_loss_take_profit (StopLossAndTakeProfit): Instance of the<br>                            StopLossAndTakeProfit class.<br><br>    This function updates the original dataframe in stop_loss_take_profit with<br>                         one new column added:<br>        - &quot;sellSignal&quot;:  The sell signal (1 = sell, 0 = hold) based on the <br>                         stop loss and take profit levels.<br>    &quot;&quot;&quot;<br>    # Initialize the &quot;sellSignal&quot; column to 0 (hold position)<br>    stoploss_takeprofit.df[&#39;sellSignal&#39;] = 0<br>    <br>    # Iterate through the rows of the dataframe to keep track when bought<br>    for index, row in stoploss_takeprofit.df.iterrows():<br>        in_buy_state = stoploss_takeprofit.buy_index is not None<br>        activate_sl_or_tp = (<br>                              (row[&quot;Close&quot;] <br>                              &lt; stoploss_takeprofit.update_stop_loss(index)) <br>                              | (row[&quot;Close&quot;] <br>                              &gt; stoploss_takeprofit.update_take_profit(index))<br>                            )<br>        if in_buy_state &amp; activate_sl_or_tp:<br>            # Register sell signal and reset stop_loss, take_profit <br>            # &amp; buy_index<br>            stoploss_takeprofit.buy_index = None<br>            stoploss_takeprofit.df.at[index, &#39;sellSignal&#39;] = 1<br>            stoploss_takeprofit.current_takeprofit = float(&quot;inf&quot;)<br>            stoploss_takeprofit.current_stoploss = float(&quot;-inf&quot;)<br>        else:<br>            if row[&quot;buySignals&quot;] = 1 and not in_buy_state:<br>                stoploss_takeprofit.buy_index = index<br>            # Updates stop-loss and take-profit values if needed<br>            stoploss_takeprofit.update_stop_loss(index)<br>            stoploss_takeprofit.update_take_profit(index)<br>     <br>    # Return dataframe<br>    return df</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c6cecea06dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modelling BTC price data: ACF & PACF]]></title>
            <link>https://medium.com/@the_market_whisperer/modelling-btc-price-data-acf-pacf-e9c047922799?source=rss-f4bcbcdca7ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9c047922799</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[bitcoin-analysis]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[financial-analysis]]></category>
            <dc:creator><![CDATA[The Market Whisperer]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 16:18:23 GMT</pubDate>
            <atom:updated>2023-01-14T16:18:23.551Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will look into BTC prices. I will download daily BTC/USD data from <a href="https://www.cryptodatadownload.com/">https://www.cryptodatadownload.com/</a>, which has a large variety of free cryptocurrency price data from many different marketplaces.</p><p>Ever since pandas version 0.19.2, it has been possible to pass an URL when reading in data directly; I will include that so that you can follow along much easier.</p><p>BTC price data is time-series data. Time series data is collected over time and typically consists of a sequence of data points measured at successive points. Since time series data is dependent on previous data points, the data is <strong>not</strong> independently distributed. So we can not use any statistical tool that assumes or depend on the data being so-called IID (<a href="https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables">independent and identically distributed</a>).</p><p>Time series has four components we can analyse: <em>trend</em>, <em>seasonality</em>, <em>cyclicality</em> and<em> residual</em>.</p><p><em>Trend</em> refers to the overall direction of a time series data, whether it is increasing or decreasing over time.</p><p><em>Seasonality</em> refers to the systematic fluctuations in data that occur at regular intervals, such as quarterly or annually.</p><p><em>Cyclicality</em> refers to fluctuations in data that occur at irregular intervals, often due to economic conditions.</p><p><em>Residual</em> is the remaining variation in a time series data after the trend, seasonality, and cyclicality have been removed.</p><p>In Python, we can easily visualise each component with the <a href="https://www.statsmodels.org/dev/generated/statsmodels.tsa.seasonal.seasonal_decompose.html">seasonal_decompose</a> model from the statsmodels library:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>from statsmodels.tsa.seasonal import seasonal_decompose<br><br># Choose daily for illustrative purposes, shorter timeframes might tell<br># much more.<br>url=&quot;https://www.cryptodatadownload.com/cdd/Bitstamp_BTCUSD_d.csv&quot;<br># skiprow=1 because the first row is just copyright data<br>df=pd.read_csv(url, skiprows=1)<br># make sure the date is datetime format<br>df[&#39;date&#39;] =  pd.to_datetime(df[&#39;date&#39;], format=&#39;%Y-%m-%d&#39;)<br># make the date column into the index to automate some stuff in <br># seasonal_decompose. Check documentation regarding the &quot;period&quot;<br># parameter if you don&#39;t want to do this and sort ascending<br>df.set_index(&#39;date&#39;, inplace=True)<br>df.sort_index(ascending=True, inplace=True)<br><br># do decomposition and plot it<br>seasonal_decompose(df[&#39;close&#39;]).plot()<br>plt.show()<br></pre><p>If you run that code you will get the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yus8kO3kfdebQlrN5ZCdCg.png" /><figcaption>Time series decomposition of daily BTC data</figcaption></figure><p>At the top subplot, we see plotted raw data from the daily close prices. In the second subplot, we can see the trend. In the third subplot, we can see the seasonality; at the bottom, we have the residual. I also mentioned cyclicality. The bottom residual includes both cyclicality and the actual residual (the noise).</p><p>If you want a closer look at the seasonality or any other part of the data, you can pull out just a range of dates. For example, if you have pandas imported, you can use many methods, but one way is to truncate (cut off) everything before or after some date. For example, if you only want data from 2020 without changing the original df dataframe, then you can do this:</p><pre>df_2020 = df.truncate(before=&#39;2020-01-01&#39;, after=&#39;2020-12-31&#39;)</pre><h3>ACF &amp; PACF</h3><p>In a time series, a trend refers to the direction the data is moving in, either upward, downward, or staying relatively constant. A trend can be observed by looking at the long-term movement of the data, and it is typically characterised by a persistent increase or decrease in the data over a long period of time. In time series analysis, identifying and modelling trends is important because they can significantly impact the forecasting of future values.</p><p>The last figure shows an example of a line plot showing the trend, but it isn’t the only way to understand it. To understand trend better, we have to consider two statistical concepts. The autocorrelation function (ACF), and the partial autocorrelation function (PACF).</p><p><em>The autocorrelation function (ACF)</em> is a statistical measure of the correlation between a time series and its lagged values. It is often used to check for autocorrelation, which is the presence of a pattern in the time series that is correlated with its own past or future values. For example, if a time series exhibits a periodic pattern, it will have high autocorrelation at lag values equal to the period of the pattern. The ACF can be used to identify autocorrelation’s presence and estimate the lag at which it occurs. It is often plotted as a function of lag, with the y-axis representing the correlation magnitude at each lag value.</p><p>It can be plotted with the plot_acf function from statsmodels.graphics.tsaplots. Like this:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>from statsmodels.graphics.tsaplots import plot_acf<br><br># import data<br>url=&quot;https://www.cryptodatadownload.com/cdd/Bitstamp_BTCUSD_d.csv&quot;<br>df=pd.read_csv(url, skiprows=1)<br>df[&#39;date&#39;] =  pd.to_datetime(df[&#39;date&#39;], format=&#39;%Y-%m-%d&#39;)<br>df.set_index(&#39;date&#39;, inplace=True)<br>df.sort_index(ascending=True, inplace=True)<br><br># plot ACF<br>plot_acf(df[&#39;close&#39;])<br>plt.xlabel(&#39;Number of lags&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*7VzejFzft7jmIAvi3fL-hg.png" /><figcaption>ACF plot of BTC price data</figcaption></figure><p>When we see an ACF plot like this where it doesn’t go to zero, it is a good idea to do an ACF plot of the difference (That is also good for other reasons we will come to).</p><pre># create column of difference in price from previous price.<br>df[&#39;price_diff&#39;] = df[&#39;close&#39;].diff()<br>df[&quot;price_diff&quot;].iloc[0] = 0<br><br># plot ACF<br>plot_acf(df[&#39;price_diff&#39;])<br>plt.xlabel(&#39;Number of lags&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*SxNIFRRsTUKnsR3Y48hJLA.png" /><figcaption>ACF plot of BTC price difference</figcaption></figure><p>It has a few significant lags. Very slight negative lag at 1. More obvious lags at 7, 9 and 12. There is no clear seasonality; there are periodic ups and downs, but it is not consistent; this might imply some cyclicality, however. Let’s see what PACF also has to say</p><p><em>The partial autocorrelation function (PACF) </em>is a statistical measure that describes the linear dependence between a time series and its own lagged values, controlling for the values of the time series at all shorter lags. In other words, the PACF measures the correlation between the time series and its lagged values after accounting for any correlation due to intermediate lags. This can be useful for identifying the appropriate lag length for modelling a time series using methods such as autoregressive moving average (ARMA) models.</p><p>It can be plotted with the plot_pacf function from statsmodels.graphics.tsaplots. Assuming you already imported the data like in the last code.</p><pre>from statsmodels.graphics.tsaplots import plot_pacf<br><br># plot PACF<br>plot_pacf(df[&#39;price_diff&#39;])<br>plt.xlabel(&#39;Number of lags&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*Su-iEORhjtegPvA5L7_QmA.png" /><figcaption>PACF plot of BTC price difference</figcaption></figure><p>And let us also do a plot of the prices themselves.</p><pre>from statsmodels.graphics.tsaplots import plot_pacf<br><br># plot PACF<br>plot_pacf(df[&#39;close&#39;])<br>plt.xlabel(&#39;Number of lags&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*ZEB05pY4hlFY5Rn3CmnRSw.png" /><figcaption>PACF plot of BTC prices</figcaption></figure><p>When we interpret ACF and PACF plots, we look for patterns, such as if there are any significant correlations at specific lags. We can see that from the plot when the “dots” are above or below the blue-shaded bands. The shaded area represents the idea that there is more than a 5% chance that random noise created the correlation. In comparison, anything above (positive correlation) or below (negative correlation) has less than a 5% chance of being created by random chance. Another pattern we look for is if there is a decay in the correlation along the lags. A very nice article (<a href="https://spureconomics.com/interpreting-acf-and-pacf-plots/">linked here</a>) that I am going to take the following figures from points out how to see if it is an autoregressive (AR) model or a moving-average model (MA), which by the way, has nothing to do with the moving average indicator we know from financial trading, or at last if it is an autoregressive–moving-average (ARMA) model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*g6c_sThx0cz0ZkJB.png" /><figcaption>This is how it should look if it is an AR Process.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*6jbLFcY_nX3kqSYz.png" /><figcaption>This is how it should look if it is a MA Process.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gsUF-ZjnufgmdmOF.png" /><figcaption>This is how it should look if it is an ARMA Process.</figcaption></figure><p>We can see that on the price difference, both ACF and PACF have significant positive and negative correlations at specific lags, but neither has a decay. While on the price, ACF has decay, and PACF has significant positive and negative correlations at specific lags, which looks like the AR process, so at this point, it looks like the best model. <strong>Except </strong>all of the models require stationarity.</p><h3>Stationarity</h3><p>As we have mentioned before, time series needs some assumptions like IID. But one important assumption in time series models (at least the ones I mentioned) is stationarity. In time series analysis, stationarity refers to the idea that the statistical properties of a time series do not change over time. A stationary time series has a constant mean, variance, and autocorrelation structure over time. This is in contrast to a non-stationary time series, which has a mean, variance, or autocorrelation structure that changes over time.</p><p>There are several ways to define stationarity more formally. One common definition is strict stationarity, which requires that the time series&#39; mean, variance, and autocorrelation structure be constant over time. A slightly weaker definition is second-order stationarity, which only requires that the mean and variance of the time series be constant over time.</p><p>It is often important to test for stationarity in time series data because many statistical techniques, such as ARIMA models, assume that the data are stationary. If the data are non-stationary, these techniques may not be appropriate and alternative approaches may need to be considered.</p><p>There are several ways to test for stationarity in a time series, including the Augmented Dickey-Fuller (ADF) test, the Kwiatkowski-Phillips-Schmidt-Shin (KPSS) test, and the Phillips-Perron (PP) test. These tests involve constructing a test statistic and comparing it to a critical value to determine whether to reject the null hypothesis that the time series is non-stationary. You can perform the <a href="https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.adfuller.html">Augmented Dickey-Fuller</a> (ADF) test and <a href="https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.kpss.html">Kwiatkowski-Phillips-Schmidt-Shin</a> (KPSS) test in Python using the statsmodels library and the <a href="https://arch.readthedocs.io/en/latest/unitroot/generated/arch.unitroot.PhillipsPerron.html">Phillips-Perron </a>(PP) test with the arch library. Here&#39;s an example of how you can do each of these tests in Python. We should test the stationarity of both the price data and the price difference data:</p><pre>import pandas as pd<br>from statsmodels.tsa.stattools import adfuller, kpss<br>from arch.unitroot import PhillipsPerron<br><br># import data<br>url=&quot;https://www.cryptodatadownload.com/cdd/Bitstamp_BTCUSD_d.csv&quot;<br>df=pd.read_csv(url, skiprows=1)<br>df[&#39;date&#39;] =  pd.to_datetime(df[&#39;date&#39;], format=&#39;%Y-%m-%d&#39;)<br>df.set_index(&#39;date&#39;, inplace=True)<br>df.sort_index(ascending=True, inplace=True)<br># Create column for price difference and deal with null values<br>df[&#39;price_diff&#39;] = df[&#39;close&#39;].diff()<br>df[&quot;price_diff&quot;].iloc[0] = 0<br><br><br># Perform the ADF test on prices<br>result_adf = adfuller(df[&#39;close&#39;])<br># Perform the KPSS test on prices<br>result_kpss = kpss(df[&#39;close&#39;])<br># Perform the PP test on prices<br>result_pp = PhillipsPerron(df[&#39;close&#39;])<br>result_pp.fit()<br><br># Check the test statistics to see if weakly stationary<br># null hypothesis = nh<br>adf_is_stationary = result_adf[1] &lt; 0.05 # reject nh<br>kpss_is_stationary = result_kpss[1] &gt;= 0.05 # accept nh<br>pp_is_stationary = result_pp.pvalue &lt; 0.05 # reject nh<br># Print results<br>print(f&quot;&quot;&quot;<br>The following tests consider the price to be stationary:<br>the Augmented Dickey-Fuller (ADF) test: {adf_is_stationary}<br>the Kwiatkowski-Phillips-Schmidt-Shin (KPSS) test: {kpss_is_stationary}<br>the Phillips-Perron (PP) test: {pp_is_stationary}<br>       &quot;&quot;&quot;)<br><br># Perform the ADF test on price differences<br>result_adf = adfuller(df[&#39;price_diff&#39;])<br># Perform the KPSS test on price differences<br>result_kpss = kpss(df[&#39;price_diff&#39;])<br># Perform the PP test on price differences<br>result_pp = PhillipsPerron(df[&#39;price_diff&#39;])<br>result_pp.fit()<br><br># Check the test statistics to see if weakly stationary<br># null hypothesis = nh<br>adf_is_stationary = result_adf[1] &lt; 0.05 # reject nh<br>kpss_is_stationary = result_kpss[1] &gt;= 0.05 # accept nh<br>pp_is_stationary = result_pp.pvalue &lt; 0.05 # reject nh<br># Print results<br>print(f&quot;&quot;&quot;<br>The following tests consider the price differences to be stationary:<br>the Augmented Dickey-Fuller (ADF) test: {adf_is_stationary}<br>the Kwiatkowski-Phillips-Schmidt-Shin (KPSS) test: {kpss_is_stationary}<br>the Phillips-Perron (PP) test: {pp_is_stationary}<br>       &quot;&quot;&quot;)</pre><p><strong>The null hypothesis of the ADF test</strong> is that the time series is non-stationary. If the p-value is less than the desired level of significance (e.g., 0.05), you can reject the null hypothesis and conclude that the time series is stationary. If the p-value is greater than the desired level of significance, you cannot reject the null hypothesis and cannot conclude that the time series is stationary.</p><p><strong>The null hypothesis of the KPSS test</strong> is that the time series is stationary. If the p-value is less than the desired level of significance (e.g., 0.05), you can reject the null hypothesis and conclude that the time series is not stationary. If the p-value is greater than the desired level of significance, you cannot reject the null hypothesis and cannot conclude that the time series is non-stationary.</p><p><strong>The null hypothesis of the PP test </strong>is that the time series is non-stationary. If the p-value is less than the desired level of significance (e.g., 0.05), you can reject the null hypothesis and conclude that the time series is stationary. If the p-value is greater than the desired level of significance, you cannot reject the null hypothesis and cannot conclude that the time series is stationary.</p><p>So what I state in the code isn’t exactly correct. Because only the ADF and PP test claim it is stationary. The KPSS test can only claim that you cannot conclude that it is non-stationary. But the idea is the same.</p><p>The answer I got on the close prices is:</p><pre>The following tests consider the price to be stationary:<br>the Augmented Dickey-Fuller (ADF) test: False<br>the Kwiatkowski-Phillips-Schmidt-Shin (KPSS) test: False<br>the Phillips-Perron (PP) test: False</pre><p>And the answer I got on the price differences is:</p><pre>The following tests consider the price differences to be stationary:<br>the Augmented Dickey-Fuller (ADF) test: True<br>the Kwiatkowski-Phillips-Schmidt-Shin (KPSS) test: True<br>the Phillips-Perron (PP) test: True</pre><h3>Conclusion</h3><p>We can&#39;t build ARMA models if a time series is non-stationary. So we can not use the price on that. The price difference, however, <em>has</em> stationarity. But as mentioned when we talked about ACF and PACF plots, the price difference only fits neatly into some of the models because although both the ACF and the PACF plots have significant positive and negative correlations at several lags, neither of them has a decay in the pattern. This might indicate that the time series has a mixture of different patterns. This makes sense because there are many things that affect the price of bitcoin over just previous prices. All sorts of news and the psychology of traders and so on.</p><p>We need to use more advanced modelling techniques, such as a mixed-frequency model or a state space model, to capture the different patterns in the data. Mixed-frequency and state space models are advanced techniques used to model time series data with complex structures. Here is a short explanation of each of them:</p><h4>Mixed-frequency models:</h4><p>A mixed-frequency model is a time series model designed to handle data with multiple frequencies, such as daily, weekly, or monthly data. This model can analyze time series data with different frequencies, such as when high-frequency data is collected more frequently than low-frequency data. Mixed-frequency models can be used to analyze data from different sources and can be used to estimate the underlying patterns of the data.</p><p>This is the easiest one to use because of Facebook’s open-source Prophet library (<a href="https://facebook.github.io/prophet/">link here</a>) that exists for both Python and R. I will do an article analysing BTC prices with that as well. There are many mixed-frequency models and ways to do it, but Facebook has automated it for us.</p><h4>State space models:</h4><p>A state space model is a type of time series model that is designed to handle data that has complex underlying patterns. These models are based on a set of equations that describe the underlying system that generates the data. State space models are particularly useful for modelling time series data with multiple levels of abstraction, such as when a system with multiple interacting components generates the data. These models can be used to estimate the underlying patterns of the data, even if the data is highly complex and difficult to model.</p><p>I have high hopes for these models. However, it takes more time to deal with. There are many different types of state space models. The Kalman filter, Seasonal AutoRegressive Integrated Moving Average with eXogenous regressors (SARIMAX), Linear state-space models (LSSM), Nonlinear State Space Models (NSSM), Hidden Markov Model (HMM), Partially Observable Markov Decision Process (POMDP), Switching State Space Model (SSSM), Regime Switching State Space Model (RSSSM), Non-Parametric State Space Model (NPSSM), Stochastic Differential Equations (SDE) State Space Model, Jump Diffusion State Space Model, Markov-Switching State Space Model (MS-SSM), Non-Linear Non-Gaussian State Space Model (NLNG-SSM), Jump Markov Linear Quadratic Gaussian (JMLQG) State Space Model, and Hybrid State Space Model (HSSM).</p><p>I will write an article going through the assumptions of each of them and see which fits BTC data. If you feel I made some mistakes, let me know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9c047922799" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All types of technical trading strategies and how they are done]]></title>
            <link>https://medium.com/@the_market_whisperer/all-types-of-technical-trading-strategies-and-how-they-are-done-be5d5a1b04c5?source=rss-f4bcbcdca7ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/be5d5a1b04c5</guid>
            <category><![CDATA[technical-analysis-course]]></category>
            <category><![CDATA[indicators]]></category>
            <category><![CDATA[trading-system]]></category>
            <category><![CDATA[trading-tips]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <dc:creator><![CDATA[The Market Whisperer]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 11:11:17 GMT</pubDate>
            <atom:updated>2023-01-04T17:14:02.522Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will give a high-level overview of all technical analysis trading strategies. <strong>Please tell me if I have overlooked a type of technical trading strategy.</strong> This article is about strategies based on technical analysis. And not other strategies like arbitrage, news-based strategies or even sentiment analysis.</p><p>Technical analysis evaluates securities by analysing statistical trends gathered from trading activity, such as past prices and volume. Technical analysts believe that market trends, as shown by charts and other technical indicators, can predict the future direction of a security. These strategies are mentioned in this article and will include references to books that discuss the strategy.</p><ol><li><a href="#e93a"><strong>Crossover</strong></a></li><li><a href="#8bad"><strong>Divergence</strong></a></li><li><a href="#e928"><strong>Breakout</strong></a></li><li><a href="#a254"><strong>Overbought/oversold</strong></a></li><li><a href="#4882"><strong>Candlestick patterns</strong></a></li><li><a href="#7370"><strong>Double-top and double-bottom</strong></a></li><li><a href="#e062"><strong>Band contraction</strong></a></li><li><a href="#efa2"><strong>Band penetration</strong></a></li><li><a href="#9666"><strong>Channel break pullback</strong></a></li><li><a href="#ae89"><strong>Fake breakout</strong></a></li><li><a href="#b826"><strong>Squeeze play</strong></a></li><li><a href="#915a"><strong>Trend following strategies</strong></a></li><li><a href="#2324"><strong>Trend strength</strong></a></li><li><a href="#c743"><strong>Counter trend strategies</strong></a></li></ol><h3>STRATEGY 1: CROSSOVER</h3><p>For crossover strategies, some useful indicators include moving averages (e.g., simple moving average, exponential moving average), MACD, and Bollinger Bands. A crossover strategy is a type of trading strategy that involves buying or selling a financial instrument based on the crossover of two moving averages (MAs). The most common type of crossover strategy is the “Golden Cross”, which involves buying an asset when its short-term moving average (MA) crosses above its long-term MA, and selling it when the short-term MA crosses below the long-term MA.</p><p>To implement a crossover strategy in trading, you must choose the periods for the MAs and the financial instrument you want to trade. For example, you could use a 50-day MA and a 200-day MA for an asset, buy the asset when the 50-day MA crosses above the 200-day MA, and sell it when the 50-day MA crosses below the 200-day MA.</p><p>There are many variations of crossover strategies, including the “Death Cross” (which involves selling an asset when the short-term MA crosses below the long-term MA), the “Bullish Cross” (which involves buying an asset when the short-term MA crosses above the long-term MA), and the “Bearish Cross” (which involves selling an asset when the short-term MA crosses below the long-term MA).</p><p>Famous traders who have used crossover strategies include Paul Tudor Jones and George Soros. Many books discuss crossover strategies, including “Technical Analysis for Dummies” by Barbara Rockefeller and “The Little Book of Trading” by Michael W. Covel.</p><p>Here is an example Python script that demonstrates a crossover strategy using moving averages and then plots it. It also highlights any bullish (buy) signals in green and any bearish (sell) signals in red:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br><br># Load data<br>data = pd.read_csv(&#39;stock_data.csv&#39;)<br><br># Calculate the fast and slow moving averages<br>fast_ma = data[&#39;Close&#39;].rolling(window=50).mean()<br>slow_ma = data[&#39;Close&#39;].rolling(window=200).mean()<br><br># Create a dataframe to hold the moving averages<br>ma_df = pd.DataFrame({&#39;Fast MA&#39;: fast_ma, &#39;Slow MA&#39;: slow_ma})<br><br># Plot the moving averages<br>ma_df.plot()<br>plt.title(&#39;Moving Averages&#39;)<br>plt.ylabel(&#39;Price&#39;)<br>plt.xlabel(&#39;Date&#39;)<br><br># Identify bullish and bearish crossovers<br>for i in range(len(ma_df)):<br>  if (ma_df[&#39;Fast MA&#39;][i] &gt; ma_df[&#39;Slow MA&#39;][i]) and (ma_df[&#39;Fast MA&#39;][i-1] &lt; ma_df[&#39;Slow MA&#39;][i-1]):<br>    plt.axvline(x=ma_df.index[i], color=&#39;g&#39;)<br>    print(&#39;Bullish crossover at:&#39;, ma_df.index[i])<br>  if (ma_df[&#39;Fast MA&#39;][i] &lt; ma_df[&#39;Slow MA&#39;][i]) and (ma_df[&#39;Fast MA&#39;][i-1] &gt; ma_df[&#39;Slow MA&#39;][i-1]):<br>    plt.axvline(x=ma_df.index[i], color=&#39;r&#39;)<br>    print(&#39;Bearish crossover at:&#39;, ma_df.index[i])<br><br>plt.show()</pre><p>This script loads stock data from a CSV file, calculates the fast- and slow-moving averages and then plots them on a chart. It then identifies bullish and bearish crossovers (where the fast MA crosses above the slow MA for a bullish crossover, and below for a bearish crossover) and highlights them with vertical lines on the chart.</p><h3>STRATEGY 2: DIVERGENCE</h3><p>For divergence strategies, some useful indicators include the RSI, Stochastic Oscillator, and MACD. Divergence is a term used in technical analysis to describe a situation where the price of a security and a technical indicator move in opposite directions. Divergence can be either bullish (indicating a potential reversal to the upside) or bearish (indicating a potential reversal to the downside).</p><p>There are several types of divergence strategies, including:</p><ol><li><em>Regular divergence</em> occurs when the price of an asset makes a new high or low, but the technical indicator does not. Bullish regular divergence occurs when the price makes a new low, but the technical indicator does not, indicating a potential reversal to the upside. Bearish regular divergence occurs when the price makes a new high, but the technical indicator does not, indicating a potential reversal to the downside.</li><li><em>Hidden divergence</em> occurs when the price of an asset and the technical indicator moves in the same direction, but the trend’s strength as indicated by the technical indicator is weaker than the price trend. Bullish hidden divergence occurs when the price makes a new low, but the technical indicator makes a higher low, indicating a potential reversal to the upside. Bearish hidden divergence occurs when the price makes a new high, but the technical indicator makes a lower high, indicating a potential reversal to the downside.</li><li><em>Convergence</em> is in many ways the opposite of divergence, but it is a related consideration which is why I mention it. Convergences occur when the price of an asset and the technical indicator moves in the same direction and at a similar rate. Bullish convergence occurs when the price and the technical indicator both trend higher, indicating a potential continuation of the uptrend. Bearish convergence occurs when the price and the technical indicator both trend lower, indicating a potential continuation of the downtrend.</li></ol><p>Some famous traders who have used divergence strategies include Larry Williams and John Bollinger.</p><p>Several books discuss divergence strategies, including “Trade What You See: How to Profit from Pattern Recognition” by Larry Pesavento and Leslie Jouflas, and “New Trading Dimensions: How to Profit from Chaos in Stocks, Bonds, and Commodities” by Bill Williams.</p><p>Here is an example Python script that demonstrates a divergence strategy using the relative strength index (RSI), and plots bullish (green) and bearish (red) signals:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>from talib import RSI<br><br># Load data<br>data = pd.read_csv(&#39;stock_data.csv&#39;)<br><br># Calculate RSI<br>rsi = RSI(data[&#39;Close&#39;], timeperiod=14)<br><br># Plot the RSI and the stock price<br>plt.plot(data[&#39;Close&#39;], label=&#39;Stock Price&#39;)<br>plt.plot(rsi, label=&#39;RSI&#39;)<br>plt.legend()<br>plt.title(&#39;RSI and Stock Price&#39;)<br>plt.ylabel(&#39;Price&#39;)<br>plt.xlabel(&#39;Date&#39;)<br><br># Identify bullish and bearish divergences<br>for i in range(len(rsi)):<br>  if (rsi[i] &lt; 30) and (data[&#39;Close&#39;][i] &gt; data[&#39;Close&#39;][i-1]):<br>    plt.axvline(x=data.index[i], color=&#39;g&#39;)<br>    print(&#39;Bullish divergence at:&#39;, data.index[i])<br>  if (rsi[i] &gt; 70) and (data[&#39;Close&#39;][i] &lt; data[&#39;Close&#39;][i-1]):<br>    plt.axvline(x=data.index[i], color=&#39;r&#39;)<br>    print(&#39;Bearish divergence at:&#39;, data.index[i])<br><br>plt.show()</pre><p>This script loads stock data from a CSV file, calculates the RSI using the talib library (although there are many ways to get RSI on Python), and plots it on a chart along with the stock price. It then identifies bullish and bearish divergences (where the RSI is in oversold territory (below 30), and the stock price is increasing, or where the RSI is in overbought territory (above 70), and the stock price is decreasing) and highlights them with vertical lines on the chart.</p><h3>STRATEGY 3: BREAKOUT</h3><p>For breakout strategies, some useful indicators include Bollinger Bands, the Donchian Channel, and the Average True Range. A breakout is a price movement through an identified level of resistance or support in a financial market. Breakout strategies are based on the idea that once a resistance or support level is broken, the price will continue to move in the direction of the breakout.</p><p>There are several types of breakout strategies, including:</p><ol><li><em>Range breakout</em> strategies are based on the idea that once the price breaks out of a defined range, it will continue to move in the direction of the breakout. Traders may use technical analysis tools such as trend lines or chart patterns to identify the range and set entry and exit points for the trade.</li><li><em>Trend breakout</em> strategies are based on the idea that once the price breaks out of a defined trend, it will continue to move in the direction of the breakout. Traders may use technical analysis tools such as moving averages or trend lines to identify the trend and set entry and exit points for the trade.</li><li><em>News-based breakout</em> is not really a pure technical indicator, but I will mention it. News-based breakout strategies are based on the idea that once important news is released, the price will break out in the direction of the news. Traders may use fundamental analysis tools such as economic indicators or earnings reports to identify potential news-based breakouts. It might be useful when looking at historical data and trying to identify new patterns to recognise behaviour related to the news.</li></ol><p>Some famous traders who have used breakout strategies include George Soros and Paul Tudor Jones. “The Intelligent Investor” by Benjamin Graham is a book that discusses breakout strategies in depth.</p><p>Here is an example Python script that demonstrates a breakout strategy using the Bollinger Bands:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>from talib import BBANDS<br><br># Load data<br>data = pd.read_csv(&#39;stock_data.csv&#39;)<br><br># Calculate Bollinger Bands<br>upper, middle, lower = BBANDS(data[&#39;Close&#39;], timeperiod=20, nbdevup=2, nbdevdn=2)<br><br># Plot the Bollinger Bands and the stock price<br>plt.plot(data[&#39;Close&#39;], label=&#39;Stock Price&#39;)<br>plt.plot(upper, label=&#39;Upper Band&#39;)<br>plt.plot(middle, label=&#39;Middle Band&#39;)<br>plt.plot(lower, label=&#39;Lower Band&#39;)<br>plt.legend()<br>plt.title(&#39;Bollinger Bands and Stock Price&#39;)<br>plt.ylabel(&#39;Price&#39;)<br>plt.xlabel(&#39;Date&#39;)<br><br># Identify bullish and bearish breakouts<br>for i in range(len(data[&#39;Close&#39;])):<br>  if data[&#39;Close&#39;][i] &gt; upper[i]:<br>    plt.axvline(x=data.index[i], color=&#39;g&#39;)<br>    print(&#39;Bullish breakout at:&#39;, data.index[i])<br>  if data[&#39;Close&#39;][i] &lt; lower[i]:<br>    plt.axvline(x=data.index[i], color=&#39;r&#39;)<br>    print(&#39;Bearish breakout at:&#39;, data.index[i])<br><br>plt.show()</pre><p>This script loads stock data from a CSV file, calculates the Bollinger Bands using the talib library and plots them on a chart along with the stock price. It then identifies bullish and bearish breakouts (where the stock price breaks above the upper Bollinger Band or below the lower Bollinger Band) and highlights them with vertical lines (green for bullish, red for bearish) on the chart.</p><h3>STRATEGY 4: OVERBOUGHT/OVERSOLD</h3><p>For overbought/oversold strategies, some useful indicators include the RSI, Stochastic Oscillator, and the Williams %R. Overbought/oversold strategies are based on the idea that prices in financial markets can become overbought (indicating that they are too high) or oversold (indicating that they are too low) and that these conditions can be used to identify potential reversals.</p><p>There are several types of overbought/oversold strategies, including:</p><ol><li><em>Oscillator-based</em> overbought/oversold strategies use technical indicators such as the relative strength index (RSI) or the stochastic oscillator to identify overbought and oversold conditions. These indicators are based on the idea that prices tend to oscillate between overbought and oversold levels, and reversals are more likely to occur when the indicator reaches these levels.</li><li><em>Mean-reversion</em> overbought/oversold strategies are based on the idea that prices tend to revert to their long-term average or “mean” over time, and that overbought and oversold conditions can be used to identify potential reversals. Traders may use technical analysis tools such as moving averages or Bollinger bands to identify overbought and oversold conditions.</li></ol><p>Some famous traders who have used overbought/oversold strategies include George Soros and Paul Tudor Jones. “The Intelligent Investor” by Benjamin Graham is a book that discusses overbought/oversold strategies in depth.</p><p>Here is an example Python script that demonstrates an overbought/oversold strategy using the Stochastic Oscillator:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>from talib import STOCH<br><br># Load data<br>data = pd.read_csv(&#39;stock_data.csv&#39;)<br><br># Calculate the Stochastic Oscillator<br>stoch = STOCH(data[&#39;High&#39;], data[&#39;Low&#39;], data[&#39;Close&#39;])<br><br># Plot the Stochastic Oscillator and the stock price<br>plt.plot(stoch[0], label=&#39;Stochastic Oscillator&#39;)<br>plt.plot(data[&#39;Close&#39;], label=&#39;Stock Price&#39;)<br>plt.legend()<br>plt.title(&#39;Stochastic Oscillator and Stock Price&#39;)<br>plt.ylabel(&#39;Price&#39;)<br>plt.xlabel(&#39;Date&#39;)<br><br># Identify overbought and oversold levels<br>for i in range(len(stoch[0])):<br>  if stoch[0][i] &gt; 80:<br>    plt.axvline(x=data.index[i], color=&#39;r&#39;)<br>    print(&#39;Overbought at:&#39;, data.index[i])<br>  if stoch[0][i] &lt; 20:<br>    plt.axvline(x=data.index[i], color=&#39;g&#39;)<br>    print(&#39;Oversold at:&#39;, data.index[i])<br><br>plt.show()</pre><p>This script loads stock data from a CSV file, calculates the Stochastic Oscillator using the talib library, and plots it on a chart along with the stock price. It then identifies overbought and oversold levels (where the Stochastic Oscillator is above 80 or below 20) and highlights them with vertical lines on the chart.</p><h3>STRATEGY 5: CANDLESTICK PATTERNS</h3><p>For candlestick pattern strategies, some useful indicators include the Hammer, Doji, and Shooting Star patterns. Candlestick patterns are graphical representations of price action used in technical analysis to identify potential reversals or continuations in the market. Candlestick patterns are based on a security’s open, high, low, and close prices over a specific time period. They can be used with other technical analysis tools to identify potential trades.</p><p>There are several types of candlestick patterns, including:</p><ol><li>Single candlestick patterns: Single candlestick patterns include patterns such as the Doji, which indicates indecision in the market, and the shooting star, which indicates a potential reversal to the downside.</li><li>Multi-candlestick patterns: Multi-candlestick patterns include patterns such as the three white soldiers, which indicates a strong uptrend, and the three black crows, which indicates a strong downtrend.</li></ol><p>Some famous traders who have used candlestick pattern strategies include Steve Nison and Paul Tudor Jones. “Japanese Candlestick Charting Techniques” by Steve Nison is a book that discusses candlestick pattern strategies in depth.</p><p>Here is an example Python script that demonstrates how to identify Candlestick patterns and highlight them on a chart:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>from talib import CDL3BLACKCROWS<br><br># Load data<br>data = pd.read_csv(&#39;stock_data.csv&#39;)<br><br># Calculate the Three Black Crows pattern<br>pattern = CDL3BLACKCROWS(data[&#39;Open&#39;], data[&#39;High&#39;], data[&#39;Low&#39;], data[&#39;Close&#39;])<br><br># Plot the stock price and highlight the pattern<br>plt.plot(data[&#39;Close&#39;], label=&#39;Stock Price&#39;)<br>plt.plot(pattern, &#39;o&#39;, color=&#39;r&#39;, label=&#39;Three Black Crows&#39;)<br>plt.legend()<br>plt.title(&#39;Three Black Crows Candlestick Pattern&#39;)<br>plt.ylabel(&#39;Price&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.show()</pre><p>This script loads stock data from a CSV file, calculates the Three Black Crows pattern using the talib library, and plots it on a chart along with the stock price. The pattern is highlighted with red circles on the chart.</p><p>You can use the ta-lib library to calculate a wide range of Candlestick patterns. For example, you can use the CDL2CROWS, CDL3INSIDE, CDL3LINESTRIKE, or CDL3OUTSIDE functions to calculate the Two Crows, Three Inside Up/Down, Three-Line Strike, or Three Outside Up/Down patterns, respectively.</p><h3>STRATEGY 6: DOUBLE-TOP AND DOUBLE-BOTTOM</h3><p>For double-top and double-bottom strategies, some useful indicators include trend lines and the Volume Weighted Average Price (VWAP), also any Bands/Channels/Envelope indicators. Double-top and double-bottom patterns are chart patterns used in technical analysis to identify potential trend reversals. These patterns are formed when the price of a security reaches a high or low level and then retreats, only to reach the same high or low level again. If the price fails to break through the high or low level on the second attempt, it is considered a double top or double bottom pattern, respectively, and may indicate a potential trend reversal.</p><p>Double top and double bottom patterns are typically confirmed when the price breaks through a specific level, such as a neckline in the case of a double top or a support line in the case of a double bottom. Traders may use technical analysis tools such as trend lines or chart patterns to identify these levels and set entry and exit points for the trade.</p><p>Some famous traders who have used double top/bottom strategies include George Soros and Paul Tudor Jones. “Technical Analysis of the Financial Markets” by John J. Murphy is a book that discusses double top/bottom patterns in depth.</p><p>Here is an example Python script that demonstrates how to use the ta-lib library to identify Double Top and Double Bottom patterns using Keltner Channels:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>from talib import ATR, EMA<br><br># Load data<br>data = pd.read_csv(&#39;stock_data.csv&#39;)<br><br># Calculate the average true range<br>atr = ATR(data[&#39;High&#39;], data[&#39;Low&#39;], data[&#39;Close&#39;], timeperiod=20)<br><br># Calculate the Keltner channel<br>middle = EMA(data[&#39;Close&#39;], timeperiod=20)<br>upper = kc_middle + 2 * atr<br>lower = kc_middle - 2 * atr<br><br><br># Initialize empty list to store buy and sell signals<br>data[&#39;signals&#39;] = &quot;hold&quot;<br><br>double_top = (data[&#39;Close&#39;]&lt;upper) # current high under upper channel<br>double_top = double_top &amp; (data[&#39;Close&#39;].shift(1) &gt; upper.shift(1)) # previous over<br>double_top = double_top &amp; abs(data[&#39;Close&#39;].shift(2) -upper.shift(2))&lt;0.02*data[&#39;Close&#39;] # before that near ~(+/-2%) channel<br>double_top = double_top &amp; (data[&#39;Close&#39;].shift(3) &gt; upper.shift(3)) #before above<br>double_top = double_top &amp; (data[&#39;Close&#39;].shift(4) &lt; upper.shift(4)) #before below<br><br>double_bottom = (data[&#39;Close&#39;]&gt;lower) # current low over lower channel<br>double_bottom = double_bottom &amp; (data[&#39;Close&#39;].shift(1) &lt; lower.shift(1)) # previous under<br>double_bottom = double_bottom &amp; abs(data[&#39;Close&#39;].shift(2) -lower.shift(2))&lt;0.05*data[&#39;Close&#39;] # before that near channel<br>double_bottom = double_bottom &amp; (data[&#39;Close&#39;].shift(3) &lt; lower.shift(3)) #before below<br>double_bottom = double_bottom &amp; (data[&#39;Close&#39;].shift(4) &gt; lower.shift(4)) #before above<br><br>data.loc(double_top, &#39;signals&#39;) = &quot;sell&quot;<br>data.loc(double_bottom, &#39;signals&#39;) = &quot;buy&quot;<br><br># Plot the close prices and the Keltner channel<br>plt.plot(df[&quot;close&quot;], label=&quot;Close&quot;)<br>plt.plot(df[&quot;upper&quot;], label=&quot;Upper&quot;)<br>plt.plot(df[&quot;lower&quot;], label=&quot;Lower&quot;)<br><br># Plot the buy and sell signals<br>plt.scatter(df.index, df[&quot;close&quot;][df[&quot;signal&quot;] == &quot;buy&quot;], color=&quot;green&quot;, marker=&quot;^&quot;)<br>plt.scatter(df.index, df[&quot;close&quot;][df[&quot;signal&quot;] == &quot;sell&quot;], color=&quot;red&quot;, marker=&quot;v&quot;)<br><br># Show the plot<br>plt.legend()<br>plt.show()</pre><p>This script loads stock data from a CSV file, calculates the Keltner Channels and Double Top and Double Bottom patterns (you might find more robust ones that can go over more periods) and plots them on a chart along with the stock price. The patterns are highlighted with red circles (Double Top) for a sell signal and green circles (Double Bottom) as a buy signal on the chart.</p><h3>STRATEGY 7: BAND CONTRACTION</h3><p>For band contraction strategies, some useful indicators include Bollinger Bands, Keltner Channels, and the Donchian Channel. Band contraction is a term used to describe a situation in which the price of a security moves within a narrowing range over a specific period of time. This can be seen on a chart as the price moves between a contracting range of support and resistance levels. Band contraction is often followed by a breakout, in which the price moves outside of the contracting range and continues in the direction of the breakout.</p><p>Band contraction strategies are based on the idea that the price will eventually break out of the contracting range and continue in the direction of the breakout. Traders may use technical analysis tools such as trend lines or chart patterns to identify the contracting range and set entry and exit points for the trade.</p><p>Some famous traders who have used band contraction strategies include George Soros and Paul Tudor Jones. “Technical Analysis of the Financial Markets” by John J. Murphy is a book that discusses band contraction and breakout strategies in depth.</p><p>Here is an example Python script that demonstrates band contraction using Stoller average range channels (STARC):</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import talib<br><br># Load the data<br>data = pd.read_csv(&#39;data.csv&#39;)<br><br># Calculate Stoller average range channels (STARC)<br>sma =  talib.SMA(data[&#39;Close&#39;], timeperiod=20)<br>atr = talib.ATR(data[&#39;High&#39;], data[&#39;Low&#39;], data[&#39;Close&#39;], timeperiod=20)<br>data[&#39;upper_band&#39;] = sma + 2*atr<br>data[&#39;lower_band&#39;] = sma - 2*atr<br>data[&#39;middle_band&#39;] = (data[&#39;upper_band&#39;] + data[&#39;lower_band&#39;] )*0.5<br><br># Identify band contraction<br>data[&#39;contracting&#39;] = np.where((data[&#39;upper_band&#39;] - data[&#39;lower_band&#39;]) &lt; (data[&#39;upper_band&#39;].shift(1) - data[&#39;lower_band&#39;].shift(1)), 1, 0)<br><br># Plot the data<br>plt.plot(data[&#39;Close&#39;])<br>plt.plot(data[&#39;upper_band&#39;])<br>plt.plot(data[&#39;lower_band&#39;])<br>plt.fill_between(data.index, data[&#39;upper_band&#39;], data[&#39;lower_band&#39;], alpha=0.5)<br><br># create buy/sell signals<br>buy = (data[&#39;contracting&#39;] == 1) &amp; (data[&#39;Close&#39;] &gt; data[&#39;middle_band&#39;])<br>sell = (data[&#39;contracting&#39;] == 1) &amp; (data[&#39;Close&#39;] &lt; data[&#39;middle_band&#39;])<br><br># Plot buy/sell signals<br>plt.plot(data.loc[buy, &#39;Close&#39;], &#39;go&#39;)<br>plt.plot(data.loc[sell, &#39;close&#39;], &#39;ro&#39;)<br><br>plt.show()</pre><p>This script calculates the Stoller average range channels for a given data set. Then it identifies when the bands are contracting (i.e., when the difference between the upper and lower bands decreases). When the bands are contracting, and the price is closer to the top, it plots a green “buy” signal. When the bands contract and the price is closer to the bottom, it plots a red “sell” signal.</p><h3>STRATEGY 8: BAND PENETRATION</h3><p>For band penetration strategies, some useful indicators include Bollinger Bands, Keltner Channels, and the Donchian Channel. Band penetration is a term used to describe a situation in which the price of a security moves outside of a range or “band” of support and resistance levels. This can be seen on a chart as the price breaking through a previously established support or resistance level. Band penetration is often followed by a trend, in which the price continues in the direction of the penetration.</p><p>Band penetration strategies are based on the idea that the price will continue in the direction of the penetration and that the previously established support or resistance level will now act as a new support or resistance level. Traders may use technical analysis tools such as trend lines or chart patterns to identify the penetration and set entry and exit points for the trade.</p><p>Some famous traders who have used band penetration strategies include George Soros and Paul Tudor Jones. “Technical Analysis of the Financial Markets” by John J. Murphy is a book that discusses band penetration and trend-following strategies in depth.</p><p>Here is an example Python script that demonstrates a band penetration strategy using Doncian Channels and plots buy/sell signals:</p><pre>import matplotlib.pyplot as plt<br>import pandas as pd<br>import numpy as np<br><br># Load data<br>df = pd.read_csv(&#39;data.csv&#39;)<br><br># Calculate Doncian Channels<br>df[&#39;Upper&#39;] = df[&#39;High&#39;].rolling(window=20, min_periods=1).max()<br>df[&#39;Lower&#39;] = df[&#39;Low&#39;].rolling(window=20, min_periods=1).min()<br>df[&#39;Middle&#39;] = (df[&#39;Upper&#39;] + df[&#39;Lower&#39;])*0.5<br><br># Identify buy/sell signals<br>df[&#39;Position&#39;] = np.where(df[&#39;Close&#39;] &gt; df[&#39;Upper&#39;], 1, <br>                         np.where(df[&#39;Close&#39;] &lt; df[&#39;Lower&#39;], -1, 0))<br>df[&#39;Position&#39;].plot(ylim=[-1.1,1.1])<br><br># Plot Bollinger Bands<br>df[[&#39;Close&#39;, &#39;MA&#39;, &#39;Upper&#39;, &#39;Lower&#39;]].plot(figsize=(10,6))<br>plt.show()</pre><p>In this script, we first calculate the Doncian Channels using the rolling mean and standard deviation of the Close column. We then identify buy/sell signals by checking if the Close price is above the upper band or below the lower band. Finally, we plot the Close price, moving average, upper band, and lower band, and highlight the buy/sell signals with a vertical line.</p><h3>STRATEGY 9: CHANNEL BREAK PULLBACK</h3><p>Some useful indicators for channel break pullback strategies include Bollinger Bands, Keltner Channels, and the Donchian Channel. Channel break pullback strategies are based on the idea that after a security breaks through a channel or range of support and resistance levels, it will pull back or retrace to a certain level before continuing in the direction of the breakout. The purpose of a channel break pullback strategy is to enter a trade at the pullback level in the direction of the breakout, with the expectation that the security will continue in that direction.</p><p>There are several variations of channel break pullback strategies, including:</p><ol><li>Entering the trade at a specific pullback level, such as the 38.2% or 50% retracement level.</li><li>Entering the trade when the security breaks through a specific level of resistance or support.</li><li>Entering the trade on a breakout and then placing a stop-loss order at the pullback level.</li></ol><p>Some famous traders who have used channel break pullback strategies include George Soros and Paul Tudor Jones. “Technical Analysis of the Financial Markets” by John J. Murphy is a book that discusses channel break pullback strategies in depth.</p><p>Here is an example Python script that demonstrates a Channel break pullback strategy using an envelope and plots buy/sell signals</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br><br># Read in data and calculate rolling mean and standard deviation<br>df = pd.read_csv(&#39;data.csv&#39;)<br>df[&#39;rolling_mean&#39;] = df[&#39;price&#39;].rolling(window=20).mean()<br>df[&#39;rolling_std&#39;] = df[&#39;price&#39;].rolling(window=20).std()<br><br># Calculate upper and lower bands<br>df[&#39;upper_band&#39;] = df[&#39;rolling_mean&#39;] + 2 * df[&#39;rolling_std&#39;]<br>df[&#39;lower_band&#39;] = df[&#39;rolling_mean&#39;] - 2 * df[&#39;rolling_std&#39;]<br><br># Initialize buy and sell signals<br>df[&#39;signal&#39;] = 0<br><br># Generate buy signal when price breaks above upper band<br>df.loc[df[&#39;price&#39;] &gt; df[&#39;upper_band&#39;], &#39;signal&#39;] = 1<br><br># Generate sell signal when price breaks below lower band<br>df.loc[df[&#39;price&#39;] &lt; df[&#39;lower_band&#39;], &#39;signal&#39;] = -1<br><br># Plot data<br>plt.plot(df[&#39;price&#39;], label=&#39;Price&#39;)<br>plt.plot(df[&#39;rolling_mean&#39;], label=&#39;Rolling Mean&#39;)<br>plt.plot(df[&#39;upper_band&#39;], label=&#39;Upper Band&#39;)<br>plt.plot(df[&#39;lower_band&#39;], label=&#39;Lower Band&#39;)<br><br># Mark buy and sell signals on plot<br>plt.scatter(df.index[df[&#39;signal&#39;] == 1], df[&#39;price&#39;][df[&#39;signal&#39;] == 1], marker=&#39;^&#39;, c=&#39;g&#39;, label=&#39;Buy&#39;)<br>plt.scatter(df.index[df[&#39;signal&#39;] == -1], df[&#39;price&#39;][df[&#39;signal&#39;] == -1], marker=&#39;v&#39;, c=&#39;r&#39;, label=&#39;Sell&#39;)<br><br>plt.legend()<br>plt.show()</pre><p>This script reads in data from a CSV file, calculates the rolling mean and standard deviation over a window of 20 periods, and uses these values to calculate upper and lower bands. It then generates buy signals when the price breaks above the upper band and sell signals when the price breaks below the lower band. Finally, it plots the data and marks the buy and sell signals on the plot using green triangles and red v-shaped markers, respectively.</p><h3>STRATEGY 10: FAKE BREAKOUT</h3><p>For fake breakout strategies, some useful indicators include Bollinger Bands, Keltner Channels, and the Donchian Channel. Fake breakout strategies are based on the idea that a security’s price may break through a support or resistance level, but then quickly revert to its previous range. This can be seen on a chart as the price breaks through a level, and then quickly moves back within the previously established range. Fake breakouts are also known as false breakouts or false signals.</p><p>There are several variations of fake breakout strategies, including:</p><ol><li>Entering a trade in the opposite direction of the breakout when the security quickly reverts to its previous range.</li><li>Entering a trade in the direction of the breakout, but using a tight stop-loss order to minimise the risk of a false signal.</li><li>Waiting for confirmation of the breakout by watching for a sustained move in the direction of the breakout before entering a trade.</li></ol><p>Some famous traders who have used fake breakout strategies include George Soros and Paul Tudor Jones. “Technical Analysis of the Financial Markets” by John J. Murphy is a book that discusses fake breakout strategies in depth.</p><p>To demonstrate a fake breakout strategy in Python, we can use the pandas library to load in price data from a file or API, and then use matplotlib to plot the data. We can then use various technical analysis techniques, such as trend lines or moving averages, to identify potential fake breakout signals.</p><p>Here is an example Python script that demonstrates a fake breakout strategy using trend lines:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br><br># Load in price data<br>df = pd.read_csv(&quot;price_data.csv&quot;)<br><br># Calculate the 20-day moving average<br>df[&quot;ma20&quot;] = df[&quot;Close&quot;].rolling(20).mean()<br><br><br># current price lower than ma20<br>bear_fake_breakout = (df[&quot;Close&quot;] &lt; df[&quot;ma20&quot;])<br># previous above ma20<br>bear_fake_breakout = bear_fake_breakout &amp; (df[&quot;Close&quot;].shift(1) &gt; df[&quot;ma20&quot;].shift(1))<br># broke above ma20 recently<br>recent_breakout_up = ((df[&quot;Close&quot;].shift(2) &lt; df[&quot;ma20&quot;].shift(2)) | ((df[&quot;Close&quot;].shift(3) &lt; df[&quot;ma20&quot;].shift(3))<br>bear_fake_breakout = bear_fake_breakout &amp; recent_breakout_up<br><br><br># current price higher than ma20<br>bull_fake_breakout = (df[&quot;Close&quot;] &gt; df[&quot;ma20&quot;])<br># previous below ma20<br>bull_fake_breakout = bull_fake_breakout &amp; (df[&quot;Close&quot;].shift(1) &lt; df[&quot;ma20&quot;].shift(1))<br># broke below ma20 recently<br>recent_breakout_down = ((df[&quot;Close&quot;].shift(2) &gt; df[&quot;ma20&quot;].shift(2)) | ((df[&quot;Close&quot;].shift(3) &gt; df[&quot;ma20&quot;].shift(3))<br>bull_fake_breakout = bull_fake_breakout &amp; recent_breakout_down<br><br># Plot data<br>plt.plot(df[&quot;Close&quot;], label=&quot;Close&quot;)<br>plt.plot(df[&quot;ma20&quot;], label=&quot;20-day MA&quot;)<br><br># Mark buy and sell signals on plot<br>plt.scatter(df.index[bull_fake_breakout], df[&#39;Close&#39;][bull_fake_breakout], marker=&#39;^&#39;, c=&#39;g&#39;, label=&#39;Buy&#39;)<br>plt.scatter(df.index[bear_fake_breakout], df[&#39;Close&#39;][bear_fake_breakout], marker=&#39;v&#39;, c=&#39;r&#39;, label=&#39;Sell&#39;)<br><br>plt.legend()<br>plt.show()</pre><p>In this example, we calculate the 20-day moving average of the closing price and then identify fake breakout signals by looking for instances where the price breaks above or below the moving average, but then reverses and closes back within the range of the moving average. We mark these signals on the plot by plotting red dots at the corresponding price data points.</p><p>There are many variations on this strategy that you could explore, such as using different trend lines or moving averages, or looking for different types of reversal patterns. You could also use other technical analysis techniques, such as oscillators or candlestick patterns, to confirm or refine the fake breakout signals.</p><h3>STRATEGY 11: SQUEEZE PLAY</h3><p>For squeeze play strategies, some useful indicators include Bollinger Bands, Keltner Channels, and the Donchian Channel. Squeeze play strategies are based on the idea that a security’s price may be “squeezed” within a range of support and resistance levels and that a breakout from this range is imminent. This can be seen on a chart as the price moving within a narrow range and then breaking through one of the levels, often with a strong move.</p><p>There are several variations of squeeze play strategies, including:</p><ol><li>Entering a trade in the direction of the breakout when the price breaks through a support or resistance level.</li><li>Using technical indicators such as Bollinger Bands or the Keltner Channel to identify when the price is in a squeeze and a breakout is likely.</li><li>Waiting for confirmation of the breakout by watching for a sustained move in the direction of the breakout before entering a trade.</li></ol><p>Some famous traders who have used squeeze play strategies include George Soros and Paul Tudor Jones. “Technical Analysis of the Financial Markets” by John J. Murphy is a book that discusses squeeze play strategies in depth.</p><p>Here is an example Python script that demonstrates a squeeze play strategy using Bollinger Bands and Keltner Channels:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import talib as ta<br><br># Load data into a Pandas DataFrame<br>df = pd.read_csv(&quot;data.csv&quot;)<br><br># Calculate Bollinger Bands<br>df[&quot;bb_upper&quot;], df[&quot;bb_middle&quot;], df[&quot;bb_lower&quot;] = ta.BBANDS(df[&quot;close&quot;], timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)<br><br># Calculate Keltner Channels<br>, , = ta.KC(df[&quot;high&quot;], df[&quot;low&quot;], df[&quot;close&quot;], timeperiod=20, nbdevup=2, nbdevdn=2)<br><br># Calculate the average true range<br>atr = ATR(data[&#39;high&#39;], data[&#39;low&#39;], data[&#39;close&#39;], timeperiod=20)<br><br># Calculate the Keltner channel<br>data[&quot;kc_middle&quot;] = EMA(data[&#39;Close&#39;], timeperiod=20)<br>data[&quot;kc_upper&quot;] = data[&quot;kc_middle&quot;] + 2 * atr<br>data[&quot;kc_lower&quot;] = data[&quot;kc_middle&quot;] - 2 * atr<br><br><br># Plot the data<br>plt.plot(df[&quot;date&quot;], df[&quot;close&quot;], label=&quot;Close&quot;)<br>plt.plot(df[&quot;date&quot;], df[&quot;bb_upper&quot;], label=&quot;Bollinger Band Upper&quot;)<br>plt.plot(df[&quot;date&quot;], df[&quot;bb_middle&quot;], label=&quot;Bollinger Band Middle&quot;)<br>plt.plot(df[&quot;date&quot;], df[&quot;bb_lower&quot;], label=&quot;Bollinger Band Lower&quot;)<br>plt.plot(df[&quot;date&quot;], df[&quot;kc_upper&quot;], label=&quot;Keltner Channel Upper&quot;)<br>plt.plot(df[&quot;date&quot;], df[&quot;kc_middle&quot;], label=&quot;Keltner Channel Middle&quot;)<br>plt.plot(df[&quot;date&quot;], df[&quot;kc_lower&quot;], label=&quot;Keltner Channel Lower&quot;)<br>plt.legend()<br>plt.show()<br><br># Identify squeeze plays<br>squeeze_plays = df[(df[&quot;bb_upper&quot;] &lt; df[&quot;kc_upper&quot;]) &amp; (df[&quot;bb_lower&quot;] &gt; df[&quot;kc_lower&quot;])]<br><br># Mark squeeze plays on the plot<br>plt.plot(squeeze_plays[&quot;date&quot;], squeeze_plays[&quot;close&quot;], &quot;y^&quot;, markersize=10, label=&quot;Squeeze Play&quot;)<br>plt.legend()<br>plt.show()</pre><p>This script first loads the data into a Pandas DataFrame. Then it calculates Bollinger Bands and Keltner Channels for the data, and plots the data and the bands/channels on a chart. It then identifies squeeze plays (i.e., instances where the Bollinger Bands are inside the Keltner Channels) and marks them on the chart with yellow triangle markers.</p><h3>STRATEGY 12: TREND FOLLOWING STRATEGIES</h3><p>For trend following strategies, some useful indicators include moving averages (e.g., simple moving average, exponential moving average), the MACD, and the Parabolic SAR. Trend direction strategies are based on identifying the direction of a security’s price trend and then trading in that direction. These strategies aim to capitalise on the trend’s momentum and are based on the belief that prices tend to move in a particular direction over time.</p><p>There are several variations of trend direction strategies, including:</p><ol><li>Entering a trade in the direction of the trend and using a trailing stop-loss order to ride the trend for as long as possible.</li><li>Entering a trade in the direction of the trend and using technical indicators such as moving averages to identify possible trend reversals.</li><li>Entering a trade in the direction of the trend and using technical analysis techniques such as trend lines or chart patterns to identify key support and resistance levels.</li></ol><p>Some famous traders using trend direction strategies include George Soros and Paul Tudor Jones. “Technical Analysis of the Financial Markets” by John J. Murphy is a book that discusses trend direction strategies in depth.</p><p>Here is an example Python script that demonstrates a trend direction or trend-following strategy using the Moving Average Convergence Divergence (MACD) indicator. This script uses the ta library to calculate the MACD and signal line, and then plots the MACD and signal line with buy and sell signals marked on the plot.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import talib as ta<br><br># Load data and set the date as the index<br>df = pd.read_csv(&quot;data.csv&quot;, index_col=&quot;date&quot;, parse_dates=True)<br><br># Calculate the MACD and signal line<br>macd, signal, macdhist = ta.trend.MACD(df, n_fast=12, n_slow=26, n_sign=9)<br><br># Plot the MACD and signal line<br>plt.plot(macd, label=&quot;MACD&quot;)<br>plt.plot(signal, label=&quot;Signal Line&quot;)<br><br># Mark the buy and sell signals on the plot<br>plt.scatter(macd.index[macd &gt; signal], macd[macd &gt; signal], c=&quot;green&quot;, label=&quot;Buy&quot;)<br>plt.scatter(macd.index[macd &lt; signal], macd[macd &lt; signal], c=&quot;red&quot;, label=&quot;Sell&quot;)<br><br>plt.legend()<br>plt.show()</pre><p>This script assumes that you have a CSV file named “data.csv” in the same directory, with the date column set as the index and the prices in a column named “close”. You can adjust the parameters n_fast, n_slow, and n_sign to change the periods used in the calculation of the MACD and signal line.</p><h3>STRATEGY 13: TREND STRENGTH</h3><p>For trend strength strategies, some useful indicators include the ADX, the Chaikin Oscillator, and the Average Directional Movement Index (ADMI). Trend strength strategies are based on the idea of identifying the strength of a security’s price trend and trading in the direction of the trend based on the strength of the trend. These strategies aim to capitalize on the momentum of strong trends and are based on the belief that prices tend to move in a particular direction over time.</p><p>There are several variations of trend strength strategies, including:</p><ol><li>Entering a trade in the direction of the trend and using a stop-loss order to manage risk.</li><li>Entering a trade in the direction of the trend and using technical indicators such as the Average Directional Index (ADX) to measure the strength of the trend.</li><li>Entering a trade in the direction of the trend and using technical analysis techniques such as trend lines or chart patterns to identify key support and resistance levels.</li></ol><p>Some famous traders who have used trend-strength strategies include George Soros and Paul Tudor Jones. “The Trend Following Bible: How Professional Traders Compound Wealth and Manage Risk” by Andrew Abraham is a book that discusses trend strength strategies in depth.</p><p>Here is an example Python script that demonstrates a trend strength strategy using the Moving Average Convergence Divergence (MACD) indicator and plots buy and sell signals on the plot:</p><pre>import matplotlib.pyplot as plt<br>import pandas as pd<br>import talib as ta<br><br># Load data and set the date as the index<br>df = pd.read_csv(&quot;data.csv&quot;, index_col=&quot;date&quot;, parse_dates=True)<br><br># Calculate the MACD and signal line<br>df[&#39;macd&#39;], df[&#39;signal_line&#39;], macdhist = ta.trend.MACD(df, n_fast=12, n_slow=26, n_sign=9)<br><br># Calculate the difference between the MACD and signal line<br>df[&#39;diff&#39;] = df[&#39;macd&#39;] - df[&#39;signal_line&#39;]<br><br># Create buy and sell signals<br>df[&#39;buy&#39;] = df[&#39;diff&#39;].shift(1) &lt; 0<br>df[&#39;sell&#39;] = df[&#39;diff&#39;].shift(1) &gt; 0<br><br># Plot the close price, MACD and signal line<br>plt.plot(df[&#39;close&#39;], label=&#39;Close&#39;)<br>plt.plot(df[&#39;macd&#39;], label=&#39;MACD&#39;)<br>plt.plot(df[&#39;signal_line&#39;], label=&#39;Signal Line&#39;)<br><br># Plot buy and sell signals<br>plt.scatter(df.index[df[&#39;buy&#39;]], df[&#39;close&#39;][df[&#39;buy&#39;]], marker=&#39;^&#39;, color=&#39;g&#39;)<br>plt.scatter(df.index[df[&#39;sell&#39;]], df[&#39;close&#39;][df[&#39;sell&#39;]], marker=&#39;v&#39;, color=&#39;r&#39;)<br><br># Add legend and show plot<br>plt.legend()<br>plt.show()</pre><p>This script loads a CSV file containing historical data for a financial instrument, calculates the MACD indicator using exponential moving averages with different periods, calculates the signal line using a 9-period exponential moving average of the MACD, calculates the difference between the MACD and signal line, and creates buy and sell signals based on the difference. The script then plots the close price, MACD, and signal line, and marks the buy and sell signals on the plot using green upward triangles and red downward triangles, respectively.</p><h3>STRATEGY 14: COUNTER TREND STRATEGIES</h3><p>For counter-trend strategies, some useful indicators include the RSI, Stochastic Oscillator, and the Williams %R. These strategies aim to capitalise on the momentum of a trend reversal and are based on the belief that prices tend to move in a particular direction over time.</p><p>There are several variations of counter-trend strategies, including:</p><ol><li>Entering a trade in the opposite direction of the trend and using a stop-loss order to manage risk.</li><li>Entering a trade in the opposite direction of the trend and using technical indicators such as moving averages or oscillators to confirm the trend reversal.</li><li>Entering a trade in the opposite direction of the trend and using technical analysis techniques such as trend lines or chart patterns to identify key support and resistance levels.</li></ol><p>Some famous traders who have used counter-trend strategies include Paul Tudor Jones and William Eckhardt. “The Wallaby Trade: Counter-Trend Trading for Stocks, Futures, and Forex” by Rob Booker is a book that discusses counter-trend strategies in depth.</p><p>Here is an example of a Python script that demonstrates a counter-trend strategy using the Average Directional Movement Index (ADX) and plots buy and sell signals on the chart:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import talib<br><br># Load data<br>df = pd.read_csv(&#39;data.csv&#39;)<br><br># Calculate ADX<br>df[&#39;adx&#39;] = talib.ADX(df[&#39;high&#39;], df[&#39;low&#39;], df[&#39;close&#39;], timeperiod=14)<br><br># Set buy and sell signals<br>df[&#39;signal&#39;] = &#39;&#39;<br>df.loc[df[&#39;adx&#39;] &gt; 25, &#39;signal&#39;] = &#39;buy&#39;<br>df.loc[df[&#39;adx&#39;] &lt; 20, &#39;signal&#39;] = &#39;sell&#39;<br><br># Plot chart<br>plt.plot(df[&#39;close&#39;])<br><br># Mark buy and sell signals on chart<br>for i, signal in enumerate(df[&#39;signal&#39;]):<br>    if signal == &#39;buy&#39;:<br>        plt.axvline(i, color=&#39;g&#39;, linestyle=&#39;dotted&#39;)<br>    elif signal == &#39;sell&#39;:<br>        plt.axvline(i, color=&#39;r&#39;, linestyle=&#39;dotted&#39;)<br><br>plt.show()</pre><p>In this example, the ADX is calculated with a time period of 14. When the ADX is above 25, a buy signal is generated. When the ADX is below 20, a sell signal is generated. These signals are plotted on the chart as green dotted lines for buy signals and red dotted lines for sell signals.</p><p><strong>Other indicators and variations can be used for strategies mentioned in this article besides the examples. But now you know how each strategy works and can judge which indicators to use yourself.</strong></p><p><em>Hope you got some use of this!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be5d5a1b04c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Dune Analytics: Understanding raw blockchain data]]></title>
            <link>https://medium.com/@the_market_whisperer/exploring-dune-analytics-understanding-raw-blockchain-data-13f60d3e3346?source=rss-f4bcbcdca7ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/13f60d3e3346</guid>
            <category><![CDATA[cryptocurrency-analysis]]></category>
            <category><![CDATA[dune-analytics]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[polygon-network]]></category>
            <category><![CDATA[polygon]]></category>
            <dc:creator><![CDATA[The Market Whisperer]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 19:12:06 GMT</pubDate>
            <atom:updated>2023-01-03T19:12:06.385Z</atom:updated>
            <content:encoded><![CDATA[<p>Dune Analytics ( <a href="https://dune.com/home">link here</a> ) is the easiest way to explore blockchain data. But it can still be tricky to understand the data because it isn’t well documented what each column means.</p><p>My plan with this article is to give an intro to what blockchain data means so that you can start a bit easier. We are going to explore the Polygon blockchain. To get straight to the query page, <a href="https://dune.com/queries?d=1&amp;category=canonical&amp;blockchain=polygon">you can click this link</a>, but it might be smart to explore the website and figure out how to find it on your own. We will look at raw blockchain data. All the queries should be able to run from the link, however.</p><p><em>Near the bottom, where you can choose the engine, please choose “Dune Engine v2 (Spark SQL)” to follow along. The default at the moment of this writing is “Ethereum”. Any queries I make here might be slightly different with that engine. Although, I won’t test, so it might go fine.</em></p><p>At the time of writing the Polygon blockchain has 5 raw tables (you can click on the name to go straight to the part about it): blocks, creation_traces, logs, tracesand transactions, which I will describe. I will refer to the Ethereum blockchain even though I am looking into the Polygon raw data. Because the Polygon platform operates using the Ethereum blockchain and connects Ethereum-based projects.</p><p><strong>Please notify me if you find any errors.</strong></p><h3>polygon.blocks</h3><p>The table contains information about each Polygon block on the ethereum blockchain. To query the 10 first lines of the table, we can do the following query:</p><pre>SELECT * FROM polygon.blocks LIMIT 10;</pre><p>This will result in 10 rows with the following columns:</p><p>The <strong>time</strong> column contains the timestamp of the block in Unix time format, which is a time format which is the number of milliseconds that have elapsed since January 1, 1970, 00:00:00 (UTC). The <strong>number</strong> column contains the block number. A block number is a sequential number assigned to each block as it is added to the blockchain. The block number is used to identify a specific block in the blockchain.</p><p>The <strong>gas_limit</strong> column contains the maximum amount of “gas that can be used to execute the transactions in the block”. The <strong>gas_used</strong> column contains the actual amount of gas used to execute the transactions in the block. The “gas” referred to in the context of the Ethereum blockchain is a measure of the computational resources required to execute a particular operation or transaction. Every operation or transaction on the Ethereum network requires a certain amount of gas to be executed, and the total amount of gas used by a block is the sum of the gas used by all of the transactions in that block.</p><p>The “gas limit” for a block is the maximum amount of gas used to execute the transactions in that block. This is set by the miners adding the block to the blockchain, and it serves as a way to prevent blocks from using excessive computational resources. The network will reject transactions that exceed the gas limit.</p><p>The <strong>difficulty</strong> column contains the difficulty level of the block, which measures how difficult it was to find the block&#39;s solution (i.e., to &quot;mine&quot; the block). The <strong>total_difficulty</strong> column contains the cumulative difficulty of the block and all of the blocks that came before it. In the context of the Ethereum blockchain, “mining” a block refers to the process of finding a solution for the block, which involves attempting to find a specific value (called a “nonce”) that, when hashed with the block’s data, produces a hash with a certain number of leading zeros.</p><p>The difficulty level controls the rate at which new blocks are added to the blockchain. It is adjusted periodically to ensure that blocks are added to the blockchain at a consistent rate, regardless of the computational power of the miners on the network.</p><p>The specific formula used to calculate the difficulty level for a block is:</p><pre>difficulty = parent_difficulty * (block_time / target_block_time)</pre><p>where parent_difficulty is the difficulty level of the previous block, block_time is the time it took to mine the current block, and target_block_time is the desired block time (i.e., the amount of time that the network aims to have between the mining of each block).</p><p>The <strong>size</strong> column contains the size of the block in bytes. The <strong>base_fee_per_gas</strong> column contains the base fee (in wei) per unit of gas for the block. The base fee is a fixed amount of wei paid for each unit of gas a transaction uses. The base fee is used to incentivise miners to include transactions in the blocks they mine, and it is set by the miners themselves based on the current demand for gas.</p><p>On Polygon, the base fee works in a similar way, but a built-in pricing oracle sets it rather than being set by the miners. The base fee on Polygon is adjusted dynamically based on the demand for gas on the network. But the base fee is in wei (the smallest unit of Ethereum) per unit of gas for the block, which applies to both the Ethereum mainnet and Polygon.</p><p>The <strong>hash</strong> column contains the block&#39;s unique hash, a cryptographic representation of the block&#39;s data. The <strong>parent_hash</strong> column contains the hash of the previous block in the chain.</p><p>The <strong>miner</strong> column contains the Ethereum address of the miner who mined the block. The <strong>nonce</strong> column contains the nonce used to find the solution for the block. Usually, the nonce is a random number, however, on Polygon, it always seems to be 0. I have been told that if the address you use to deploy the contract has not been used, you will get nonce 0. It might have something to do with how Polygon works, in any case, you can ignore this column when it comes to Polygon (as far as I know).</p><p>In summary,</p><ul><li>the <strong>time</strong> column contains the timestamp of the block,</li><li>the <strong>number</strong> column contains the block number,</li><li>the <strong>gas_limit </strong>and <strong>gas_used</strong> columns contain information about the gas usage of the block,</li><li>the <strong>difficulty</strong> and <strong>total_difficulty</strong> columns contain information about the difficulty of the block,</li><li>the <strong>size</strong> column contains the size of the block,</li><li>the <strong>base_fee_per_gas</strong> column contains the base fee per unit of gas for the block (in wei),</li><li>the <strong>hash</strong> and <strong>parent_hash</strong> columns contain the block&#39;s hash and the hash of the previous block,</li><li>the <strong>miner</strong> column contains the Ethereum address of the miner who mined the block,</li><li>and the <strong>nonce</strong> column contains the nonce used to find the solution for the block. Which for whatever reason seems always to be 0 on the Polygon chain.</li></ul><h3>polygon.creation_traces</h3><p>The <strong>creation_traces</strong> table in Dune Analytics is a table that contains information about contract creation transactions on the Ethereum blockchain (including the Polygon mainnet). To query the 10 first lines of the table, we can do the following query:</p><pre>SELECT * FROM polygon.creation_traces LIMIT 10;</pre><p>This will result in 10 rows with the following columns:</p><p>The <strong>block_time</strong> column contains the block’s timestamp in which the contract creation transaction was included, in Unix time format. The <strong>block_numbe</strong>r column contains the block number of the block in which the transaction was included.</p><p>The <strong>tx_hash</strong> column contains the unique hash of the contract creation transaction. The <strong>address</strong> column contains the Ethereum address of the contract that was created.</p><p>The <strong>from </strong>column contains the Ethereum address of the account that initiated the contract creation transaction. The <strong>code</strong> column contains the bytecode of the contract that was created.</p><p>In summary, the creation_traces table in Dune Analytics contains,</p><ul><li>the <strong>block_time</strong> column contains the timestamp of the block,</li><li>the <strong>block_umber</strong> column contains the block number,</li><li>the <strong>tx_hash</strong> column contains the unique hash of the contract creation transaction,</li><li>the <strong>address</strong> column contains the Ethereum address of the contract that was created,</li><li>the <strong>from</strong> column contains the Ethereum address of the account that initiated the contract creation transaction,</li><li>the <strong>code</strong> column contains the bytecode of the contract that was created.</li></ul><h3>polygon.logs</h3><p>The logs table in Dune Analytics is a table that contains information about log events that are emitted by smart contracts on the Ethereum blockchain (including the Polygon mainnet). In the context of the Ethereum blockchain, a log event is a record of an event that occurred within a smart contract. Log events can include data payloads that provide more information about the event, and they can also include topics, which are indexed data fields that can be used to filter log events. To query the 10 first lines of the table, we can do the following query:</p><pre>SELECT * FROM polygon.logs LIMIT 10;</pre><p>This will result in 10 rows with the following columns:</p><p>In Unix time format, the <strong>block_time</strong> column contains the timestamp of the block in which the log event was included. The <strong>block_number</strong> column contains the block number of the block in which the log event was included. The <strong>block_hash</strong> column contains the block’s unique hash in which the log event was included.</p><p>The <strong>contract_address</strong> column contains the Ethereum address of the contract that emitted the log event. The <strong>topic1</strong>, <strong>topic2</strong>, <strong>topic3</strong>, and <strong>topic4</strong> columns contain the topics of the log event. Topics are indexed data fields included in the log event and can be used to filter log events.</p><p>Topics are typically used to classify log events into categories or to tag them with specific metadata. Topics are 32-byte (256 bit) “words” that describe what’s going on in an event. <a href="https://medium.com/mycrypto/understanding-event-logs-on-the-ethereum-blockchain-f4ae7ba50378">Look at this medium article for more information on interpreting and understanding it</a>.</p><p>Because topics are indexed, they can be efficiently searched and filtered using log filters or event listeners. For example, you could create a log filter that only returns log events with a certain topic or an event listener that triggers an action when a log event with a specific topic is emitted.</p><p>The <strong>data</strong> column contains the data payload of the log event. The <strong>tx_hash</strong> column contains the unique hash of the transaction that triggered the log event. The <strong>index</strong> column contains the index of the log event within the block. The <strong>tx_index</strong> column contains the index of the transaction within the block.</p><p><strong>You can use the function </strong><a href="https://web3js.readthedocs.io/en/v1.2.11/web3-eth-abi.html#decodeparameters"><strong>web3.eth.abi.decodeParameters</strong></a><strong>, to decode the log topics and other columns in this table and in the transaction table I will discuss later. All you need is the ABI definition of the data, which you can get from the smart contract and the encoded data. Dune Analytics has many datasets already decoded (</strong><a href="https://dune.com/queries?d=1&amp;category=decoded_project"><strong>you can find them in this link</strong></a><strong>), but what you learn in this article is still useful. And it can be educational to know how it originally was.</strong></p><p>In summary,</p><ul><li>the <strong>block_time</strong> column contains the timestamp of the block,</li><li>the <strong>block_number</strong> column contains the block number,</li><li>the <strong>block_hash</strong> column contains the block’s unique hash in which the log event was included,</li><li>the <strong>contract_address</strong> column contains the Ethereum address of the contract that emitted the log event,</li><li>The <strong>topic1</strong>, <strong>topic2</strong>, <strong>topic3</strong>, and <strong>topic4</strong> columns contain the topics of the log event,</li><li>the <strong>data</strong> column contains the data payload of the log event,</li><li>the <strong>tx_hash</strong> column contains the unique hash of the transaction that triggered the log event,</li><li>the <strong>index</strong> column contains the index of the log event within the block,</li><li>and the <strong>tx_index</strong> column contains the index of the transaction within the block.</li></ul><h3>polygon.traces</h3><p>The traces table in Dune Analytics is a table that contains information about transactions and their associated execution traces on the Ethereum blockchain (including the Polygon mainnet). In the context of the Ethereum blockchain, a trace is a record of the execution of a transaction. Traces provide detailed information about the steps taken during the execution of a transaction, including the calls to other contracts, the reading and writing of storage, and the use of gas.</p><p>Traces can be used to debug and analyse the behaviour of smart contracts, as they provide a detailed record of the execution of a transaction and the interactions with other contracts. Traces can also be used to track the flow of data and the consumption of resources within a contract.</p><p>Traces can be generated for transactions on the Ethereum mainnet and on networks built on Ethereum, such as Polygon (formerly known as Matic Network). Traces can be accessed using tools such as Dune Analytics like we are or Ethereum block explorers. To query the 10 first lines of the table, we can do the following query:</p><pre>SELECT * FROM polygon.traces LIMIT 10;</pre><p>This will result in 10 rows with the following columns:</p><p>The <strong>block_time</strong> column contains the timestamp of the block in which the transaction was included, in Unix time format. The <strong>block_number</strong> column contains the block number of the block in which the transaction was included.</p><p>The <strong>value</strong> column contains the value (in wei) transferred by the transaction. The <strong>gas</strong> column contains the maximum amount of gas allowed to be used by the transaction. The <strong>gas_used</strong> column contains the actual amount of gas that was used by the transaction. The <strong>block_hash</strong> column contains the unique hash of the block in which the transaction was included.</p><p>The <strong>success</strong> column indicates whether the transaction was successful (1) or unsuccessful (0). The <strong>tx_index</strong> column contains the index of the transaction within the block. The <strong>sub_traces</strong> column contains the number of sub-traces (i.e., nested traces) generated by the transaction.</p><p>The <strong>error</strong> column contains an error message if the transaction failed and is null if it was successful. The <strong>tx_success</strong> column indicates whether the transaction was successful (1) or unsuccessful (0). The <strong>tx_hash</strong> column contains the unique hash of the transaction.</p><p>The <strong>from</strong> column contains the Ethereum address of the account that initiated the transaction. The <strong>to</strong> column contains the Ethereum address of the account that received the transaction. The <strong>trace_address</strong> column contains the Ethereum address of the contract that was called by the transaction.</p><p>The <strong>type</strong> column contains the type of trace (e.g., &quot;create&quot;, &quot;call&quot;, &quot;suicide&quot;). The <strong>address</strong> column contains the Ethereum address of the contract that was created or called by the transaction. The <strong>code</strong> column contains the bytecode of the contract that was created or called by the transaction.</p><p>The <strong>call_type</strong> column contains the type of call that was made by the transaction. there are three types of calls that can be made by a transaction: call, delegatecall, and callcode.</p><p>A call is a regular function call to a contract. It allows a contract to call another contract and execute its code. When a contract makes a call to another contract, the calling contract&#39;s storage and balance are not affected, but the called contract&#39;s storage and balance are updated.</p><p>A delegatecall is similar to a call, but it executes the code of the called contract using the storage, balance, and caller of the calling contract. This allows a contract to execute code from another contract while maintaining its own context (i.e., storage, balance, and caller).</p><p>A callcode is similar to a call, but it executes the code of the called contract using the caller of the calling contract and the storage and balance of the called contract. This allows a contract to execute code from another contract while using the called contract&#39;s storage and balance, but maintaining its own caller.</p><p>The <strong>input</strong> column contains the input data for the transaction. The <strong>output</strong> column contains the output data for the transaction. The <strong>refund_address</strong> column contains the Ethereum address of the account that will receive any refund if the transaction is unsuccessful.</p><p>In summary,</p><ul><li>the <strong>block_time</strong> column contains the timestamp of the block,</li><li>the <strong>block_number</strong> column contains the block number,</li><li>the <strong>value</strong> column contains the value (in wei) transferred by the transaction.</li><li>the <strong>gas</strong> column contains the maximum amount of gas allowed to be used by the transaction,</li><li>The <strong>gas_used</strong> column contains the actual amount of gas that was used by the transaction,</li><li>the <strong>block_hash</strong> column contains the unique hash of the block in which the transaction was included,</li><li>the <strong>success</strong> column indicates whether the transaction was successful (1) or unsuccessful (0),</li><li>The <strong>tx_index</strong> column contains the index of the transaction within the block,</li><li>The <strong>sub_traces</strong> column contains the number of sub-traces (i.e., nested traces) generated by the transaction,</li><li>The <strong>error</strong> column contains an error message if the transaction failed and is null if it was successful,</li><li>The <strong>tx_success</strong> column indicates whether the transaction was successful (1) or unsuccessful (0),</li><li>The <strong>tx_hash</strong> column contains the unique hash of the transaction,</li><li>The <strong>from</strong> column contains the Ethereum address of the account that initiated the transaction,</li><li>The <strong>to</strong> column contains the Ethereum address of the account that received the transaction,</li><li>The <strong>trace_address</strong> column contains the Ethereum address of the contract that was called by the transaction,</li><li>The <strong>type</strong> column contains the type of trace (e.g., &quot;create&quot;, &quot;call&quot;, &quot;suicide&quot;),</li><li>The <strong>address</strong> column contains the Ethereum address of the contract that was created or called by the transaction,</li><li>The <strong>code</strong> column contains the bytecode of the contract created or called by the transaction,</li><li>The <strong>call_type</strong> column contains the type of call that was made by the transaction,</li><li>The <strong>input</strong> column contains the input data for the transaction,</li><li>The <strong>output</strong> column contains the output data for the transaction,</li><li>and the <strong>refund_address</strong> column contains the Ethereum address of the account that will receive any refund if the transaction is unsuccessful.</li></ul><h3>polygon.transactions</h3><p>The transactions table in Dune Analytics is a table that contains information about transactions on the Ethereum blockchain (including the Polygon mainnet). A transaction is a record of an event that occurs on the blockchain. Transactions can represent various events, such as the transfer of value (e.g., cryptocurrency, tokens), the execution of a smart contract, or the creation of a new account.</p><p>Transactions are usually initiated by users or programs (e.g., smart contracts) and are broadcast to the network to be included in the blockchain. Transactions are typically validated and processed by network nodes, and once they are included in a block, they become part of the permanent record of the blockchain.</p><p>Transactions typically have associated fees (e.g., gas fees in Ethereum) that are paid to the network in exchange for processing the transaction. These fees are typically used to incentivise network nodes to validate and include the transaction in a block. To query the 10 first lines of the table, we can do the following query:</p><pre>SELECT * FROM polygon.transactions LIMIT 10;</pre><p>This will result in 10 rows with the following columns:</p><p>The <strong>block_time</strong> column contains the timestamp of the block in which the transaction was included, in Unix time format. The <strong>block_number</strong> column contains the block number of the block in which the transaction was included.</p><p>The <strong>value</strong> column contains the value (in wei) transferred by the transaction. The <strong>gas_limit</strong> column contains the maximum amount of gas allowed to be used by the transaction. The <strong>gas_price</strong> column contains the price (in wei) of gas that was paid by the transaction. The <strong>gas_used</strong> column contains the actual amount of gas that was used by the transaction.</p><p>The <strong>max_fee_per_gas</strong> column contains the transaction’s maximum fee (in wei) paid per gas unit. In the Ethereum blockchain, transactions can be assigned different levels of priority based on the fees the sender pays. Higher fees can increase the likelihood of a transaction being processed and included in a block before other transactions. The <strong>max_priority_fee_per_gas</strong> column contains the maximum priority fee (in wei) paid per unit of gas by the transaction. The <strong>priority_fee_per_gas</strong> column contains the actual priority fee (in wei) that was paid per unit of gas by the transaction.</p><p>The priority fee is an additional fee that is paid by a transaction to increase its priority. Transactions with higher priority fees are more likely to be processed and included in a block sooner than transactions with lower priority fees.</p><p>The <strong>nonce</strong> column contains the nonce of the transaction. The <strong>index</strong> column contains the index of the transaction within the block. The <strong>success</strong> column indicates whether the transaction was successful (1) or unsuccessful (0).</p><p>The <strong>from</strong> column contains the Ethereum address of the account that initiated the transaction. The <strong>to</strong> column contains the Ethereum address of the account that received the transaction. The <strong>block_hash</strong> column contains the unique hash of the block in which the transaction was included.</p><p>The <strong>data</strong> column contains the input data for the transaction. This data can be of any type, typically used to provide more context or details about the transaction. For example, if the transaction represents the execution of a smart contract function, the <strong>data</strong> column might contain the parameters for the function call.</p><p>The <strong>hash</strong> column contains the unique hash of the transaction. This hash is used to identify and retrieve the transaction from the blockchain.</p><p>The <strong>type</strong> column contains the type of the transaction. Some common types of transactions in Ethereum are:</p><ul><li>A transfer transaction represents the transfer of value (e.g., cryptocurrency, tokens) from one Ethereum address to another.</li><li>A contract_creation transaction represents the creation of a new smart contract on the Ethereum blockchain. This type of transaction includes the bytecode of the contract and the initial values for its storage.</li><li>A contract_call transaction represents the execution of a function in an existing smart contract on the Ethereum blockchain. This type of transaction includes the contract address and the input data for the function call.</li></ul><p>The <strong>access_list</strong> column contains a list of Ethereum addresses allowed to access the transaction data.</p><p>In summary,</p><ul><li>the <strong>block_time</strong> column contains the timestamp of the block,</li><li>the <strong>block_number</strong> column contains the block number,</li><li>the <strong>value</strong> column contains the value (in wei) transferred by the transaction,</li><li>The <strong>gas_limit</strong> column contains the maximum amount of gas allowed to be used by the transaction,</li><li>The <strong>gas_price</strong> column contains the price (in wei) of gas that was paid by the transaction,</li><li>The <strong>gas_used</strong> column contains the actual amount of gas that was used by the transaction,</li><li>The <strong>max_fee_per_gas</strong> column contains the transaction’s maximum fee (in wei) paid per gas unit,</li><li>The <strong>max_priority_fee_per_gas</strong> column contains the maximum priority fee (in wei) paid per gas unit by the transaction,</li><li>The <strong>priority_fee_per_gas</strong> column contains the priority fee (in wei) paid per unit of gas by the transaction,</li><li>The <strong>nonce</strong> column contains the nonce of the transaction,</li><li>The <strong>index</strong> column contains the index of the transaction within the block,</li><li>The <strong>success</strong> column indicates whether the transaction was successful (1) or unsuccessful (0),</li><li>The <strong>from</strong> column contains the Ethereum address of the account that initiated the transaction,</li><li>The <strong>to</strong> column contains the Ethereum address of the account that received the transaction,</li><li>The <strong>block_hash</strong> column contains the unique hash of the block in which the transaction was included,</li><li>The <strong>data</strong> column contains the input data for the transaction,</li><li>The <strong>hash</strong> column contains the unique hash of the transaction,</li><li>The <strong>type</strong> column contains the type of the transaction (e.g., &quot;transfer&quot;, &quot;contract_creation&quot;, &quot;contract_call&quot;),</li><li>The <strong>access_list</strong> column contains a list of Ethereum addresses allowed to access the transaction data.</li></ul><p><strong>You can use the function </strong><a href="https://web3js.readthedocs.io/en/v1.2.11/web3-eth-abi.html#decodeparameters"><strong>web3.eth.abi.decodeParameters</strong></a><strong>, to decode the hashed columns in the transaction table. All you need is the ABI definition of the data, which you can get from the smart contract and the encoded data. Dune Analytics has many datasets already decoded (</strong><a href="https://dune.com/queries?d=1&amp;category=decoded_project"><strong>you can find them in this link</strong></a><strong>).</strong></p><p><em>Hope you found this useful!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13f60d3e3346" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>