Ancient Psychology

True good is only possible when the self is aware of the suffering of the other and wants to minimize the suffering.

An interesting thought is to think about is when did humans or higher animals become self conscious and therefore developed a theory of mind that allows them to know what it feels like for others to experience the same thing that they might.

To make this more concrete, let’s use an example, two for that matter, one good behavior and one not so good. A bonobos monkey accidentally breaks a branch off of a tree and it falls on the head someone below, “… the film’s animal advisor, Patrick Bleuzen, who remarked that ‘Once I got hit on the head with a branch that had a bonobo on it. I sat down and the bonobo noticed I was in a difficult situation and came and took me by the hand and moved my hair back, like they do. So they live on compassion, and that’s really interesting to experience.” Excerpt From FREEDOM: The End Of The Human Condition Jeremy Griffith. The behavior  suggests that they can feel what it like to be in a position of compassion towards others.

Example two, an angry dominant male chimp snatches an infant from a female and dangles it precariously over a cliff edge. This is a clear example of control and an I don’t have to hit you but, I can get what I want from you by threat alone.

So what’s the threshold. What level does an animal have to be at to exhibit this behavior. How do we test for self awareness to begin with. One way that comes to mind is can they recognize themselves in the mirror. I decided to look it up, sure enough it has been done. As one would guess higher primates pass the test along with dolphins and others. See Mirror Test for more.

So once one is self aware, it is one easy step to start projecting that out to others and develop a theory of mind. And, this might be the root of good and evil. ( I started thinking about this was when I read partway through FREEDOM: The End Of The Human Condition by Jeremy Griffith )

For how can one know good and evil other than having a theory of mind for the other. True evil  is only possible when the self is aware of the suffering of the other and wants to maximize this suffering. True good is only possible when the self is aware of the suffering of the other and wants to minimize the suffering. The good news is that there is more good available because good can go beyond just minimizing suffering but, beyond it to generate positive benefit above this point, towards freedom from the potential of suffering and on to the path of the pursuit of happiness. Good can also generate the resources to create a reserve to push out and prevent suffering.

Cooperation

Think of it this way, people in small groups or a community can cooperate to store up a harvest and other reserves to carry the individual and a community through the hardest of times. The more that is stored up, the more that can be shared and the worse conditions might have to be before there is suffering.

Kye

In modern times this form of cooperation can be extended to one of the best resources that can be held in reserve collectively and used to do good for people involved cooperatively. The resource is money and the tool is known as a kye in Korean and, pronounced as geh in English. A form of this concept exists in many other countries around the world. It is basically a loan circle among a group of close friends and/or relatives and can expand to be as large as a community (good for the community such as providing a water well can be funded this way). Money goes into a kitty on a periodic basis, usually monthly and then someone from the group gets a payout to start a business, cover an emergency, obtain a down-payment on a house and so on. Think of it as a communal savings plan of sorts. Money is effectively harvested and concentrated to do good for all the participants on a rotating basis which can be determined by a leader of the group, a vote, consensus, random draw or rotation around the group in turn. To read more about this and the versions from other parts of the world read The Radical Economics of Lending Your Friends Money and/or Rotating Savings and Credit Association (ROSCA) . The descriptive category that is one level higher than this is Collaborative Finance.

The Circle of Self

In a way personal money can work like this too, with yourself, you can give the gift of it to your future self from your present self, your own mini loan circle, with now-you giving and future-you on the other side of it receiving.

Money is not quite about happiness after all

Money really does not buy happiness and having it beyond a certain point creates less of what economists call utility.

  • The first million is exciting, the second not quite as much.
  • Twenty dollars to someone living on the street with nothing is worth far more in utility than a person that is making 100K per year, it has a lot more utility for the former than the latter.

A thought experiment is to pretend that you have 10x your financial resources, 10x in income and in the bank, just divide everything that you see the price of by 10 and think of that for a minute for a perspective of how it would feel. Then do the opposite. It’s like having a utilty-scope and gives you a sense of what it feels like to slide into different financial brackets.

But, money has it’s limits to buying happiness as we can see with falling utility as we have more of it. But, it ( having enough buffer ) does buy a way out of misery, which is just a word for a continuous never ending path of suffering. Savings is just money set aside to share with your future self.

It’s expensive to be poor

  • In central Nairobi water comes out of a tap. In a shanty town outside of Nairobi it gets delivered in plastic containers at 10 times the cost of the tap water and with much more inconvenience to use.
  • If you are too poor to have enough money in your banking account to cover a check that was written to you, you can go to the originating bank and cash it. In the past this was free and why not, the money is right there, isn’t it? Totally verifiable and available on the spot. Nowadays you can expect a service fee of $5 for the convenience of getting the check cashed.

These and worse examples of predatory lending like payday loans, subprime lending make access to money as a resource more difficult for the poor.

How much to save?

It depends, some say 6 months of your income. I’d take that further by looking at what the FIRE (Financial Independence Retire Early  ) movement does. Save 6 months worth of expenses as a start, but don’t stop there, get rid of debt, learn how to raise your savings rate and learn how to invest what you have saved. The more you have, the further you push out the gap between comfort and potential suffering for you and others around you. Aim for true financial independence. Something major breaks, a big expense, no problem. If in the end it’s become a large pile of fat stacks of cash that you don’t need all of, well you can pay it forward to do good for someone else, a reverse kye maybe. Plus, having money saved up gives you more options in a positive way, life changes, plans change, unforeseen opportunities arise and being there at the right place and the right time means nothing unless you have the resources, usually money,  to make the opportunity manifest into reality.

 

Lightbeam Cat

Luna Rides Light Beam

Can you write a story about a cat riding a beam of light. Use a writing style that is characterized by a narrative storytelling approach, use anecdotes and examples to illustrate the main points and also ask pretend questions about your own beliefs and assumptions, use a conversational tone and make it easy to follow your reasoning. Also use metaphors and comparisons.

Once upon a time, there was a cat named Luna who lived in a small village at the foot of a mountain. Luna was a curious and adventurous cat, always looking for new and exciting experiences.

One day, while exploring the mountain, Luna stumbled upon a strange, glowing beam of light. Without hesitation, she leapt onto the beam and began to ride it. The beam was like a magic carpet, lifting Luna higher and higher into the sky.

As Luna rode the beam, she saw things she had never seen before. The world below her became smaller and smaller, and she could see for miles and miles. She felt like she was flying, free as a bird. Luna felt a sense of wonder and amazement as she soared through the air.

As Luna rode the beam, she couldn’t help but think about the nature of light. She remembered her physics lessons and wondered if light was a particle or a wave. She wondered if the beam she was riding on was made up of photons, the fundamental particles of light. Luna also wondered if the beam she was riding on was infinite, and if there were other cats riding on beams of light somewhere in the universe.

But Luna quickly realized that these were just idle musings and that she should just enjoy the ride. The beam was like a river of light, and Luna was its fearless navigator. She rode the beam, feeling the wind in her fur, and the sun on her face.

Just as Luna was starting to feel like the beam would take her to the ends of the earth, it suddenly disappeared. Luna found herself back on the mountain, with the village below her. She realized that her adventure had come to an end, but the memories of it would stay with her forever.

From that day on, Luna had a new appreciation for the beauty and mystery of light. She would often return to the mountain and gaze up at the sky, searching for that magical beam of light once again.

And who knows? Maybe, just maybe, she would find it and ride it again, forever exploring the unknown and experiencing the wonder of the universe.

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.