(x)slates
https://xslates.com/
Recent content on (x)slates
Hugo  gohugo.io
2019 (x)slates © All Rights Reserved.
Mon, 09 Dec 2019 00:00:00 +0000

Consumer Surplus and Producer Surplus
https://xslates.com/post/consumersurplusandproducersurplus/
Mon, 09 Dec 2019 00:00:00 +0000
https://xslates.com/post/consumersurplusandproducersurplus/
You can think of demand and supply (of a product) as quantities that are functions of price. However, it can be convenient to also think of them as prices as functions of quantity, that is \(p = D(x)\) and \(p = S(x)\). Consumer surplus and producer surplus are such quantities.
A consumer’s demand curve is the graph of \(p = D(X)\), which shows the price per unit that the consumer is willing to pay for \(x\) units of a product.

Properties of Definite Integrals
https://xslates.com/post/propertiesofdefiniteintegrals/
Mon, 25 Nov 2019 00:00:00 +0000
https://xslates.com/post/propertiesofdefiniteintegrals/
We’ve seen that the definite integral
\[\int_a^c f(x)dx\]
can be regarded as the area under the graph of \(y = f(x)\) over the interval [a, c]. If you have a point \(b\) such that \(a < b < c\), the above integral can be expressed as the sum of the integral from \(a\) to \(b\), and the integral from \(b\) to \(c\). This is the additive property of definite integrals.

Sane Development Practices
https://xslates.com/post/sanedevelopmentpractices/
Sat, 23 Nov 2019 00:00:00 +0000
https://xslates.com/post/sanedevelopmentpractices/
Some thoughts on programming from a nonprogrammer (at least by trade).
Beware of tools that are too recent. Sometimes change is good. Oftentimes it isn’t.
Developers like shiny new gadgets. These tend to be of lesser quality than older, more robust ones.
Whenever someone calls their library “simple” or “easy”, skip it. It’s likely to be a poorly documented, inconsistent, and wasteful solution to whatever problem you might have.

Applications of Definite Integrals
https://xslates.com/post/applicationsofdefiniteintegrals/
Mon, 18 Nov 2019 00:00:00 +0000
https://xslates.com/post/applicationsofdefiniteintegrals/
Total Profit A company finds that the marginal profit, in dollars, from drilling a well that is \(x\) feet deep is given by
\[P^\prime(x) = \sqrt[5]{x}\] Find the profit when a well 250 ft deep is drilled.
import sympy as sp from sympy.abc import x import matplotlib.pyplot as plt import numpy as np marginal_profit = sp.root(x, 5) marginal_profit ## x**(1/5) profit = sp.integrate(marginal_profit, x) profit ## 5*x**(6/5)/6 p = sp.

Area and Definite Integrals
https://xslates.com/post/areaanddefiniteintegrals/
Fri, 15 Nov 2019 00:00:00 +0000
https://xslates.com/post/areaanddefiniteintegrals/
The process of integration is about making the logical connection that the antiderivative of a function \(f\) does in fact lead to the exact area under the graph of \(f\). That’s what’s called the fundamental theorem of calculus
The Fundamental Theorem of Calculus The area under the graph of a nonnegative continuous function \(f\) over an interval \([a, b]\) is determined as an area function \(A\), which is an antiderivative of \(f\); that is, \(\frac{d}{dx}A(x) = f(x)\).

Antiderivatives as Areas
https://xslates.com/post/antiderivativesasareas/
Thu, 14 Nov 2019 00:00:00 +0000
https://xslates.com/post/antiderivativesasareas/
Integral calculus is mainly concerned with the area below the graph of a function. Let’s investigate that.
Geometry and Areas The most common areas used in integration are triangles, \(A = \frac{1}{2} bh\), and rectangles, \(A = bh\), where \(b\) is the base, the \(x\)axis, and \(h\) is the height, the \(y\)axis.
def area(b, h, polygon="rectangle"): if polygon == "triangle": A = 1/2 * (b * h) else: A = b * h return A Distance as Area A vehicle travels at 50 mi/hr for 2 hr.

Antidifferentiation
https://xslates.com/post/antidifferentiation/
Thu, 07 Nov 2019 00:00:00 +0000
https://xslates.com/post/antidifferentiation/
Antidifferentiation is the process of, given a function \(f(x)\), finding another function \(F(x)\) whose derivative is the given function, \(\frac{d}{dx} F(x) = F^\prime(x) = f(x)\). Antidifferentiation and the antiderivative are part of a larger process called integration.
Formally, the antiderivative of \(f(x)\) is the set of functions \(F(x) + C\) such that
\[\frac{d}{dx}[F(x) + C] = f(x)\]
where \(C\) is what’s called the constant of integration. This can be restated as follows: if two functions \(F(x)\) and \(G(x)\) have the same derivative \(f(x)\), then \(F(x)\) and \(G(x)\) differ by at most a constant \(F(x) = G(x) + C\).

Notes on Development Environments
https://xslates.com/post/notesondevelopmentenvironments/
Thu, 07 Nov 2019 00:00:00 +0000
https://xslates.com/post/notesondevelopmentenvironments/
After trying to figure out to make Vim, Python, Zsh, and Tmux play along for the second time in a couple of years, I came to the conclusion(s) that:
spending hours on end reading docs for things that other tools offer at a much lower barrier to entry is not worth it. losing your temper over even the smallest of battles (e.g how to change colors in Tmux, or configuring setup files) is a waste of energy.

Economics Applications of Derivatives
https://xslates.com/post/economicsapplicationsofderivatives/
Mon, 04 Nov 2019 00:00:00 +0000
https://xslates.com/post/economicsapplicationsofderivatives/
Some interesting things you can do with derivatives in the context of economics are to:
Find the price elasticity of a demand function. Find the maximum of a totalrevenue function. Characterize demand in terms of elasticity. Retailers and manufacturers often need to know how a small change in price will affect the demand of a product. If a small increase in price produces no change in demand, then the price increase is a reasonable decision to make.

Beware of Code on the Internet
https://xslates.com/post/bewarecodeontheinternet/
Sun, 03 Nov 2019 00:00:00 +0000
https://xslates.com/post/bewarecodeontheinternet/
As I try to figure out how to ease back into Vim, Tmux, and other “esoteric” tools, I’m reminded again that you should never trust people’s suggestions on the Internet (especially their code). I suspect that the hundreds of blog posts on “how to configure x”, “how to setup y”, or “why everyone should be using z” contribute to the general attitude of mistrust that I have towards people trying to be helpful online.

Derivatives of Exponential and Logarithmic Functions
https://xslates.com/post/derivatesofexponentialandlogarithmicfunctions/
Wed, 30 Oct 2019 00:00:00 +0000
https://xslates.com/post/derivatesofexponentialandlogarithmicfunctions/
The derivative of an exponential function of the form \(a^x\) is
\[\frac{d}{dx}a^x = (\ln a)a^x\]
from sympy import * from sympy.abc import x expr = 2**x expr2 = 3**(2*x) diff(expr) ## 2**x*log(2) diff(expr2) ## 2*3**(2*x)*log(3) The derivative of a function of the form \(\log_ax\)is
\[\frac{d}{dx}\log_a x = \frac{1}{\ln a} \cdot \frac{1}{x}\]
expr3 = log(x, 8) expr4 = log((x**2 + 1), 3) diff(expr3) ## 1/(x*log(8)) diff(expr4) ## 2*x/((x**2 + 1)*log(3))

Exponential Decay
https://xslates.com/post/exponentialdecay/
Tue, 29 Oct 2019 00:00:00 +0000
https://xslates.com/post/exponentialdecay/
In the equation of population growth, \(dP/dt = kP\), the constant \(k\) is given by \(k = (\text{birth rate})  (\text{death rate})\). Thus, a population grows only when the birth rate is greater than the death rate. When the death rate is greater than the birth rate we have a decrease or “decay”. Our equation for population decay becomes \(dP/dt = kP\), where \(k >0\). The function that satisfies that rate of return is then

Exponential Functions Business Applications
https://xslates.com/post/exponentialfunctionsbusinessapplications/
Mon, 28 Oct 2019 00:00:00 +0000
https://xslates.com/post/exponentialfunctionsbusinessapplications/
We go over some textbook exercises for exponential functions.
Franchise Expansion A franchise business is selling franchises for pizza shops throughout the country. The marketing manager estimates that the number of franchises, \(N\), will increase at the rate of 10% per year, that is,
\[\frac{dN}{dt} = 0.10N\]
Find the function that satisfies this equation, assuming that the number of franchises at \(t = 0\) is 50. How many franchises will be there in 20 years?

Applications of Exponential Functions: Uninhibited and Limited Growth Models
https://xslates.com/post/applicationsofexponentialfunctionsuninhibitedandlimitedgrowthmodels/
Thu, 24 Oct 2019 00:00:00 +0000
https://xslates.com/post/applicationsofexponentialfunctionsuninhibitedandlimitedgrowthmodels/
If you have a function like \(f(x) = ce^{kx}\), where \(c\) is a constant then its derivative is \(f^\prime (x) = k \cdot f(x)\), where \(k\) is also a constant.
For example, the general form of a function like \(\frac{dA}{dt} = 5A\) is \(A(t) = ce^{5t}\). The general form of a function like \(\frac{dP}{dt} = kP\) is \(P(t) = ce^{kt}\). Whereas solutions of an algebraic equation is a number, the solutions to the equations in these examples are functions.

Sorting Lists of Dictionaries by Common Keys
https://xslates.com/post/sortinglistsofdictionariesbycommonkeys/
Thu, 24 Oct 2019 00:00:00 +0000
https://xslates.com/post/sortinglistsofdictionariesbycommonkeys/
If you have a list of dictionaries and you would like to sort the entries according to one or more of the dictionary values, you can use itemgetter from operator.
from operator import itemgetter entries = [ {"name": "Sarah", "surname": "Connor", "uid": 104}, {"name": "Morticia", "surname": "Addams", "uid": 174}, {"name": "Sal", "surname": "Gomez", "uid": 345}, {"name": "Kawhi", "surname": "Leonard", "uid": 2} ] entries_by_name = sorted(entries, key=itemgetter("name")) entries_by_uid = sorted(entries, key=itemgetter("uid")) entries_by_name ## [{'name': 'Kawhi', 'surname': 'Leonard', 'uid': 2}, {'name': 'Morticia', 'surname': 'Addams', 'uid': 174}, {'name': 'Sal', 'surname': 'Gomez', 'uid': 345}, {'name': 'Sarah', 'surname': 'Connor', 'uid': 104}] entries_by_uid ## [{'name': 'Kawhi', 'surname': 'Leonard', 'uid': 2}, {'name': 'Sarah', 'surname': 'Connor', 'uid': 104}, {'name': 'Morticia', 'surname': 'Addams', 'uid': 174}, {'name': 'Sal', 'surname': 'Gomez', 'uid': 345}] entries_by_uid_and_surname = sorted(entries, key=itemgetter("uid", "surname")) entries_by_uid_and_surname ## [{'name': 'Kawhi', 'surname': 'Leonard', 'uid': 2}, {'name': 'Sarah', 'surname': 'Connor', 'uid': 104}, {'name': 'Morticia', 'surname': 'Addams', 'uid': 174}, {'name': 'Sal', 'surname': 'Gomez', 'uid': 345}] You can also use operations with itemgetter.

Logarithmic Functions
https://xslates.com/post/logarithmicfunctions/
Wed, 23 Oct 2019 00:00:00 +0000
https://xslates.com/post/logarithmicfunctions/
If we wanted to solve the equation
\[10^y = 1000\]
we would be trying to find the power of 10 that will give 1000. Since \(10^3 = 1000\), the answer is 3, hence the number 3 is called the logarithm, base 10, of 1000.
A logarithm is defined as
\[\log_{a} x = y \rightarrow a^y = x\] for \(a > 0\) and \(a \neq 1\). The number \(log_ax\) is the power \(y\) to which we raise \(a\) to get \(x\).

Exponential Functions
https://xslates.com/post/exponentialfunctions/
Tue, 22 Oct 2019 00:00:00 +0000
https://xslates.com/post/exponentialfunctions/
An exponential function is given by
\[f(x) = a^x\]
where \(x\) is any real number, \(a > 0\), and \(a \neq 1\). The number \(a\) is called the base. Unlike power functions, which have the variable in the base, exponential functions have the variable in the exponent.
import numpy as np import matplotlib.pyplot as plt def f(x): return 2**x def g(x): return (1/2)**x def h(x): return 0.4**x x = np.

Implicit Differentiation
https://xslates.com/post/implicitdifferentiation/
Mon, 21 Oct 2019 00:00:00 +0000
https://xslates.com/post/implicitdifferentiation/
We often write a function the output variable (usually \(y\)) isolated on one side of the equation (e.g., \(y = 3x + 7\)). However, sometimes, it’s cumbersome or impossible to isolate the output variable (e.g. \(y^3 + x^2y^5  x^4 = 27\)). In such cases, we have what’s called an implicit relationship between our variables. We can find the derivative with respect to \(y\) for these functions using a process called implicit differentiation.

Business Applications of Marginals and Differentials
https://xslates.com/post/businessapplicationsofmarginalsanddifferentials/
Fri, 11 Oct 2019 00:00:00 +0000
https://xslates.com/post/businessapplicationsofmarginalsanddifferentials/
In this post, we look at some business applications of marginals and differentials. To begin with, let’s make a recap of the topic.
If \(C(x)\) represents the cost of producing \(x\) items, then marginal cost \(C^\prime(x)\) is its derivative, and \(C^\prime(x) \approx C(x + 1)  C(x)\). Thus, the cost to produce the \((x + 1)\)st item can be approximated by \(C(x + 1) \approx C(x) + C^\prime(x)\). If \(R(x)\) represents the revenue from selling \(x\) items, then marginal revenue \(R^\prime(x)\) is its derivative, and \(R^\prime(x) \approx R(x + 1)  R(x)\).

Marginal Analysis & Differentials
https://xslates.com/post/marginalsdifferentials/
Fri, 27 Sep 2019 00:00:00 +0000
https://xslates.com/post/marginalsdifferentials/
Marginal analysis is the study of the additional benefits of an activity compared to the additional costs incurred for pursuing said activity. Marginal analysis relies on derivatives and is oftentimes used in microeconomics and business settings to optimize decisionmaking.
Let \(C(x)\), \(R(x)\), \(P(x)\) represent, respectively, the total cost, revenue, and profit from the production and sale of \(x\) items; there are two ways to mathematically define the marginals of these quantities.

MaxMin Problems
https://xslates.com/post/maxminproblems/
Wed, 25 Sep 2019 00:00:00 +0000
https://xslates.com/post/maxminproblems/
An important use of calculus is the solving of maximumminimum problems, that is, fidning the absolute maximum of minimum value of some varying quantity and that point at which that maximum of minimum occurs.
There’s an extensive treatment of optimization on Scipy’s lecture notes.
The general strategy for solving these problems involves translating the problem into an equation in one variable. Then one can use derivatives to find out critical points and evaluate whether these points are maximum or minimum values over a (closed or open) interval.

Asymptotes
https://xslates.com/post/asymptotes/
Fri, 20 Sep 2019 00:00:00 +0000
https://xslates.com/post/asymptotes/
A rational function is a function \(f\) that can be described by
\[f(x) = \frac{P(x)}{Q(x)}\] where \(P(x)\) and \(Q(x)\) are polynomials, with \(Q(x)\) not the zero polynomial. Rational functions can generate graphs with asymptotes.
import matplotlib.pyplot as plt import numpy as np def rational(x): return x**2  4 / x  1 y_values = [rational(x) for x in np.linspace(5, 5)] plt.scatter(np.linspace(5, 5), y_values) plt.axvline(0, linestyle="", color="gray") The line \(x = a\) is a vertical asymptote if any of the following limit statements is true:

Second Derivatives to Find Maximum and Minimum Values
https://xslates.com/post/secondderivativestofindmaximumandminimumvalues/
Wed, 18 Sep 2019 00:00:00 +0000
https://xslates.com/post/secondderivativestofindmaximumandminimumvalues/
The “turning” behavior of a graph is called its concavity. The second derivative plays a pivotal role in analyzing a function’s concavity.
Suppose that \(f\) is a function whose derivative \(f^\prime\) exists at every poting in an open interval \(I\). Then \(f\) is concave up on \(I\) if \(f^\prime\) is increasing (and therefore \(f^{\prime\prime}\) is positive) over \(I\). \(f\) is concave down on \(I\) if \(f^\prime\) is decreasing (and therefore \(f^{\prime\prime}\) is negative) over \(I\).

Notes on Work #2
https://xslates.com/post/notesonwork2/
Tue, 17 Sep 2019 00:00:00 +0000
https://xslates.com/post/notesonwork2/
Read an interesting thread on HN. The comment that stood out the most to me was this one, and the ensuing discussion around it:
Successful companies also attract gold diggers. When the company is small, unless everybody is going above and beyond the call of duty, it’s likely going to fail. As the company gets bigger, there is more and more latitude for failure. At some point it is successful enough that it can survive having people whose only goal is to direct a large amount of money into their pockets.

First Derivatives to Find Maximum and Minimum Values of Functions
https://xslates.com/post/firstderivativestofindmaximumandminimumvaluesoffunctions/
Mon, 16 Sep 2019 00:00:00 +0000
https://xslates.com/post/firstderivativestofindmaximumandminimumvaluesoffunctions/
If the graph of a function rises from the left to the right over an interval \(I\), the function is increasing on, or over, \(I\). If the graph drops from left to right, the function is decreasing on, or over, \(I\).
Mathematically speaking, a function is increasing over an interval if, for every input \(a\) and \(b\) in the interval, the input \(a\) is less than the input \(b\), and the output \(f(a) < f(b)\).

Business Applications of Derivatives
https://xslates.com/post/businessapplicationsofderivatives/
Fri, 13 Sep 2019 00:00:00 +0000
https://xslates.com/post/businessapplicationsofderivatives/
A company is selling laptop computers. It determines that its total profit, in dollars, is given by
\[P(x) = 0.08x^2 + 80x\] where \(x\) is the number of units produced and sold. Suppose that \(x\) is a function of time, in months, where \(x = 5t + 1\). (a) Find the total profit as a function of time \(t\). (b) Find the rate of change of total profit when \(t = 48\) months.

HigherOrder Derivatives
https://xslates.com/post/higherorderderivatives/
Fri, 13 Sep 2019 00:00:00 +0000
https://xslates.com/post/higherorderderivatives/
Let’s consider the function
\[y = f(x) = x^5  3x^4 + x\]
Its derivative \(f^\prime\) is
\[y^\prime = f^\prime(x) = 5x^4  12x^3 + 1\]
The derivative function \(f^\prime\) can also be differientiated. We can think of the derivative of \(f^\prime\) as rhe rate of change of the slope of the tange lines of \(f\). We use the notation \(f^{\prime\prime}\).
\[f^{\prime\prime}(x) = \frac{d}{dx}f^\prime(x)\]
We call this function the second derivative of \(f\).

Differentiation Techniques Pt.3
https://xslates.com/post/differentiationtechniquespt3/
Wed, 11 Sep 2019 00:00:00 +0000
https://xslates.com/post/differentiationtechniquespt3/
The extended power rule states that, supposing that \(g(x)\) is a differentiable function of \(x\). Then, for any real number \(k\),
\[\frac{d}{dx}[g(x)]^k = k[g(x)]^{k1} \cdot \frac{d}{dx}g(x)\]
Taking a detour into function compositions, a composed function \(f \circ g\), the composition of \(f\) and \(g\), is defined as
\[(f \circ g)(x) = f(g(x))\]
Suppose we want to calculate how much it costs to heat a house on a particular day of the year.

Differentiation Techniques Pt.2
https://xslates.com/post/differentiationtechniquespt2/
Sun, 08 Sep 2019 00:00:00 +0000
https://xslates.com/post/differentiationtechniquespt2/
A function can be written as athe product of two other functions.
The product rule states that if you let \(F(x) = f(x) \cdot g(x)\), then
\[F^{\prime}(x) = \frac{d}{dx}[f(x) \cdot g(x)] = f(x) \cdot \Bigg[ \frac{d}{dx}g(x) \Bigg] + g(x) \cdot \Bigg[ \frac{d}{dx}f(x) \Bigg]\]
In simple English, the derivative of a product is the first factor times the derivative of the second factor, plus the second factor times the derivative of the first factor.

Differentiation Techniques
https://xslates.com/post/differentiationtechniques/
Fri, 06 Sep 2019 00:00:00 +0000
https://xslates.com/post/differentiationtechniques/
Let \(y\) be a function of \(x\). A common way to express “the derivate of \(y\) with respect to \(x\)” is the notation
\[\frac{dy}{dy}\]
Using this notation, we can write that if \(y = f(x)\), then the derivative of \(y\) with respect to \(x\) is \(\frac{dy}{dx} = f^{\prime}(x)\).
There are a handful of rules that you can use when evaluating derivatives.
The Power Rule states that
\[\frac{d}{dx}x^k = kx^{k  1}\]

Trading Technical Analysis  A Refreshing Take
https://xslates.com/post/tradingarefreshingtake/
Fri, 06 Sep 2019 00:00:00 +0000
https://xslates.com/post/tradingarefreshingtake/
There’s some controversy on whether technical analysis and chart reading are better than fundamental analysis and intrinsic valuation. I personally don’t have a dog in the fight. However, scanning reddit, I found a couple of interesting answers to a thread called “Change my mind: Technical Analysis is a complete nonsense” on r/CryptoCurrency
Card And the original post on r/Bitcoin
Card

Differentiation Using Limits of Difference Quotients
https://xslates.com/post/differentiationusinglimitsofdifferencequotients/
Wed, 04 Sep 2019 00:00:00 +0000
https://xslates.com/post/differentiationusinglimitsofdifferencequotients/
A tangent line touches a curve at a single point only. For a function \(y = f(x)\), its derivative at \(x\) is the function \(f^{\prime}\) defined by
\[f^{\prime}(x) = \lim_{h \to 0} \frac{f(x + h)  f(x)}{h}\]
provided that the limit exists. If \(f^{\prime}(x)\) exists, then we say that \(f\) is differentiable at \(x\).
The key concept here is that we’re taking the difference quotient between any two points of a function and reducing that difference \(f(x + h)  f(x)\) until it approaches \(0\).

Average Rates of Change
https://xslates.com/post/averageratesofchange/
Sun, 01 Sep 2019 00:00:00 +0000
https://xslates.com/post/averageratesofchange/
The average rate of change of \(y\) wih respect to \(x\), as \(x\) changes from \(x_1\) to \(x_2\), is the ratio of the change in output to the change in input:
\[A(x) = \frac{f(x_2)  f(x_1)}{x_2  x_1}\]
where \(x_2 \neq x_1\). The average rate of change is the secant line passing through two points. If we generalize this idea we arrive at the different quotient, an average rate of change over any interval of a function.

Limits
https://xslates.com/post/limits/
Wed, 28 Aug 2019 00:00:00 +0000
https://xslates.com/post/limits/
As \(x\) approaches some number \(a\), the limit of \(f(x)\) is \(L\).
\[\lim_{x \to\ a} f(x) = L\]
A limit is a rigorous mathematical way of saying almost. A limit represents the output value that a function “approaches” as the input of the function closes in on some value.
The value of \(f(x)\) at the input value is irrelevant, sometimes it doesn’t even exist, sometimes even the limit itself doesn’t exist.

Packing and Unpacking Arguments in Python Functions
https://xslates.com/post/packingandunpackingargumentsinpythonfunctions/
Mon, 26 Aug 2019 00:00:00 +0000
https://xslates.com/post/packingandunpackingargumentsinpythonfunctions/
You can pack and unpack functions arguments in Python.
If you have a function take takes in \(n\) arguments, you can’t just pass it a list of said arguments. Let’s say we have a linear function that takes in an array of \(x\)values, a slope and intercept.
import numpy as np x_array = np.linspace(1, 10, 10) def linear(x, m, b): return x * m + b args = [2, 4] # the operation below leads to # TypeError: linear() missing 1 required positional argument: 'b' linear(x_array, args) Python takes in the x_array and args list as the first positional arguments.

Applications of Nonlinear Functions
https://xslates.com/post/applicationsofnonlinearfunctions/
Mon, 19 Aug 2019 00:00:00 +0000
https://xslates.com/post/applicationsofnonlinearfunctions/
import matplotlib.pyplot as plt Let’s look at some textbook applications of nonlinear functions (and models).
Stock Prices and Prime Rate It is theorized that the price per share of a stock is inversely proportional to the prime (interest) rate. In January 2010, the price per share \(S\) of Apple Inc. stock was $205.93, and the prime rate \(R\) was 3.25%. The prime rate rose to 4.75% in March 2010. What was the price per share in March 2010 if the assumption of inverse proportionality is correct?

Mathematical Modeling and Curve Fitting in Python
https://xslates.com/post/mathematicalmodelingandcurvefitting/
Sun, 18 Aug 2019 00:00:00 +0000
https://xslates.com/post/mathematicalmodelingandcurvefitting/
There are a handful of families of functions that form the basic toolkit that we use to model data. Curve fitting is the process of constructing a curve, or mathematical function, that best fits a series of data points.
The simplest way to decide which, if any, type of function fits a dataset is to examine a scatterplot of the data. If we can spot a general pattern that looks like any of the functions we would like to model with, then we can try to fit the data with it.

Nonlinear Models, Polynomial Functions
https://xslates.com/post/nonlinearmodelspolynomialfunctions/
Fri, 16 Aug 2019 00:00:00 +0000
https://xslates.com/post/nonlinearmodelspolynomialfunctions/
import matplotlib.pyplot as plt import numpy as np import math Linear and quadratic functions are part of a general class of polynomial functions. A polynomial function is given by
\[f(x) = a_nx^n + a_{n1}x^{n1}, + \dots + a_2x^2 + a_1x^1 + a_0\]
where \(n\) is a nonnegative integer and \(a_n, a_{n1}, \dots, a_1, a_0\) are real numbers, called the coefficients. The number \(a_0\), which is not multiplied by a variable, is called a constant.

Nonlinear Models, Quadratic Functions
https://xslates.com/post/quadraticfunctions/
Thu, 15 Aug 2019 00:00:00 +0000
https://xslates.com/post/quadraticfunctions/
A quadratic function is given by
\[f(x) = ax^2 + bx + c\]
where \(a \neq 0\). The graph of a quadratic function is called a parabola such that:
it always has a cupshaped curve it opens upward if \(a > 0\) or opens downwards if \(a < 0\) it has a turning point, or vertex, whose coordinate is \(x =  \frac{b}{2a}\) the vertical line \(x = \frac{b}{2a}\) (which is not part of the graph) is the line of symmetry You could think of the vertex as the first \(y\)value.

Determining the Most Frequent Items in a Sequence
https://xslates.com/post/determiningthemostfrequentitemsinasequence/
Tue, 13 Aug 2019 00:00:00 +0000
https://xslates.com/post/determiningthemostfrequentitemsinasequence/
If you have a sequence of items, and want to determine the most frequently occurring items in it, you can use the collections.Counter class.
words = [ "look", "into", "my", "eyes", "look", "into", "my", "soul", "it's", "not", "uncommon", "to", "see", "my", "mood", "in", "my", "eyes" ] from collections import Counter wcount = Counter(words) wcount.most_common(3) ## [('my', 4), ('look', 2), ('into', 2)] You can also check how many times a given item appears in the sequence.

Naming Slices
https://xslates.com/post/namingslices/
Mon, 12 Aug 2019 00:00:00 +0000
https://xslates.com/post/namingslices/
The builtin slice function creates a slice object tha can be used anywhere a slice is allowed. There are three arguments to to fill in, start, end, and step. The object returns the values at the indices specified in the arguments. If you only provide one argument, by default, slice will interpret it as the end.
items = [0, 1, 2, 3, 4, 5, 6] section = slice(2, 4, 1) initial = slice(4) items[section] ## [2, 3] items[initial] ## [0, 1, 2, 3] More on slices can be found here.

Applications of Linear Functions
https://xslates.com/post/applicationsoflinearfunctions/
Sun, 11 Aug 2019 00:00:00 +0000
https://xslates.com/post/applicationsoflinearfunctions/
import matplotlib.pyplot as plt In this post, we’ll look at some textbook applications of linear functions. Although these are contrived problems taken from a book, they shed some light on how to think about using linear functions to solve real business problems.
Highway tolls Since heavier vehicles are responsible for more of the wear and tear on highways, drivers should pay tolls in direct proportion to the weight of their vehicles.

Slope and Linear Functions
https://xslates.com/post/slopeandlinearfunctions/
Sat, 10 Aug 2019 00:00:00 +0000
https://xslates.com/post/slopeandlinearfunctions/
The graph of \(y = c\), or
\[f(x) = c\]
a horizontal line is the graph of a function. We call such a function a constant function. A constant function is one whose output value is the same for every input value. The graph of \(x = a\) is a vertical line, and \(x = a\) is not a function.
import matplotlib.pyplot as plt def constant(x): return 4 y_values = [constant(x) for x in range(1,10)] plt.

Calculating with Dictionaries in Python
https://xslates.com/post/calculatingwithdictionaries/
Thu, 08 Aug 2019 00:00:00 +0000
https://xslates.com/post/calculatingwithdictionaries/
To perform useful calculations on the contents of a dictionary, it is often useful to invert the keys and values of the dictionary using zip(), which creates an iterable tuple of a dictionary’s keys and values.
prices = { "ACME": 45.23, "AAPL": 612.78, "IBM": 205.55, "HPQ": 37.20 } prices ## {'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.2} zipped = zip(prices.values(), prices.keys()) for v, k in zipped: print(v, k) ## 45.

Finding Commonalities in Dictionaries in Python
https://xslates.com/post/findingcommonalitiesindictionaries/
Wed, 07 Aug 2019 00:00:00 +0000
https://xslates.com/post/findingcommonalitiesindictionaries/
A Python dictionary is a mapping between a set of keys and values. The keys() method supports common set operations such as unions, intersections, and differences. Same goes for the items() method. However, that’s not the case with the values() method since the values of a dictionary are not guaranteed to be unique. Based on these notions, we can compare dictionaries and see what they have in common with basic set operations.

Cumulative & Annualized Returns
https://xslates.com/post/cumulativeannualizedreturns/
Tue, 06 Aug 2019 00:00:00 +0000
https://xslates.com/post/cumulativeannualizedreturns/
The cumulative return of an investment is the aggregate return that an investment has gained or lost over time (it can be both positive or negative). If you have OpenHighLowClose stock data, you can compute cumulative returns on its adjusted price as dividends, and stock splits will lead to incorrect results.
\[R_c = \frac{P_c}{P_i}  1\]
where \(R_c\) is the cumulative return, \(P_c\) is the current price, and \(P_i\) is the initial price.

Keeping Python Dictionaries in Order
https://xslates.com/post/keepingpythondictionariesinorder/
Mon, 05 Aug 2019 00:00:00 +0000
https://xslates.com/post/keepingpythondictionariesinorder/
If you want to control the order of items in a dictionary, you can use an OrderedDict. It preserves the original insertion order of data. It’s a useful construct for when you want to seriealize or encode in different formats. As a note, the structure of an OrderedDict (a doubly linked list), means that these dictionaries are at least twice as heavy as normal dictionaries, meaning they require more memory.

Mapping Keys to Multiple Dictionary Values in Python
https://xslates.com/post/mappingkeystomultipledictionaryvalues/
Fri, 02 Aug 2019 00:00:00 +0000
https://xslates.com/post/mappingkeystomultipledictionaryvalues/
If you want to create a dictionary where you map keys to more than one value (a “multidict”), you must store these values into another container like a list or set. Use lists if you want to preserve the order of insertions, use sets if you don’t want to keep duplicates. It all depends on your use case, use the container with the characteristics that fit your needs.
d = { "a" : [1, 2, 3], "b" : [4, 5] } d ## {'a': [1, 2, 3], 'b': [4, 5]} e = { "a" : {1, 2, 3}, "b" : {4, 5} } e ## {'a': {1, 2, 3}, 'b': {4, 5}} You can also use defaultdict which allows you to write cleaner code.

Control Limits in Analytics
https://xslates.com/post/controllimitsinanalytics/
Wed, 31 Jul 2019 00:00:00 +0000
https://xslates.com/post/controllimitsinanalytics/
Control limits are visual references that help you detect if a statistic (or time series) is getting “out of control.” I first saw them referenced on Avinash Kaushik’s blog.
You can use a metric’s standard deviation to plot a bounded region, (\(\pm 3 \sigma\)), within which the statistic is assumed to behave normally. It’s not wandering too far off from its mean. The reason why this is useful in analytics is that more often than not, people will latch onto meaningless fluctuations and believe them to be worthy of attention.

Notes on Trading #2
https://xslates.com/post/notesontrading2/
Tue, 30 Jul 2019 00:00:00 +0000
https://xslates.com/post/notesontrading2/
StopLosses and TakeProfits Having StopLoss Orders (S/L) and TakeProfit Orders (T/P) allows you to compute a Risk/Reward Ratio for you trades. If you’re trading at the weekly level, these types of orders might let you ride upward trends more reliably than if you did it intraday. Volatile assets might hit a T/P target way earlier than you’d hope, which might be a good thing if you want to dip in and out.

Lambda Functions in Python
https://xslates.com/post/lambdafunctionsinpython/
Mon, 29 Jul 2019 00:00:00 +0000
https://xslates.com/post/lambdafunctionsinpython/
In Python, lambda functions are anonymous functions (meaning functions without a name).
The syntax for lambda functions is lambda arguments: expression.
half = lambda x: x / 2 half(14) ## 7.0 split = lambda s: list(s) split("hi") ## ['h', 'i'] pow = lambda x, y: x ** y pow(2, 3) ## 8 Lambda functions come in handy when you want to create a function that you won’t reuse. You can avoid defining the function and use a lambda function instead.

Heapq Algorithm
https://xslates.com/post/heapqalgorithm/
Thu, 25 Jul 2019 00:00:00 +0000
https://xslates.com/post/heapqalgorithm/
You can use the heapq module to perform operations like finding the nlargest and nsmallest items in a collection. A heap is a treebased data structure for which every parent node has a value less than or equal to any of its children. You can use it to make queues.
import heapq nums = [3, 4, 7, 1, 4, 9, 0, 2, 4, 6, 7, 1] print(heapq.nlargest(3, nums)) ## [9, 7, 6] print(heapq.

Assignment Operators in Python
https://xslates.com/post/assignmentoperatorsinpython/
Tue, 23 Jul 2019 00:00:00 +0000
https://xslates.com/post/assignmentoperatorsinpython/
Python’s assignment operators are used to store data into variables. The convention +=, = and the likes are used to update the value of a set variable with the value in the right operand.
a = 5 a += 2 a ## 7 a =2 a ## 5 a **= 2 a ## 25 Here’s a useful reference.

Deque Iterables in Python
https://xslates.com/post/operationsoniterablesinpython/
Tue, 23 Jul 2019 00:00:00 +0000
https://xslates.com/post/operationsoniterablesinpython/
If you want to keep a limited history of the last few items seen during iteration or other processes, you can use a deque which is a faster container, \(O(1)\), than a list, \(O(N)\). A deque allows you to keep a limited history of items, as in a queue.
from collections import deque import numpy as np d = deque(maxlen=3) d.append(1) d.append(2) d.append("text") d ## deque([1, 2, 'text'], maxlen=3) If we add more items, the earlier ones get bumped.

Unforgiving Math of Stock Value Loss
https://xslates.com/post/painfulmathofstockvalueloss/
Sun, 21 Jul 2019 00:00:00 +0000
https://xslates.com/post/painfulmathofstockvalueloss/
You buy a product for $25.00. The store has a sale and drops the price by 30%. Then they raise the price again by 30%, so now the product costs $23.43. What happened? Well, it’s a typical case of misleading percentages. The store applied the price increase to the discounted price.
Percentage calculations What is 4% of 10? 20 is what percentage of 30?
Questions like these can be answered by the following equations.

Unpacking Iterables into Variables in Python
https://xslates.com/post/unpackingiterablesintovariablesinpython/
Fri, 19 Jul 2019 00:00:00 +0000
https://xslates.com/post/unpackingiterablesintovariablesinpython/
You can unpack sequences and iterables into collections of variables by using an assignment operator.
p = (4, 5) x, y = p x ## 4 y ## 5 For this to work, the number of variables must match the number of elements in the iterable. Unpacking works on lists, tuples, strings, dictionaries, iterators, generators, files, and more data types.
data = ["BIGINC", 50, 355.6, (2019, 5, 12)] name, shares, price, date = data name ## 'BIGINC' shares ## 50 price ## 355.

Notes on Documentation
https://xslates.com/post/notesondocumentation/
Sun, 14 Jul 2019 00:00:00 +0000
https://xslates.com/post/notesondocumentation/
I’ve been trying to understand Backtrader recently, and I was a bit taken aback by its poor documentation; which made me reflect on how I should not document my projects in the future. These are just a few of the issues I’ve encountered. While I didn’t explore the whole documentation, these problems were enough to turn me off to the project entirely because, unfortunately, I’m to busy to try and figure out the platform right now.

Notes on Trading
https://xslates.com/post/notesontrading/
Fri, 05 Jul 2019 00:00:00 +0000
https://xslates.com/post/notesontrading/
Over the past few months, I’ve been listening to a podcast called Chat with Traders where you get to listen to professional traders share how they work.
Having no experience in the trading world, I thought it would be a good idea to try and pick up the topic by listening to conversations about it, rather than books. I’m not sure I’ll listen to all episodes but here are some lessons I’ve picked up from the podcast so far.

Notes on Work
https://xslates.com/post/notesonwork/
Thu, 23 May 2019 00:00:00 +0000
https://xslates.com/post/notesonwork/
Here are some thoughts on my experience working in the tech industry.
You can’t manufacture team culture. It’s the result of organic habits and behaviors that a group of people develops over time, which is also the reason why workshops and topdown change initiatives meet so much resistance.
Don’t have a meeting if you don’t have an agenda.
If you can end a meeting early, do it.
Don’t use meetings for status updates.

About
https://xslates.com/about/
Tue, 01 Jan 2019 00:00:00 +0000
https://xslates.com/about/
My name is Will. This is my site, there are many like it, but this one is mine.
I make my living as an analyst and I mostly write about technology, business, and mathematics.
For speaking, consulting, or just to get in touch, you can contact me here.