All posts by erickclasen

About erickclasen

This is my Blog for writing about technical items and my other thoughts. I also use it to experiment with WordPress.

Kelly Criterion Paper

ChatGPT tackles dense research papers

Never underestimate life’s beauty.

ChatGPT can help to understand parts of a research paper that require clarification.

In this case the paper happens to be on applying the Kelly criterion to a portfolio of multiple assets.   I was interested in the paper and read through it a few times and understand it pretty well as I have been studying this area recently, including reading Fortune’s Formula by William Poundstone which deals with the Kelly criterion. But, I wanted to make sure my understanding was concrete.  I want to understand it in a way that I can compare what I personally have done in the way of setting up a portfolio. Specifically code that manages an index fund with risk management applied that operates similar the way the Kelly criterion works.

Electronic copy available at: http://ssrn.com/abstract=2259133Kelly criterion for multivariate portfolios: a model-free approach

The process involved to simplify text

By pasting in a section of the paper and asking it to dumb it down a bit and then interacting with it using some followup questions it can help clarify it. ChatGPT can be asked to bring it down to a high school level or alternatively you can tell it an age that you want the understanding to be brought down to.

In this case I also asked it to produce and example using Python code. The code is functional, however there is a few unused variables in it.


Transcript of the ‘conversation’ with ChatGPT

Explain the following in simpler terms, like high school level… Algorithm for the fractional Kelly strategies The strategies that bet less than the Kelly fraction are called fractional Kelly strategies. As we just pointed out, they are less profitable but also less risky. In the case of a univariate portfolio we just decrease the capital fraction invested in the risky asset and shift the released capital to the riskless bond. But for a multivariate portfolio such an approach is ambiguous. Indeed, an investor usually cares about the total fraction of risky assets in his/her portfolio. And s/he can at first proportionally descrease the fractions of all risky assets in u? but then additionally redistribute the capital among the risky assets. If the returns are jointly Gaussian then we shall just proportionally reduce the fractions of the risky assets. Moreover, in this case the strategy with Kelly fraction x := 1/(1 − α) is equivalent to the maximization of the (negative) power utility xα/α, α < 0. But in general this nice property does not hold true (see MacLean et al. [2010] and Davis and Lleo [2012]). For instance7, even if the marginal returns are Gaussian but the marginals are paired by Clayton copula, then the proportional fraction reduction is suboptimal. Imposing additional constraints 0 ≤ ui ≤ x ∀i and ∑n i=1 ui ≤ x we can still use (3) to find the optimal portfolio for a given x. However, (3) may be a bad approximation for the leveraged portfolios or the portfolios that contain assets with possibly very high returns8 (see Appendix 1). Additionally, practitioners usually like having two independent optimization methods: if both of them get similar results then they are plausible. We consider the portfolio optimization under the no leverage and no short selling constraints. A Monte Carlo grope algorithm we employ is as follows: 1. Assume we want to invest x of our capital in risky assets9, x ∈ [0%, 100%]. Choose an initial portfolio so that all fractions of the risky assets are between 0.0 and x and their sum is equal to x. Distributing the capital over all assets equally may be a good start. 2. (Groping step): modify the fractions at random so that the no short selling and no leverage conditions still hold. If the new portfolio yields higher expected growth rate, set it as initial portfolio, otherwise leave initial portfolio unchanged. 3. Repeat Step 2 until portfolio performance stops increasing.

The Kelly strategy is a way to invest money in different assets (like stocks or bonds) in order to make the most profit. The Kelly strategy says that you should invest a certain percentage of your money into each asset, based on how likely that asset is to make a profit. However, this strategy can be risky because if one of your assets doesn’t make as much money as you expected, you can lose a lot of your overall investment.

A fractional Kelly strategy is a way to make the Kelly strategy less risky by investing less money into each asset. For example, instead of following the Kelly strategy exactly, you might only invest 80% of the money that the Kelly strategy suggests. This means you’ll make less profit, but you’ll also be less likely to lose a lot of money.

When you’re using a fractional Kelly strategy for a portfolio (a collection of assets) that has multiple types of assets, it can be tricky to figure out how much to invest in each one. If all of the assets are likely to make similar profits, you can just decrease the percentage you’re investing in each one by the same amount. But if the assets have different levels of risk, you’ll need to adjust the percentages differently.

One way to do this is by using a computer program that simulates how different portfolios would perform. The program starts with a random portfolio and then makes small changes to it, to see if it will make more profit. If the new portfolio is better, the program switches to it and continues making changes. If the portfolio stops improving, the program stops.

This process is called a “Monte Carlo simulation” because it uses random numbers and works like a game of chance. By doing this simulation many times, it will get a portfolio that has a better chance to make a better return. The optimization process will be constraint by no leverage and no short selling, and the final result will be the optimal portfolio.

Would it be possible to use historic data or some kind of model data?

Yes, it is possible to use historic data or model data when using a fractional Kelly strategy. In fact, using historical data is often necessary in order to estimate the expected returns and risks of different assets.

One way to use historic data is by looking at the past performance of the assets. By analyzing the returns of an asset over a certain period of time, you can estimate the expected return and risk of investing in that asset. This information can then be used as input for the simulation algorithm.

Another way is to use financial models to estimate the expected returns and risks of different assets. These models use mathematical equations to describe how the assets should behave based on certain factors, such as economic conditions, market trends, and other variables. By plugging in the relevant information into the model, you can get estimates of the expected returns and risks of investing in different assets. This information can also be used as an input for the simulation algorithm

It’s important to note that, regardless of the input, the simulation and optimization algorithm will still work by exploring different portfolio scenarios under the constraints and looking for the one that will generate a higher expected return.

 

When working with historical data I assume it is going to be simulating trades.

Yes, when working with historical data, it is common to use it to simulate trades and backtest the strategy.

Backtesting is the process of applying a trading strategy to historical data to see how it would have performed in the past. By simulating trades on historical data, you can get an idea of how the strategy would have performed in the past and evaluate the strategy’s performance.

When you’re backtesting a fractional Kelly strategy, you would use historical data on the returns and risks of the assets in your portfolio to estimate the expected returns and risks. You would then use the simulation algorithm to generate different portfolios and apply the fractional Kelly strategy to them. The simulated trades will be compared to actual historical returns and the strategy performance will be evaluated.

It’s important to remember that past performance does not guarantee future results and that backtesting does not take into account all the risks of real-world trading. However, backtesting allows you to check how the strategy behaves over the course of history and how it could have performed if it would have been used in the past. This can give you an idea of how the strategy might perform in the future, and whether it’s worth implementing in a live trading scenario.


So, in essence it is using backtesting on set of assets and adjusting the fraction of each of them up and down randomly to find the best overall gains of the entire portfolio.

Yes, that’s correct! Essentially, backtesting a fractional Kelly strategy involves using historical data on the returns and risks of the assets in your portfolio, and then using a simulation algorithm to generate different portfolios. The algorithm will make random adjustments to the fraction of capital invested in each asset and will evaluate the expected return of each portfolio generated. The goal of this process is to find the portfolio that will generate the best overall gains by adjusting the fraction of capital invested in each assets, that is the one that will have the highest expected return.

In practice, the algorithm will explore the portfolio space by making random changes to the portfolio, according to the constraints and the Kelly strategy, and it will keep track of the best portfolio so far. The algorithm will repeat this process multiple times until it reaches a predefined criteria to stop, such as reaching a certain number of iterations or reaching a level of portfolio performance.

It’s worth noting that the algorithm can explore a large number of different portfolio combinations and therefore it can be a computationally expensive process. But, it allows to find the optimal portfolio given the conditions of the assets, constraints, and the Kelly strategy, and it can also provides insights on how the assets are behaving together.


If the algorithm finds the best returns isn’t this equivalent to the Kelly strategy.

Not exactly, while the fractional Kelly strategy and the algorithm I’ve described are related, they are not the same thing.

The Kelly strategy is a mathematical formula that tells you the optimal percentage of your capital to invest in each asset, given the expected returns and risks of the assets. The formula is based on the idea that you want to maximize your long-term growth rate, and it assumes that you have a perfect estimate of the expected returns and risks of each asset.

The algorithm I described, on the other hand, is a process for finding a good portfolio using the constraints and the Kelly strategy, but it doesn’t follow the formula exactly. Instead, it uses historical data and simulations to estimate the expected returns and risks of the assets, and it explores different portfolio combinations to find the one that generates the highest return. It may find a portfolio that is similar or equivalent to what the Kelly formula would suggest, but it is not guaranteed to do so.

It’s worth noting that the Kelly strategy can be challenging to implement in practice because of the difficulty to estimate the expected return and risk for each asset and because of the Kelly assumption that an individual can reinvest the profits and have no constraints on the bet size. On the other hand, the fractional Kelly algorithm is a more practical approach that can handle different constraints and real-world scenarios, such as leverage and short selling constraints.


Is there a simple example that can be shown with Python code?

Here is a simple example of how you might use Python code to backtest a fractional Kelly strategy:

import numpy as np

# Example data: historical returns and volatilities of three assets
returns = np.array([[0.02, 0.03, 0.01], [0.05, 0.02, 0.04], [0.04, 0.06, 0.03]])
volatilities = np.array([[0.01, 0.02, 0.005], [0.02, 0.01, 0.03], [0.01, 0.03, 0.02]])

# Initialize portfolio with equal fractions of capital invested in each asset
portfolio = np.array([1/3, 1/3, 1/3])

# Set the Kelly fraction (fraction of capital to invest in risky assets)
kelly_fraction = 0.8

# Set the number of simulations to run
num_simulations = 1000

# Set the fractional Kelly fraction
frac_kelly = 0.6

# Initialize a variable to keep track of the maximum portfolio return
best_return = -np.inf

# Run the simulations
for i in range(num_simulations):
    # Randomly adjust the portfolio fractions
    new_portfolio = portfolio + np.random.normal(size=3) * 0.01
    # Make sure the fractions are between 0 and the Kelly fraction
    new_portfolio = np.maximum(new_portfolio, 0)
    new_portfolio = np.minimum(new_portfolio, frac_kelly)
    # Make sure the fractions sum to 1
    new_portfolio = new_portfolio / new_portfolio.sum()
    # Calculate the expected return and volatility of the new portfolio
    expected_return = (new_portfolio * returns).sum()
    expected_volatility = (new_portfolio * volatilities).sum()
    # Update the best portfolio if the new one has a higher return
    if expected_return > best_return:
        portfolio = new_portfolio
        best_return = expected_return

# Print the optimal portfolio fractions
print("Optimal portfolio fractions:", portfolio)

This code is a simple example that shows how you can use Python to backtest a fractional Kelly strategy. The example uses historical returns and volatilities of three assets. The code set the Kelly fraction to 0.8 and the fractional Kelly fraction to 0.6 and runs the simulation 1000 times.

It starts with an initial portfolio that has equal fractions of capital invested in each asset, and then makes small random changes to the portfolio in each simulation. It then checks whether the new portfolio has a higher expected return and if so, it keeps the new portfolio and continue the process. After all the simulations are done, the optimal portfolio fractions are printed.

Keep in mind that this is a very simple example, and in practice, you would need to use more sophisticated methods to estimate the expected returns and risks of the assets, and you would need to use more realistic constraints. Additionally, you would want to test the performance of the algorithm with a variety of scenarios and parameters to validate the strategy.


Is it possible to use a genetic algorithm for this instead of Monte Carlo simulation?

Yes, it is possible to use a genetic algorithm for backtesting a fractional Kelly strategy instead of a Monte Carlo simulation. A genetic algorithm is a type of optimization algorithm that is inspired by the process of natural selection.

Just like the Monte Carlo simulation algorithm that I described earlier, a genetic algorithm would be used to explore the portfolio space and find the portfolio that generates the highest expected return. However, instead of making random changes to the portfolio, a genetic algorithm uses the principles of natural selection to evolve a population of portfolios over time.

Here’s a general overview of how a genetic algorithm for backtesting a fractional Kelly strategy might work:

  1. Start with an initial population of portfolios that are randomly generated and satisfy the constraints of the problem.
  2. Evaluate the fitness of each portfolio in the population. This is usually done by calculating the expected return of each portfolio and use it as the fitness value
  3. Select the best portfolios from the population to “breed” new portfolios. The selection process is usually based on the fitness value of each portfolio.
  4. “Breed” new portfolios by combining the characteristics of the selected portfolios through crossover and mutation operators.
  5. Repeat the process of selection, breeding, and mutation until the performance of the population reaches a predefined stopping criteria.
  6. Return the best portfolio of the final population.

A genetic algorithm can be a powerful optimization technique, and it has the ability to find globally optimal solutions to problems that are difficult to solve using other methods. However, it also has its limitations, such as the difficulty of determining the optimal configuration of parameters and the risk of getting stuck in local optima.

It is also worth noting that, similar to the Monte Carlo simulation, a genetic algorithm would still need to estimate the expected return and risk of each assets, and it would also need to be validated and tested thoroughly with a variety of scenarios and parameters before it is used in a live trading scenario.

sqrt(2) AI

Generating Code With ChatGPT

ChatGPT can generate code by asking for it using plain English. Here are a few examples easy and some harder where it generates code to get the square root of two. It fails to do it via a genetic algorithm although the form of the code is not too bad and looks like it could be debugged and modified to work. For a different spin I asked it to do it using BASH script as well. ChatGPT has some ways to go but it is a world ahead of GPT3.0,2.0 and other generative text models I have used over the last 5 years.
Can you write Python code to get the square root of two?

Certainly! Here is some Python code that you can use to calculate the square root of two:

 import math

# Calculate the square root of two
square_root_of_two = math.sqrt(2)

# Print the result
print(square_root_of_two)

This code uses the sqrt() function from the math module to calculate the square root of a number. In this case, the number is 2, so the code will calculate the square root of two.

The sqrt() function returns the result as a floating point number, which is a type of data that can represent decimal values. The code then prints the result using the print() function, which will output the square root of two to the console.

I hope this helps! Let me know if you have any questions or if you need further assistance.


Can you redo the code using Newton’s method?

Certainly! Here is some Python code that uses Newton’s method to calculate the square root of two:

 # Function to calculate the square root using Newton's method
def square_root(x, guess=1.0):
    # Calculate the next guess using Newton's method
    next_guess = (guess + x / guess) / 2
    
    # Check if the guess is close enough to the actual value
    if abs(next_guess - guess) < 0.00001:
        # If it is, return the result
        return next_guess
    else:
        # If it's not, use the next guess as the new starting point and call the function again
        return square_root(x, next_guess)

# Calculate the square root of two
square_root_of_two = square_root(2)

# Print the result
print(square_root_of_two)

This code defines a function called square_root() that takes two arguments: the number for which you want to calculate the square root (x), and an initial guess for the square root (guess). The function uses Newton’s method to iteratively improve the guess until it is close enough to the actual value, at which point it returns the result.

To calculate the square root of two, you can call the square_root() function with the number 2 as the first argument. The function will then return the square root of two as a floating point number, which you can then print to the console using the print() function.

I hope this helps! Let me know if you have any questions or if you need further assistance.


Can you make Python code using recursion to calculate the square root of two?

Certainly! Here is a Python function that uses recursion to calculate the square root of two:

 def sqrt(x, guess=1.0):
    if abs(guess**2 - x) < 0.00001:
        return guess
    else:
        return sqrt(x, (guess + x/guess)/2)

result = sqrt(2)
print(result)

This function uses the Newton-Raphson method to calculate the square root of a given number x. The function takes an optional initial guess for the square root, which is used as the starting point for the iterative process. The function then calculates a new guess using the formula (guess + x/guess)/2, which is derived from the equation f(guess) = guess^2 - x = 0. The function then checks whether the difference between the new guess and the true value of the square root is small enough, and if it is, it returns the guess. Otherwise, it calls itself with the new guess and continues the iterative process.

This function will continue to iterate until it finds a guess that is close enough to the true value of the square root, at which point it will return the final guess. The function will terminate when the difference between the guess and the true value is small enough, as determined by the abs(guess**2 - x) < 0.00001 condition.

You can try calling the sqrt function with different values of x to see how it works. For example, to calculate the square root of two, you can call sqrt(2).


Can you make Python code to calculate the square root of two using machine learning?

Certainly! Here is a Python function that uses a machine learning model to calculate the square root of two:

 import numpy as np
from sklearn.linear_model import LinearRegression

def sqrt(x):
    # Create training data
    X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
    y = np.array([1, 1.41421356, 1.73205081, 2, 2.23606798])
    
    # Create and fit the model
    model = LinearRegression()
    model.fit(X, y)
    
    # Use the model to predict the square root of x
    return model.predict([[x]])[0]

result = sqrt(2)
print(result)
 

This function uses a linear regression model from the sklearn library to predict the square root of a given number x. The model is trained on a dataset of input-output pairs, where the input is a number and the output is its square root. The model is then used to predict the square root of x by calling the predict method and passing it the value of x as an input.

To use this function, you will need to install the numpy and sklearn libraries


Can you calculate the square root of two using a bash script?

Certainly! Here is a bash script that calculates the square root of two using the bc command-line calculator:

 #!/bin/bash

# Calculate the square root of 2 using the bc calculator
sqrt=$(echo "sqrt(2)" | bc -l)

# Print the result
echo "The square root of 2 is: $sqrt"


To run this script, save it to a file and make it executable using the chmod command:

 chmod +x sqrt.sh

Then you can run the script by calling it:

 ./sqrt.sh

This script uses the bc command-line calculator to calculate the square root of two by passing the expression sqrt(2) to the bc command and using the -l flag to specify that it should use the built-in math library. The result is stored in the sqrt variable and is then printed to the console.

The bc command is a powerful calculator that can perform a wide range of mathematical operations, including arithmetic, algebra, trigonometry, and more. It is often used in bash scripts to perform calculations and manipulate numerical data.


Non Functional code was produced when it was asked to generate the code to do sqrt of 2 using a genetic algorithm. I had asked it to refine code that it generated that ‘ran off the page’ to shorten it. It removed some comments and streamlined the code as well.

Certainly! Here is a shorter version of the Python code that uses a genetic algorithm to find the square root of two:

 import random

def fitness(individual):
    return 1/abs(individual - 2**0.5)

def create_population(size):
    return [random.random() for _ in range(size)]

def select_parent(population, tournament_size):
    random.shuffle(population)
    return max(population[:tournament_size], key=fitness)

def reproduce(parent1, parent2):
    split_point = random.randint(1, len(parent1)-1)
    return parent1[:split_point] + parent2[split_point:]

def mutate(individual):
    mutate_index = random.randint(0, len(individual)-1)
    mutate_value = random.random()
    return individual[:mutate_index] + [mutate_value] + individual[mutate_index+1:]

def evolve(population, retain_percentage, random_select_percentage, mutation_rate):
    retain_length = int(len(population) * retain_percentage)
    random_length = int(len(population) * random_select_percentage)
    sorted_population = sorted(population, key=fitness, reverse=True)
    parents = sorted_population[:retain_length]
    for individual in sorted_population[retain_length:retain_length+random_length]:
        if random.random() < mutation_rate:
            parents.append(individual)
    parents_length = len(parents)
    desired_length = len(population) - parents_length
    children = []
    while len(children) < desired_length:
        parent1 = select_parent(population, tournament_size=5)
        parent2 = select_parent(population, tournament_size=5)
        child = reproduce(parent1, parent2)
        if random.random() < mutation_rate:
            child = mutate(child)
        children.append(child)
    parents.extend(children)
    return parents

def run_genetic_algorithm(population_size=100, generations=100, retain_percentage=0.2, random_select_percentage=0.05, mutation_rate=0.01):
    population = create_population(population_size)
    for _ in range(generations):
        population = evolve(population, retain_percentage, random_select_percentage, mutation_rate)
    return max(population, key=fitness)

result = run_genetic_algorithm()
print(result)
 

This code uses a genetic algorithm to search for the square root of two by generating a population of possible values and iteratively improving them through reproduction, mutation, and selection. The fitness function is used to evaluate the quality of each individual, and the genetic algorithm uses this function to guide the search towards better solutions.

 

Chicken Tenders

Chicken Tenders Monetary Standard

Really? Not sure on this idea, so let’s ask ChatGPT

Could chicken tenders be used as a standard?

Chicken tenders, or strips of chicken breast that are breaded and fried, could not be used as a standard for currency or any other type of financial system.

There are several reasons why chicken tenders (or any other type of food) could not be used as a standard. One reason is that they do not have a stable value. The value of chicken tenders (or any other type of food) can fluctuate based on a variety of factors, including supply and demand, production costs, and market conditions. This makes them an unreliable store of value and an unreliable medium of exchange.

Another reason is that chicken tenders (or any other type of food) do not have a widely recognized value or a widely accepted means of exchange. Unlike fiat currencies, which are issued by governments and accepted as a means of payment in most countries, chicken tenders (or any other type of food) are not recognized as a legitimate form of payment and are not widely accepted as a medium of exchange.

Finally, chicken tenders (or any other type of food) are subject to spoilage and deterioration, which makes them a poor choice as a standard for currency or any other type of financial system.

Overall, it is not practical or feasible to use chicken tenders (or any other type of food) as a standard for currency or any other type of financial system.

Create a stable coin based on chicken tenders.

It would not be practical or feasible to create a stablecoin based on chicken tenders. While it is theoretically possible to create a stablecoin based on any type of asset, including chicken tenders, there are several reasons why it would not be practical or feasible in this case.

One reason is that chicken tenders (or any other type of food) do not have a stable value. The value of chicken tenders (or any other type of food) can fluctuate based on a variety of factors, including supply and demand, production costs, and market conditions. This makes them an unreliable store of value and an unreliable medium of exchange, which would make it difficult to maintain the stability of a stablecoin based on chicken tenders.

Another reason is that chicken tenders (or any other type of food) do not have a widely recognized value or a widely accepted means of exchange. Unlike fiat currencies, which are issued by governments and accepted as a means of payment in most countries, chicken tenders (or any other type of food) are not recognized as a legitimate form of payment and are not widely accepted as a medium of exchange. This would make it difficult for people to use a stablecoin based on chicken tenders in everyday transactions.

Finally, chicken tenders (or any other type of food) are subject to spoilage and deterioration, which would make it difficult to maintain a stablecoin based on chicken tenders over the long term.

Overall, it is not practical or feasible to create a stablecoin based on chicken tenders or any other type of food.


On a more serious note check out The Bitcoin Standard, which might actually work.

Also there are interviews ( by Jordan Peterson and Lex Fridman ) with Saifedean Ammous an Austrian economist who wrote, The Bitcoin Standard: The Decentralized Alternative to Central Banking, see this post … http://erick.heart-centered-living.org/info-links/jordan-peterson-bitcoin-interview/

Precious Metal Accumulation and Distribution

Precious Metal Exchanges

A few examples to get started with…

https://www.coinexchangeny.com
https://libertycoin.com/
https://www.jmbullion.com/

Resources

Silver Dragons

The Silver Dragons channel is about silver stacking, buying silver, silver investing, precious metals, gold investing and anything to do with silver or gold …
https://www.youtube.com/channel/UCucqfNRyBkieAop_LDUqHEg

Yankee Stacking

One New Englander trying to stack silver and gold the “Yankee Way”!Stack silver and gold to hedge against our debt-fueled, fiat currency-based economy that …
https://www.youtube.com/c/YankeeStacking

Tickers on Yahoo Finance, this is where the iPhone gets prices

SI=F Silver Futures next delivery period, close enough to the spot price.
GC=F Gold Futures next delivery period, close enough to the spot price.
DXY (DX-Y.NYB) Dollar Index, strength of the USD against a basket of other currencies, The six currencies included in the USDX are the Euro, Swiss franc, Japanese yen, Canadian dollar, British pound, and Swedish krona. When the dollar goes up, metals go down and vice versa.

Investing Basics

All of the basics of investing apply to not only gold and silver but in general, only this first idea is specific to gold and silver.

Do you buy gold, silver, both?

A general rule for investing that gives a short answer for Gold -v- Silver.

When the ratio of the Gold price divided by the Silver price is…
> 80 Buy Silver
60-80 Buy Both
< 60 Buy Gold
Some people will even pairs-trade (swap) between the two to accumulate more metal over time. As in when > 80 buy silver by selling gold. When < 60 buy gold by selling silver. 60-80 is a neutral zone do nothing.

DCA

The following applies to metals or any other long term investment.

You can’t always predict the right moment to move a large sum into or out of an investment.

For investing it is best to dollar cost average (DCA) in and out of a position. Buying and selling on a periodic basis helps accumulate and distribute at average reasonable prices over the long haul of time. This can be done weekly, monthly, quarterly. And it could be done by considering good prices to buy or sell at, with a buy lower and sell higher plan.

Buy Lower/Sell Higher

The following applies to metals or any other long term investment.

You can’t always pick the bottom or top of a market.

A simple rule is to buy when the price is lower than it has been in a while, buying a local low and the converse on highs. The concept can be used to improve upon the ‘blind’ DCA, buy on a regular periodic basis.
Looking back at the high or low from the past year, or market cycle works fine for picking a reasonable high and low point. Keep buying in small amounts when below a local low and selling small amounts when above ( preferably longer timeframe ) local high. It is not always worth trying to ‘time’ the tops and bottoms of the market as this is very tricky even for sophisticated traders.

Judging Value Simply

The following applies to metals or any other long term investment.

Is it a bargain or overpriced?

When starting out it in investing is hard to judge value, so a quick and easy to spot way is the best way to start to get thinking about value.

A reasonable rule is to use the midpoint between the last big high or low price and keep accumulating up to that midpoint. In this manner you can easily tell that you are buying ‘value’ and not buying the asset when it is overpriced. Then hold the asset until the appropriate market cycle which reaches beyond local highs, preferably higher than a previous high in the future and do the converse, slowly sell above the midpoint which should always be checked out to make sure it is in profitable range. It is easier to sell into a rising market as when the price hits a peak sometimes it can drop violently. Prices tend to fall faster than they rise.

Price Charts

How to view the price and a handy tool, the moving average of price.

Kitco among others has decent charts for metals that have moving averages on them as well. The moving averages are a tool that can help with trading and investing. They act as guides to see to position of the price relative to a slower,smoother version of the price, the average price. These charts can be used to help DCA in and out using the buy lower/sell higher, judging value simply or using the moving averages as described below to use a trading type strategy or to accumulate and distribute for long term investing.

Using charts as a  trading tool example

Moving averages can be used to follow a trend. When the price is above a moving average or even better, a short time average (like 14,30,60 days) is above a long average (200 days) there is an uptrend. It is possible to follow a trend by buying in when the short average crosses the long average and sell when the short average goes below the long average. This is an example of a ‘trade’, specifically a long trade or going long. Technically this is called a Dual Moving Average Crossover. This is just one simple example of many trading styles.

Using charts as a tool to accumulate and distribute example

Moving averages can be also used to accumulate and distribute by looking for lows that are worth DCA-ing in and out on. For example good buys would be in the zone where the following line up, ..

  • short moving average lower (try 30 or days- blue line on Kitco chart) than long moving average. 200 day, green line on Kitco chart), with price lower than both ( buy when 30 or 60 day average below 200, with price below both, blue line below green, with red price below both

This is like buying little nips at a time, buying mini-bottoms. The opposite can be done for distributing….

  •   ( sell when 30 or 60 day average above 200, with price above both, blue line above green, with red price above both ), unless you have a buy and hold forever plan.

https://www.kitco.com/charts/techcharts_gold.html

https://www.kitco.com/charts/techcharts_silver.html

BTC When Bottom

In December 2022, with BTC hovering in the 17K range after the FTX unwind , the question is when is the bottom coming ? Or in other words is BTC in a good range to stack or is more waiting required?

A few thoughts, like I thought about this for too long, hours. What got me going was all these predictions on the business news, 5K,10K,13.5K, whatnot. So a theory stood out based on looking back at history using the MVRV Z-Score and Puell Multiple from lookintobitcoin.com and the Mayer multiple from https://bitcoinition.com/charts/mayer-multiple/

Examine the 2022 low and the last low (Dec 2018 ) on the Puell and Mayer Multiples

Hunting for a low in the Puell and Mayer Multiple charts something interesting jumps out, they both point to a July 2022 time when BTC was around 20K. Looking back to December 2018 when they were both in the same kind of zone and at a bottom the BTC price at 3.2K was a definite good buy. BTC spent a lot of time at 6.5K in the Fall of 2018 and then dropped after the  November 15th, due to a FED rate hike. Confirming by looking at the MVRV Z- Score, the negative zones have seemed to coincide with the prices that are worth accumulating at. Now as of December 2022, all three seem to have all hit their low already and are climbing higher.

Hints at 20K and below

The fact that the Puell and Mayer hit a low in 2022, mid year and both print 20K BTC at least for me, gives a hint. Anything under 20K is pretty good, so hunt those local lows. (Like, buy at the bottom of the 20 day Bollinger Bands or even watch 200 Day Bollinger Bands for a dip around 1.5 SD below the midline. )Yes, the bottom could really go lower than the 15.5K. It certainly would have as the DXY (Dollar Index against a basket f currencies, such as Euro, Yen, CAD, Swiss Franc, Krona, GBP and I am sure I am forgetting one or two more) was pointing down pretty good by the time FTX hit the skids. If the DXY was significantly higher, a drop to 12-13K would not have been out of the question. Ironically, BTC looked like it was just about to move higher when the FTX meltdown crushed it down. It seems almost like some entity was hovering their finger over the push BTC down button waiting to release the FTX news, probably just a coincidence but a strange one though.

Here are the charts, judge for yourself, time will tell on this theory

Makes a lot of good points on BTC versus Fiat and bonus material on FTX

Incentives are the strongest force in the world. They explain why good people do awful things, why smart people do stupid things, and why ordinary people do amazing things. Nearly everyone underestimates how much their own beliefs and actions are influenced by their incentives, many of which are designed to fulfill someone else’s goals. – Morgan Housel

For a 21 year old, he gets it. He seems to have a grasp on monetary policy, gold to fiat history and the place that Bitcoin has in the world and it’s future. Plus he has the guy in the middle frame speechless the whole time, not sure if that’s good or bad but, interesting as I kept waiting to see if he was going to jump in the conversation at some point.

 

Additional thoughts on FTX

Incentives for fraud

The FTX implosion looks to be likely fraud or some kind of massive oversight and/or just some bad incentives. With the wrong incentives people can just plain behave badly. Morgan Housel has a short blog post on incentives that covers this topic better than I can here. But, basically once you create incentives that are tempting, too tempting, people can behave badly. People that normally would not steal or commit fraud start to bargain with themselves and wind up slowly dipping into bad behavior, if they don’t get caught, it keeps going. There are many cases of embezzlement that start as innocent “borrowing” from petty cash. Once no one notices that the cash is going out and not coming back ,over time there is an incentive to dip in more. And then you have these news stories of let’s say, because I remember this happening in a town near where I live, I’ll go with this following. Example: You have a town clerk that gets busted for being on the take to the tune of $30K, it all started slowly with small dips and grows to a big number.

Misjudgement and/or Incompetence

Or is FTX/Alameda more about a big misjudgement or incompetence. After all there are precedents for this. Smart people losing boat loads of money as they have not counted on some kind of fat tail event happening. This even occurred with Nobel Prize winners, freshly minted in 1997, Myron Shoales ( Of the Black-Scholes option pricing formula fame ) and Robert Merton ( also part of the  the same famous formula as a contributor ) when in 1998 John Merriweather’s LTCM, Long Term Capital Management imploded as they were seriously over-betting. They were heavily leveraged at the time, which is OK to a point, but they didn’t diversify enough so when things went wrong, the leverage actually went up, when they should have manually dialed it down. What happened at the time was that in 1998 Russia defaulted on it’s debt which LTCM was invested in but they also were invested in the same way with other foreign debt. Well, once one country defaults, it casts a shadow on the rest of the foreign debt as people start to get a bit paranoid as to who might default next. So if you are LTCM and you have a bunch of positions in this same kind of sovereign bonds all over the world, you are certainly not diversified  enough ( they might have thought this all sovereign bond debt was uncorrelated somehow, that bonds would never fall in unison) and if this chunk is a big part of your portfolio and it tanks guess what, bad news fast.

Death Spiral

With LTCM and others,  you get a situation where you have to liquidate something before a margin call happens, usally it’s good stuff that you might want to hold otherwise. This can depress prices of those assets. Soon a firm can get in a situation where the best description would be a reverse hedge and the losses mount on both sides of the trade. With leverage, large leverage 30,60X, it quickly consumes the real capital available. If you try to ask for more capital at this point, nervous lenders may sense panic and then the gig is up. Once lending banks or any other credit line smells something ‘funny’ in the air, panic calls for more capital, through price movements, insider info, whatever, they and other competitors will start to work against a firm like LTCM. They can trade against it and bleed it dry even faster, or they might start dumping the same assets pushing price down more and dry up any liquidity for a firm like LTCM to sell into. Then the problem grows so big that Fed has an emergency meeting and either puts other banks up to the challenge, the creditors, to carve up the carcass and potentially hold the assets until a better time to unload, or worst of all like in Lehman Brothers and etc, the taxpayer gets the bill, or QE happens, which generates inflation, just another tax.

LTCM could have taken the market down much like what happened 10 years later. A excellent course on how the economic collapse of 2008 played out is available at Khan Academy for free as all the material there is, Current Economics

Something like this could have happened at FTX, to much leverage and some fraud with users money, over-betting on the market as it was going into a down-cycle and they couldn’t get out of the dive. If this was a bull market, this kind of stunt might have worked out. Worst of all seems like they used their own FTT token as collateral. It seems like a real conflict of interest, if not just a bad idea as you have created what could be best described as a type of recursive risk. A risk that becomes riskier and you take on more risk. A few more anecdotes from LTCM thanks to one of my favorite books, William Poundstone’s Fortune’s Formula….

  • LTCM lost $4.4B from it’s peak, the partners aloe had dropped about $1.8B. The entire fund had shriveled to $28M in weeks.
  • Robert Merton (1997 Nobel Prize Winner) lost as much as $100M.
  • Larry Hilibrand took out a $24M loan to increase his stake in the fund, leverage on top of leverage. His net worth went from $100M to $20M in debt thanks to the loan. He requested a bailout from the banks carving up LTCM known as the consortium, they said no.

More Interesting FTX Reads

https://www.coindesk.com/layer2/2022/12/02/sam-bankman-frieds-self-incrimination-tour/

https://www.coindesk.com/layer2/2022/11/30/ftxs-collapse-was-a-crime-not-an-accident/

FTX Contagion Slowly Being Revealed

A good interview on this FTX issue is one between C.J Wilson and Josh Olszewicz. It’s well worth seeing them pick this FTX issue apart further.

Blockchain example slide

Proof of Work why use it and why does it use energy

Proof of Work

Proof of work relates to mining of cryptocurrency. It uses computing resources to solve a mathematical puzzle of sorts that takes a lot of compute power to solve but a minimum amount of power to verify that it has been completed. It is an example of a one way function. Easy to go one way but hard to go in the other. Imagine throwing a glass of water in the ocean, now imagine getting all of that water and only that water back out, like running a film backwards, might be impossible. The closer the one way function is to the glass in the ocean example the more secure a blockchain can be made. Why is that? Because it would take so much effort to mutate or corrupt the blockchain that it is not even worth trying.

Brilliant Idea, from Anti-SPAM to Blockchain

In the case of Bitcoin, mining occurs across thousands of nodes that can easily verify that the “work’ has been done and as long as there is a > 50% consensus among mining nodes , then the block is deemed valid and the nodes accept it and move on to the next block of transactions. So it would take an enormous amount of computing power to ‘fake’ a block and create a duplicate spend or a spend that pays an entity some unearned (Bitcoin) BTC, stealing it effectively. That in essence is the brilliance of Bitcoin and it’s pseudonymous creator Satoshi Nakamoto. All the ideas are not original, there was once an idea to use proof of work to prevent spam in email in the mid 1990s when SPAM became a nuisance. For regular uses it would delay the email by a few seconds, for a spammer sending out 1000’s of emails their computer would slow down to much to make it worth it. Satoshi Nakamoto took this idea and applied it to Bitcoin.

The chain part of block chain

On top of this, proof of work  that secures a single block, every block contains the hash of the previous block making it extremely hard to ‘fake’ out and create old blocks over as many hashes would have to be faked. So the longer the chain the more secure older transactions become as they become harder and harder to undo , or fake out.

Hashing in Cryptocurrency

Hashing is the key. Hashing is used in several ways in cryptocurrency.(toward the end of this post a second use is covered) . When mining a block a hash is generated for that block, a SHA256 hash. But not just any hash works. It has to be lower than a specific number determined by the difficulty adjustment, the so called target hash. This changes periodically to keep the outputs of blocks on the block chain, a giant electronic ledger of transactions, blocks are produced very 10 minutes on average. This also limits how many transactions can occur in a given time period. Blocks contain a finite number of transactions and they come out at period intervals, so there are only so many made per day. For Bitcoin this limits the daily transaction to something like around 300000. Other cryptocurrencies do better in this regard (but, buyer beware, they are beholden to companies or individuals that created them,so not independent from control like Bitcoin), so do layer 2 solutions like the Lightning network for Bitcoin. in the future most likely only large infrequent transactions will occur on Bitcoin main chain. With other solutions like the Lightning network or other cryptocurrencies serving to move money like PayPal or a Point Of Sale network, or Swift for that matter.

To create the special hash know as the target hash that meets the difficulty requirement means creating a hash that is lower than a specific 256 bit number. It contains a bunch of zeros at the beginning. This is done by add what is called a nonce ( just a random string will work, used just once  to make the hash come out lower than the target) to the block of transactions and computing the hash. The nonce can be a completely random string or a sequence of numbers tried in order, it really doesn’t matter. The only requirement is that whatever it is it creates a hash output that is lower than the number, target hash, specified by the difficulty requirement. In mining the first node that obtains this number will broadcast the result on the BTC network, all mining nodes will check it (hash the block and see if they agree, quick and easy to do), if it’s OK, the block becomes accepted added to the chain and that miner, the one who solved the hash, gets the block reward along with the fees for all the transactions that have been validated in the block. And, all nodes move on to the next block.

The hash itself

A typical block hash would look something like this…

00000000000000000007cd983a54a4eaf969d79961681fa2fa41eff0aba4a168

Notice all the zeros. With 256 byte number, using SHA256, it is hexadecimal where every number is 0-15 it takes a while to arrive at a number like this. Basically all the nodes that handle the blockchain that are mining are trying to get a ‘low’ number by changing the nonce.

Energy

This takes a lot of computing power and therefore energy. And, this is the complaint when it comes to cryptocurrency that are mined such as Bitcoin. The energy used to mine Bitcoin is equal to that of a small country. But, it has to be remembered that the whole financial technology sector of the economy still dwarfs the energy use of Bitcoin. Just imagine all of the ATMs alone that are plugged in all over the world, the computers running in the banks, heating, other electric and etc. Also, Bitcoin can be mined using energy that is otherwise orphaned. Meaning energy that can not be used for anything else. An example is natural gas and a petroleum well that might normally be flared off. Instead of flaring it off, it could be burned in a gas turbine turning a generator and run mining equipment. The mining equipment could be connected via Cell network or Satellite if no wire are available in a remote location. It is a way of burning a fuel at the source and generating value from it that otherwise would go to waste.

Proof of Work Example

Just a simple example of using a nonce along with a string ‘hello’ in this case and then printing out the resulting hashes of the new compound string of hello+nonce.

As more zeroes are required it gets harder and harder to find a nonce that will satisfy the requirement. To find the first hash with one zero at the start it takes 28 tries, ‘hello28’.

To get 8 leading zeroes it takes hello1202655595  = 1202655595 tries, on fairly regular computer it took from 2022-11-19 15:42 to 2022-11-19 16:48. Just over 1 hour.

Proof of Work Here it comes, ready…

I can give you the hash…

00000000e0d103722c6e172e145d15b9e909e109b47b30d741911bdb3cf3da84

and the string….

hello1202655595

….and this is proof that work was done. You can prove it. It took work to get this result, the computer ‘did’ something hard. It takes almost no energy and time to verify that the hash above is generated by hello1202655595, so it is cheap to verify but expensive to produce.

By ‘stamping’ this result into the blocks on the blockchain, hash of previous block into every block, it is very hard (glass of water back out the ocean hard) to create a forgery or do some other type of nastiness to the blockchain. Proof of Work secures the blockchain.

(Python code at the bottom of this post)

erick@OptiPlex-7010:~/python/hashing$ python3 multi-pow-hash-of-string.py 
Enter String to hash: hello
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
2022-11-19 15:42:15.173991 1 hello28 02a13c40ba00dc0fb199d3cbe5b01be59d937775890243fd411bdf001935ffc8
2022-11-19 15:42:15.175116 2 hello227 001b92541ed0a22b0cb89018b561d895503206c0082c0ecf2d0b7e5182191eed
2022-11-19 15:42:15.206154 3 hello10284 0006bc9ad4253c42e32b546dc17e5ea3fedaecdabef371b09906cea9387e8695
2022-11-19 15:42:15.350531 4 hello60067 0000e49eab06aa7a6b3aef7708991b91a7e01451fd67f520b832b89b18f4e7de
2022-11-19 15:42:15.771205 5 hello156056 0000037660ee0e22df67a053537e000325bbfad2cce9b8b7c795f6aa961d5cb7
2022-11-19 15:43:47.285252 6 hello33290382 000000865194de5c0744d72183dcce2eca2b69264b749a1798f1b6996baef7de
2022-11-19 15:49:22.363936 7 hello121001637 0000000bcd89bc714263460f7b1fc82562410b96eaeec5cc2175e83f2d215046
2022-11-19 16:48:46.136385 8 hello1202655595 00000000e0d103722c6e172e145d15b9e909e109b47b30d741911bdb3cf3da84

Keys and Addresses

To round it out, the other main use of cryptography in cryptocurrencies, the private key, secures your ‘coins’. If you aren’t careful to hide and not reveal your private key, you lose your coins. Your public key which is basically translated into an address for BTC (and others) it is a 160 byte number can be freely given out, posted online, in email, put it anywhere you wish. Why? Because all someone an ever do with the public key/address is send you some ‘coin’. So if they did, great. And, if it is a publicly transparent blockchain like Bitcoin and most others, privacy coins such as Zcash and Monero for example being the exception, you can trace the transactions. Just put a public address into the browser search bar and various tools will appear that allow you to trace transactions to an address. So the criminals that think cryptocurrency gives them some kind of magic cloaking mechanism for their transactions are getting it wrong. The cryptography in cryptocurrency has nothing to do with keeping a record of transactions securing hidden away, in fact the transactions are as transparent as they could possibly be.

 



Infographic showing #3 a blockchain and a block consisting of it’s sequence number, the hash of the previous block and the nonce, plus a record of transactions.

The miner of the block gets the reward plus all the fees for the transactions. In 2021 when this was made the block reward was 6.25BTC per block mined. This is cut in half approximately every 4 years, until it drops off  altogether around the year 2140. By then the fees will be the only thing sustaining the miners financially. The fact that there is only a finite amount of Bitcoin that can be mined, ever, 21 Million of them, keeps inflation of Bitcoin at bay. This is not the case for all coins, some cryptocurrencies can create more and more coins at will, so they are inflationary. Bitcoin is a fixed supply of which most of it has been mined already. So most of the stock is already created and the flow of more coins gets lower and lower with each block reward halving, every 4 years. This concept of stock to flow is important because it is a measure of scarcity. If something can be made easily like fiat currency the flow can be a large input to the stock in existence. This is what is going on in 2022 with economies all over the world that have printed massive amounts of fiat money during the Covid crisis, when the stock to flow is not a good ratio, inflation results. The opposite occurs with gold for example, it is hard to increase the amount of gold pulled from the earth, so the flow of new gold into the current world stock of gold is less than 2% per year, (I think that I remember the max was just 2.2% somewhere in the WW2 time frame) so in essence the market is never flooded with new gold, which would debase gold against other stores of value.

Blockchain example slide

 

 

Blockchain example slide

'''
https://www.pythoncentral.io/hashing-strings-with-python/
'''
import hashlib
from datetime import datetime

mystring = input('Enter String to hash: ')
# Assumes the default UTF-8
hash_object = hashlib.sha256(mystring.encode())
print(hash_object.hexdigest())

for DIF in range(1,32):
    for n in range(1,1000000000000):

            x = mystring + str(n)
            hash_object = hashlib.sha256(x.encode())
            d = hash_object.hexdigest()

            #print(x,d)
            tally = 0

            for z in range(0,DIF):
                    if d[z] == '0':
                            tally += 1

            if tally == DIF:
                break

    timestamp = str(datetime.now())

    print(timestamp,DIF,x,d)

Resources

https://seekingalpha.com/article/4452010-bitcoin-energy-usage-isnt-a-problem-heres-why

https://ingoldwetrust.report/the-stock-to-flow-ratio-as-the-most-significant-reason-for-golds-monetary-importance/?lang=en

JPEG image Metcalfe's Law BTC

Bitcoin Charting Resources for Long Term Investing

“Good investing is not necessarily about making good decisions. It’s about consistently not screwing up.” – Morgan Housel author of The Psychology of Money

Accumulation/Distribution Aids

2 year moving average investor tool

https://www.lookintobitcoin.com/charts/bitcoin-investor-tool/

Puell Multiple, an oscillator, accumulate at bottoms, distribute at tops

https://www.lookintobitcoin.com/charts/puell-multiple/

MVRV Z-Score, an oscillator, accumulate at bottoms, distribute at tops

https://www.lookintobitcoin.com/charts/mvrv-zscore/

Pi cycle top indicator, finds tops…it actually worked again in 2021

https://www.lookintobitcoin.com/charts/pi-cycle-top-indicator/

Market Sentiment, fear and greed index…

Fear mode = Might be a buying opportunity, people are scared and dumping BTC probably at a loss to them in full panic mode, macro indicators are crashing, full panic, bank run on exchanges, major crisis crypto or otherwise…

Greed Mode = Look out, euphoria is happening, price may drop soon as BTC is in the news and suckers buying in late in the game pushing the price parabolic, like the old saying, ” Bulls run up the stairs only to jump out the window.”…

https://www.lookintobitcoin.com/charts/bitcoin-fear-and-greed-index/

HODL wave 1 year. BTC sitting on chain for more than a year, shows if people are accumulating or distributing

https://www.lookintobitcoin.com/charts/1-year-hodl-wave/

Realized Price, might be a good indicator of fair value for BTC.  A gauge of relative under/overvalue….

https://www.lookintobitcoin.com/charts/realized-price/

Wallet Sizes, who is holding large amounts of BTC, good to track the ‘smart money’, are they accumulating or distributing?

Wallet > 1 BTC

https://www.lookintobitcoin.com/charts/wallets-greater-than-1-btc/

Wallet > 10 BTC

https://www.lookintobitcoin.com/charts/wallets-greater-than-10-btc/

Wallet > 100 BTC

https://www.lookintobitcoin.com/charts/wallets-greater-than-100-btc/

Wallet > 1000 BTC

https://www.lookintobitcoin.com/charts/wallets-greater-than-1000-btc/

Look into Bitcoin, has many more charts…

https://www.lookintobitcoin.com/charts/


Mayer Multiple

Basically accumulate until it hits 2.4, then hold, sell at the top optionally, then when it drops below 1.5 start accumulating again.

https://bitcoinition.com/charts/mayer-multiple/

Metcalfe’s Law Model

This is a static chart, (don’t remember where it is from) would love to see this as a dynamic one. Seems to show a fair value for BTC. Paper on Metcalfe’s law and Bitcoin

Mushroom Mycellium Timelapse Video

Timelapse photography is back with a new setup after a multi year hiatus. Still using the Raspberry PI and old school low res webcam, just in a new location in my utility room with a light on 24/7.

On this video 1 second of play is one hour of real time.

The substrate that the mycellium is growing on is corn, popping corn and about 25% rye grain that have be pressure cooked to sterilized. It also has a small amount of ground coffee mixed in with it to provide small pieces of substrate for the mycellium to branch off of quickly. This batch was inoculated by using a spore syringe, right at the top of the jar and takes a few days to take off and show up in frame.