Leo E.

/leoe

Leo E.

Math enthusiast

User Avatar

Leo E.

4y ago

Beautiful Analogies: Ohm's Law for Blood Pressure in the Context of Homeostasis

Today I'm writing about a different topic -- medical physiology. This topic is close to my heart because my father liked it, but also because in my mind, it has a math-y flavor (unlike many other aspects of medicine).

For the context, I have been studying Zone 2 training and heart rate variability, but could not quite get to terms with the fundamental ideas, such as homeostasis. So, I started checking medical publications. Obviously, those are hard to understand since I don't have a medical background.

Luckily, I found one article that resonated with me. It is a long article about homeostasis in the journal called "Frontiers in Physiology" [1]. The article talks about various aspects of homeostasis. Specifically, one of those aspects describes feedback control in medical physiology.

The most surprising, and most beautiful part of the article describes the simplification of homeostatic regulation of blood pressure. It turns out that the simplified model of arterial pressure can be mathematically defined using Ohm's Law! Algebraically, blood pressure (BP - analogous to voltage, E) is a product of cardiac output (CO - analogous to current, I) and total peripheral resistance (TPR - analogous to resistance, R).

BP = CO × TPR | E = I × R

This simple analogy, made a big difference in my intuitive understanding of fundamentals of homeostasis. I am not sure where it will lead me, but this surprising connection made the ideas related to homeostasis quite a bit more accessible.

[1] https://doi.org/10.3389/fphys.2020.00200

User Avatar

Leo E.

4y ago

Brief Look at Fundamental Analysis and Efficient Market Hypothesis

Last week I started my exploration of the stock market using a "what seems interesting" methodology. I just jumped into some Python code that helped me get basic data and then started looking deeper at whatever piqued my interest. As I was doing my research, the term that kept showing up was technical analysis. It turns out that I was doing some very rudimentary technical analysis. I also realized during this process that besides technical analysis there is another type of analysis called fundamental analysis.

Technical analysis comes more naturally to me, so I decided to take a look at the fundamental analysis. Fundamental analysis is concerned with the stock's real value. My first guess was that fundamental analysis was probably more intuitive, qualitative, descriptive. The guess evoked memories of my futile attempts to parse finance jargon. Well, it turns out I was only partially correct. But more about that in some later essays. The more important outcome of my recent research was the "aha moment" about fundamental analysis: it implicitly assumes that the market does not always properly capture the value of a stock. I thought that was the only way to think about the market, because it intuitively makes sense to me. However, there is another school of thought based on efficient market hypothesis, which claims that the stock prices on the market already include all the existing information. The logical conclusion of efficient market hypothesis is that both fundamental and technical analysis are largely useless.

As I mentioned before, I am far from an expert, but intuitively efficient market hypothesis seems to be a naive interpretation of the real-world complexities. Therefore, I will continue exploring both technical and fundamental analysis.

User Avatar

Leo E.

4y ago

Review of Volume, Moving Averages, Candlestick with 5 Lines of Python

Today, I will review some of the key ideas from the previous week and show how Python can help represent all that information with only five lines of code.

  • Volume - a number of shares traded during some time period, usually a day.

    • Volume / price combination can help us determine whether the stock is bearish or bullish.

  • Moving averages - one of the fundamental techniques for technical analysis of stocks.

    • I've shown how simple moving averages can help you remove the noise from the data and then apply volume / price combination.

    • Candlestick chart - simple but effective way to summarize 5 features of the daily stock data.

You can depict all those ideas with 5 lines of Python code!

import mplfinance as mpf
import yfinance as stock_data
cur = stock_data.Ticker('ON')
ohlc_cur = cur.history(period="21d")
mpf.plot(ohlc_cur, type="candle", mav=4, volume=True)

(I'll post the image as a separate tweet.)

User Avatar

Leo E.

4y ago

Candlestick Charts: Delightfully Simple Representation of Daily Stock Data

Yesterday I wrote about simple moving averages as a way to more clearly depict the stock data. Today I will write about a complementary visualization technique that cleverly packs five important aspects of the daily movement of a stock price. The visualization is called candlestick charting.

Candlestick charts were developed in 18th century by Japanese rice traders. (Apparently, in 1710 rice markets evolved from "on the spot" to a form of futures contracts.) A single candlestick element represents opening, closing, high and low price of the day. Moreover, it also uses a simple two color scheme to depict whether the price closing price was lower or higher at the end of the day. For example, a red shaded candlestick "body" represents lower closing price relative to opening, while green represents higher closing price relative to opening.

In summary, a candlestick chart consists of the following elements:

  • High price

  • Open price

  • Close price

  • Low price

The line between the high and open price is called the upper shadow, a bar between opening and closing price is called the real body, and finally the line between the close and low price is called the lower shadow. Another name for the upper / lower shadow is a wick.

In my mind, the candlestick is brilliant in its simplicity -- it encodes five key pieces of information in an intuitive way. In the following essays I will describe how candlestick charts can be used in technical analysis of stocks.

User Avatar

Leo E.

4y ago

Stock Technical Analysis: Simple Moving Averages Help Interpret Irregular Volume Data

Today I decided to expand the set of technical indicators used for evaluating stocks. The previous indicators based on price / volume combination and On-balance volume seem fundamental. In the similar vain, today I am taking a deeper look at another simple but fundamental indicator: simple moving averages (SMA).

Intuitively, moving averages just smoothes the data, so it does not seem particularly exciting. The key benefit of SMA is the filtering the noise out of data. Note that unlike price / volume indicators form previous essays this metric does not have any predictive power. Another reason to explore SMA is to prepare the ground for more complex indicators that use it as a building block.

The mathematical definition, given a time-frame of size n, given data points D1, D2, ..., Dn, SMA is just an average:

SMA = (D1 + D2 + ... + Dn) / n

This defintion simple enough to implement in Python, but I'll just use Python built-in statistics module.

from statistics import mean

I applied SMA with "window" length equal to five days for yesterdays ON Semiconductor EKG like volume data to see the effects of smoothing. The smoothing is obvious. Moreover, the smoothed volume data for ON stock is U shaped, and more importantly it is "synchronized" with the U shaped closing price data. In this case, smoothing confirmed the yesterday's estimate of bullish behavior of the ON stock.

User Avatar

Leo E.

4y ago

On-Balance Volume Indicator for ON Semiconductor Corporation

Today I will analyze a stock from another industry that is close to my heart -- semiconductors. Specifically, I'll look into ON Semiconductor Corporation (stock ticker: ON). I had heard about the company before, but I don't think the company can be considered a household name. So, a short introduction using their own words:

ON Semiconductor Corporation provides intelligent sensing and power solutions worldwide. Its intelligent power technologies enable the electrification of the automotive industry that allows for lighter and longer-range electric vehicles, empowers fast-charging systems, and propels sustainable energy for the solar strings, industrial power, and storage systems.

Ok, looks quite interesting, especially, the electrification of the automative industry.

First, the closing price in the last 21 days behaved almost the same as HashiCorp Inc. from yesterday -- there is a distinct U shape: on Feb 25 the price was $63, then it dipped to $54 on Mar 7 and Mar 14, after today it bounced back to $64.

Second, the volume is all over the place, it looks like a sinusoid signal from an EKG -- especially the last 7 days. Accordingly, there is not real trend to be noticed for the volume. So, I don't think the price / volume heuristics really applies in this case.

Third, there is the OBV indicator that looks interesting, it is slightly jagged in the last week of February and the first part March, after that the OBV indicator for ON has very clear upward slope. Therefore, I think this stock is bullish.

User Avatar

Leo E.

4y ago

Basic Analysis of the Last Three Weeks of HashiCorp Inc. Stock

Yesterday I stumbled upon the first simple heuristics for stock analysis. As a disclaimer, I have no idea what I am talking about when it comes to stock market analysis, so take everything with a large grain of salt. Honestly, I am just trying to have fun while writing, and currently stock analysis writes itself.

Today I am going to analyze the last three weeks of HashiCorp Inc. stock (ticker: HCP). The high-level reason for doing analysis is to get more comfortable with the stock analysis. A more personal reason is that I like the idea behind HashiCorp as a company and have liked using their software, specifically Vagrant and Vault. The final reason for this analysis is that the company has been on the stock market for a very short time, only since November 2021.

During the last two days, I have expanded the time-frame from 5 to 12, and now to 21 days. I still don't have a good intuition which time-frame is more useful, but I am sure each has some benefits depending on what you are trying to analyze.

Now I will describe three aspects of this stock during the last three weeks.

  • Price: the price graph is distinctly U shaped, the price started at around $53, dipped to $32, and today is back at $54.

  • Volume: the volume graphs is almost perfectly opposite, that is, A shaped, with the highest volume almost perfectly aligning with the lowest price. Concretely, volume of exchange on Mar 11 was 3.6 million, and the price hit the low of $32.45. Today, the volume was relatively low, hovering around 900 thousand.

  • On-Balance Volume: the OBV indicator appears like a more jagged version of the price.

Using the heuristics from yesterday, pricing going up on low volumes, and the price going down on high volume indicates bearish stock. I really wanted this stock to perform well, and I hope it will. Moreover, it is possible that this heuristics does not accurately asses this specific stock. Regardless, I am happy with the insight gained from this analysis.

User Avatar

Leo E.

4y ago

Heuristics to Determine If Stock is Bullish or Bearish with Volume and Price

I continue to deepen my understanding of stock market terms. Today I'll try to take a deeper look at using the OBV metric to decide whether a stock is bearish or bullish. Those two terms are relatively simple:

  • bear stock is a stock that we determine will decrease in value,

  • bull stock is a stock that we determine will increase in value.

How does OBV indicator help us determine whether stock is bearish or bullish? The intuition behind OBV metric is that: volume often precedes price. Given that intuition it becomes clear how price / volume combination gives us simple heuristics for determining the nature of the stock.

Properties of bearish stock:

  • Decreasing price with increasing volume

  • Increasing price with decreasing volume

Properties of bullish stock:

  • Increasing price with increasing volume

  • Decreasing prince with decreasing volume

I will apply these heuristics to the Shopify stock.

  • During the last two days both price and volume are trending downward. I find it counterintuitive, but according to the heuristics that indicates the properties of a bullish stock. My current intuition behind the bullishness of the stock whose price and volume is decreasing is that market or company is consolidating. So, it may be possible that the stock will breakout after the period of consolidation.

User Avatar

Leo E.

4y ago

On-Balance Volume Indicator Algorithm in Python

Yesterday, I introduced the idea of On-Balance Volume and showed how to get volume and closing values for the Shopify stock during a five day time period. I also described the basic steps of the algorithm, however I did not present the algorithm. Below is the full algorithm with some dependencies on yesterday's code.

obv_prev = 0 obv = 0 obv_history = [] close_price_prev = None start = True vol_close_lst = zip(volume_nd, close_nd) for vol, close_price in vol_close_lst: if start is True: start = False else: if close_price > close_price_prev: obv = obv_prev + vol elif close_price < close_price_prev: obv = obv_prev - vol else: obv = obv_prev obv_prev = obv obv_history.append(obv) close_price_prev = close_price

One minor modification is that instead of 5 days range for volume and closing price I decided to parametrize it for any number of days that I may care about.

Below this essay I will post graphs showing closing range, volume and OBV changes for the last 12 days, where today will show up as zero in the graph.

User Avatar

Leo E.

4y ago

Calculating On-Balance Volume Indicator for Shopify Stock using Python

Encouraged by yesterday's experiments I am continuing my exploration of the stock market. Today I will try to make sense of On-Balance Volume indicator. According to Investopedia, On-Balance Volume (OBV) is an indicator that uses volume flow to predict changes in stock prices.

The algorithm to calculate OBV is simple, it is a cumulative value that depends on the initial time of computation. Each step considers one of three cases:

  1. OBV = OBV' + volume if close > close'

  2. OBV = OBV' if close == close'

  3. OBV = OBV - volume if close < close'

    Where, OBV' is a previous value OBV and close' is previous closing price in some time interval (in this case, previous day).

So, OBV indicator seems fairly simple in theory. But enough of theory, let's get our hands dirty. Somewhat randomly, I decided to check Shopify stock today.

shop = stock_data.Ticker('SHOP')
shop_history = shop.history(period="5d")
volume_5d = list(shop_history['Volume'])
print(volume_5d)
> 2655400, 3159600, 3035600, 4602400, 6669931

Shopify stock looks more interesting than I expected when I started this experiment -- the volume has more than doubled in the last five days!

Now, let's check the closing price:

close_5d = list(shop_history['Close'])
print(close_5d)
[553.43, 622.38, 657.38, 780.0, 683.45]

Finally, let us find the OBV for the last five days using the algorithm above is:

[0, 3159600, 6195200, 10797600, 4127669]

(The code for computing OBV is longer, so I might post it later.)

It turns out that the individual numerical values of OBV are not important, what matters is the rate of the change. In this small sample, the first four days look like a strong signal for higher prices, however that did not materialize on day 5. Overall, this was an interesting experiment that helped me understand the basic idea behind OBV and made the stock market price changes slightly less opaque.

User Avatar

Leo E.

4y ago

How I Used Python to Gain Deeper Understanding of Stock Volume Trading

Today I decided to develop a deeper understanding of stocks. I find finance in general and stocks in particular kind of boring; I like math, computer science, that kind of stuff. So, instead of forcing myself to learn about stocks the usual way by reading finance books or articles, I decided to use coding to organically learn specific stock related topics. I only assume you have Python 3 installed, then you just need to pip install yfinance. Now, you're ready to start exploring.

import yfinance as stock_data
import json
hcp = stock_data.Ticker('HCP')
stock_info = hcp.get_info()
print(stock_info.keys())

After I got the list of all keys I could explore, I decided to check the stock volume.

volume = stock_info['volume']
print(volume)
> 2031364

I remember hearing about stock volume, but obviously it didn't stick. When I had a concrete number I got curious. After brief research I learned the stock volume is just the number of shares traded during some time period. However, I was unable to find what this specific value means. So, I tried something more specific, namely the stock volume during the last 10 days.

avg_volume = stock_info['averageDailyVolume10Day']
print(avg_volume)
> 1803570

Next I thought it'd be interesting to figure out how was that average formed. Specifically, how did the volume change, say during the last five days.

hcp.history(period="5d")
> ... Volume
> ... 2489700
> ... 1172200
> ... 1905800
> ... 1433100
> ... 2031500

Now, I was curious about the significance of the stock volume. It turns out that stock volume is one of the fundamental indicators. Specifically, the volume patterns over time point toward trends. For example, increasing price and decreasing volume might indicate lack of interest. Inversely, decreasing price and increasing volume indicate that something about the stock has fundamentally changed. I'll likely continue to deepen my understanding now that dry financial concepts got concrete embodiment in data via code.

User Avatar

Leo E.

Byzantine Generals

4y ago

Byzantine Fault in Tri-Party Agreement Between Buyer, Lender, and the Construction Company

In the previous essays, I have talked about Byzantine Generals Problem from various perspectives. The problem used military analogy but was motivated by software development issues and is now fundamental to the theory of distributed computing. In this essay I will apply the reasoning to the Tri-Party Agreement in the mortgage industry. I have no knowledge of mortgage industry, but want to demonstrate the generality of the problem.

Let's take the following problem definition from Investopedia:

A tri-party agreement is a business deal between three separate parties. In the mortgage industry, a tri-party or tripartite agreement often takes place during the construction phase of a new home or condominium complex, to secure so-called bridge-loans for the construction itself. In such cases, the loan contract involves the buyer, the lender, and the builder.

The real tripartite agreement are complex; for simplicity let us assume that parties want to reach simple binary agreement: (a) start building or (b) postpone.

First, let us assume that each of the parties may behave maliciously. Second, let us consider the agreement from the perspective of an honest buyer. Third, let us assume the parties only use oral messages to communicate. We are now ready to examine two scenarios:

  1. An honest lender separately informs the buyer and the builder that they can provide money to start building. However, malicious builder informs the buyer that the lender said that building needs to be postponed.

  2. A malicious lender informs the buyer that building can start, but informs the builder that it needs to be postponed. Honest builder conveys the message from lender to the buyer.

The buyer receives exactly the same messages in both cases and cannot distinguish between the two scenarios. The buyer must start from scratch with new lender and new builder.

Of course, real life tripartite agreement are usually not oral agreements. However, I hope this simplified version of real-life problem demonstrates importance and difficulty of Byzantine agreement.

User Avatar

Leo E.

Byzantine Generals

4y ago

Three Aspects of the Problem of Reaching Agreement In Distributed Computing Systems Even If Some Participants are Malicious

Finally there is no mention of Byzantine Generals in the title, but I am not done with the topic yet. :) Following the feedback I received about the previous essays I will narrow the scope to distributed computing systems and give three aspects of the problem of reaching agreement even if some participants are giving misleading answers.

First, let's start with three ways participants can behave:

  1. They may not send or receive messages.

  2. A participant can send contradictory messages to various participants.

  3. Participants may send specially crafted messages to cause confusion during communication.

Another name for faults that satisfy these three properties is Byzantine faults.

Second, we say that participants will reach an agreement if two conditions hold:

  1. All non-malicious participants must receive the same set of messages.

  2. A message by a non-malicious participant must be received by every other non-malicious participant.

Third, we assume that communication channel satisfies the following three conditions:

  1. The communication network is reliable, in other words the messages are not corrupted during the transport.

  2. A receiver can identify the sender.

  3. A participant can detect absence of messages, that is, each participant knows which other participant sent a message.

The impossibility result (that is not trivial to prove) is that the agreement (as described above) can be reached only if less than a third of participants are not malicious.

User Avatar

Leo E.

Byzantine Generals

4y ago

The Origin of Byzantine Generals Problem

As Richard Feynman noted, knowing the name of something is not the same as knowing something. However, naming by itself is hard and important. Famous computer scientist, Leslie Lamport, who is credited as the inventor of the Byzantine General Problem talks about the problem of naming [https://www.microsoft.com/en-us/research/publication/byzantine-generals-problem/]:

I have long felt, because it was posed as a cute problem about philosophers seated around a table, Dijkstra's dining philosophers received much more attention that it deserves. (For example, it has probably received more attention in the theory community than the readers/writers problem, which illustrates the same principles and has much more practical importance.) I believed that the problem introduced in [another Lamport's paper on Reaching Agreement in Presence of Faults] was very important and deserved attention of computer scientists. The popularity of the dining philosophers problem taught me that the best way to attract attention to a problem is to present it in terms of a story.

If my wife and son thought that the Byzantine Generals Problem is not that exciting they would have probably immediately fell asleep reading or listening about reaching agreement in presence of faults.

Almost 40 years since the original paper an interesting way to pose a problem ensures the enduring interest in understanding it. An interesting story behind an idea may provoke more interest than the idea deserves, but more importantly it gives a kind of immortality to ideas that would otherwise live in relative obscurity.

User Avatar

Leo E.

Byzantine Generals

4y ago

Byzantine Generals Explained to an Eight-year Old

My son was excited when I told him I was going to write about Byzantine Generals. Like many 8-year old boys he likes to play war, and he also happens to like history. He has toy Roman soldiers and has enjoyed learning some Roman history, so Byzantine Generals sounded really cool. However, when I described to him what I was going to write about, he seemed a little bit disappointed because it turned out these were not typical generals, there was no bravery or even gory details about fighting, just an abstract idea about a group of generals making a decision.

Unlike my wife, about whose perception I wrote yesterday, he did not find the Byzantine Generals Problem too simple or unrealistic. Of course, there could be treacherous generals! Since the real-life experience did not get in his way I think he got the core idea. Specifically, it made sense to him that you'd want some way to assure majority vote among loyal generals. Perhaps, because Byzantine Generals consensus it is not that different from the consensus he has to find daily on a school playground. What he did not understand is why are we stopping there, and where is all the excitement of the battle.

So, an interesting lesson for me is that the understanding of abstract ideas often requires careful analysis of underlying assumptions. Unfortunately, most insidious assumptions are not easily recognizable because they are the result of accumulated experience. Even though my son does not realize the significance of Byzantine Generals in the context of distributed systems, he understood that you need a way to reach majority, and that reaching majority is not always easy.

User Avatar

Leo E.

Byzantine Generals

4y ago

Context-free Byzantine Generals are Boring

For the last two days, I was writing about Byzantine Generals as an analogy for consensus in distributed systems. Anyone who read a textbook or an academic paper about distributed systems will know that it is a pretty interesting analogy. However, everything else about distributed systems is fairly abstract and dry unless you already deeply care about the topic.

My wife lovingly read my three essays and even though she did not find them particularly exciting, she didn't mind revising them for grammar and basic readability. However, in all honesty I think she found Byzantine Generals relatively contrived and boring. Some of the issues that she mentioned explicitly or implicitly were:

  • Maybe they are all wrong so who cares about an agreement?

  • Military severely punishes dissent, so having treacherous generals sounds contrived.

  • Why would they have to agree all the time? They seem to agree most of the time, so what if there is some special case where they don't agree?

So, Byzantine Generals works in relatively specific context where the reader already understands that distributed systems often imply malicious setting where the least you can do is guarantee correctness at the design level. More importantly, looking at the problem mathematically, every corner case matters and without meticulously covering all of them the theory is just wrong.

Occasionally, mathematics can appear both contrived and nit-picky. Admittedly, sometimes it is. However, most of the times mathematics helps us understand the fundamental nature of the problem if we have the right context and are willing to put in the effort.

User Avatar

Leo E.

Byzantine Generals

4y ago

Three Byzantine Generals

Yesterday I wrote about thought experiments involving Byzantine generals that can only communicate via a messenger. Recall that Byzantine generals may be loyal or treacherous, however I did not explicitly specify whether the messenger is trustworthy. For simplicity, let us assume we can trust that each messenger will accurately convey the general's orders.

Conceptually, the Byzantine Generals thought experiment is not particularly difficult. But, it might not be immediately obvious that it is impossible to guarantee that with three Byzantine generals, all loyal generals will agree whether to attack or retreat. Let us first explicitly rule out simple, uninteresting cases. The first two cases cover complete loyalty or complete dissent. In the first case there will be no problem in reaching consensus by simple majority: there will be at least two votes for either attack or retreat. The second case is trivial since the consensus only matters to loyal generals.

One loyal general might intuitively seem a bit trickier, but recall that we only care about achieving agreement between loyal generals. Therefore the only interesting case is two loyal generals that need to agree on the course of action. Imagine that one of the loyal generals joined the siege late and now receives two contradicting messages (one attack / one retreat). Without additional information it is impossible for the third general to decide which message is trustworthy and how to proceed.

User Avatar

Leo E.

Byzantine Generals

4y ago

The Byzantine Generals Problem

Yesterday I wrote about how 40 years ago NASA realized computer systems would fulfill critical functions in our daily lives. Consequently, they had to design a system that would have extremely low failure rates. However, at that time we did not know how to design them correctly. Admittedly, we still don't but we got better at it.

One particularly interesting concept that helps us design better systems is known as the Byzantine Generals Problem. It was proposed by an illustrious computer scientist, Leslie Lamport. Mathematically, the problem is about consensus in distributed systems. Since that sounds boring, imagine there is a Byzantine army attempting to siege a city. In fact, you don't have to imagine, there were plenty of Byzantine sieges, not the least the Siege of Naples, but that's another story.

So coming back to the main story, there are Byzantine Generals with their armies around Naples and they had to decide whether to attack or retreat. The generals can communicate only via a messenger. Moreover, not all generals are loyal, and some may actively attempt to thwart the attempt.

Finally, the solution to the problem must ensure:

  1. All loyal generals will agree on the same plan of attack.

  2. Treacherous generals cannot deceive the loyal generals into adopting the bad plan.

Seemingly this is a simple problem. However, it turns out it is impossible to devise a solution with two loyal and only one disloyal general. I barely scratched the surface, so I may return to it later.

User Avatar

Leo E.

4y ago

One in a Billion

In the late 1970s / early 1980s NASA set to design SIFT, which stands for Software Implemented Fault Tolerance. The motivation for the work was an observation that aircrafts rely on computer systems to provide important functions such as navigation and flight control to name a few. However, those are not critical in a sense that if computer provided control fails then a member of a crew can take over.

The next frontier of that time, more than 40 years ago, was how to design an aircraft that would for the first time critically rely on computer system control. In that case, computer systems must be significantly more reliable. Specifically, the reliability requirement should be 10⁻⁹ or one in a billion per hour in a ten hour flight. To put that into perspective, the probability of being struck by lighting is around one in a million in a year or thousand times more likely.

Now you are probably wondering how did they figure out that the design really meets the requirement? How do you go about testing it? Clearly, they could not just build a bunch of aircrafts and test them through flights. The only way for NASA to convince themselves that their design satisfies the extremely small failure rates is to use math. That math lead to the idea of Byzantine Generals, but that's another story.