Thursday, 22 August 2024

The Evolution of JavaScript


Agenda

  • History of Javascript

  • Javascript Engine

  • ECMA

  • Node.js

  • Frameworks

  • Transpilers

  • Conclusion


History Of Javascript

In this blog we will see how Javascript has been evolved in the passed three decades, lets see the history of Javascript. But before we get into history of Javascript, let's talk about Web Browser.


What is Web Browser

It is a software that is used to access internet. The information is transferred using Hypertext Transfer Protocol (HTTP), which defines how text, images and video are transmitted on the web. As a client/server model, the browser is the client run on a computer that contacts the web server and request information.


WorldWideWeb

The first web browser, called WorldWideWeb, was created in 1990 by Sir Tim Berners-Lee. But only worked on the proprietary software of NeXT computers, which were in limited use. This is how the first web browser looks:

Fig1: WorldWideWeb, 1994. Credits: https://en.wikipedia.org/wiki/WorldWideWeb


Line Mode Browser

The Line Mode Browser is the second web browser ever created. The browser was the first demonstrated to be portable to several different operating systems. Operated from a simple command-line interface, it could be widely used on many computers and computer terminals throughout the Internet.

Fig2: Line Mode Browser. Credits: https://en.wikipedia.org/wiki/Line_Mode_Browser


Mosaic web browser

The Mosaic web browser was released in 1993. As the first browser with a graphical user interface accessible to non-technical people, it played a prominent role in the rapid growth of the nascent (nascent – just coming into existence and beginning to display signs of future potential) World Wide Web.

Fig3: Mosaic Web Browser. Credits: http://memex.cc/Web_browser


Creation of Javascript

Initial years of web, web pages were static. There was desire of dynamic behaviour after the page was loaded in the browser. 1995, Netscape decided to add a scripting language to Navigator. They pursued two routes to achieve this: collaborating with Sun Microsystems to embed the Java Programming Language, while also hiring Brendan Eich to embed Schema language.

In September 1995 “Brendan Eic” created the first version of Javascript (officially called LiveScript). It was developed in 10days.

The name was changed from LiveScript to Javascript in three months, well it was due to marketing reasons, as Java was hot new programming language at that time. (well based on the content I read)


Javascript Engine

The Javascript Engine resides in the web browser, we may need to know at high level how web browser works.

How Web Browser Works?

As said Web Browser is client program, it is what allows Web clients and Web servers to communicate with each other. The Web Browser act as a Web client here.

When you enter a Web address (URL) in your browser, this actually sends an HTTP command to the Web server directing it to fetch and transmit the requested Web page and display the information in your browser.

To display the web page on the screen of the browser, a group of structured codes which together performs a series of tasks.

Fig4: Browser broad level Architecture. Credits: https://medium.com/web-god-mode/how-web-browsers-work-behind-the-scene-architecture-technologies-and-internal-working-fec601488bfa


We will touch upon these at high level:

User Interface: Input given to the Browser such as URL, Next, Back, etc.

Browser Engine: Based on input from User interface queries and manipulates Rendering Engine.

Rendering Engine: Interprets the HTML, XML documents and images that are formatted using CSS and generates the layout that is displayed in the User Interface.

Networking: Retrieves the URLs using the common internet protocols of HTTP or FTP.

Javascript Interpreter: It is the component of the browser which interprets and executes the Javascript code embedded in a website. The interpreted results are sent to the rendering engine for display. If the script is external then, first the resource is fetched from the network. Parser keeps on holds until the script is executed.

UI Backend: UI backend is used for drawing basic widgets like combo boxes and windows. This backend exposes a generic interface that is not platform specific. It underneath uses operating system user interface methods.

Data Persistence/Storage: This is a persistence layer. Browsers support storage mechanisms such as localStorage, IndexedDB, WebSQL and FileSystem. It is a small database created on the local drive of the computer where the browser is installed. It manages user data such as cache, cookies, bookmarks and preferences.


Note: All Web browser are not all created equal, and Web pages also will not be displayed the same in different browsers. To understand in detail about architecture of how web browsers works internally, it would require a separate blog to be written.


Javascript Engine

Javascript is client side language, also can be said as web browser language. HTML and CSS displays the content in the web page, and Javascript is used for interaction.

As you know computers understand only binary, so how the Javascript be understood. Well to resolve this we have Javascript engine.

Each browser has their own engine.

  • First Javascript engine was created by Brenden Eich in 1995 for the Netscape Navigator web browser. Now evolved and its still being user in Firefox called SpiderMonkey engine.

  • First modern Javascript engine was V8, created by Google for its Chrome browser in 2008, having great performance in converting into machine code.

  • Chakra is the Javascript engine of the Internet Explorer browser. It was also forked by Microsoft for original Edge browser, but Edge was later rebuilt as Chromium-based browser and thus now uses V8.


ECMA

What is ECMA?

  • By 1959 the growing use of computers, built by several different manufacturers, showed the necessity for standardisation in operation techniques, such as programming, and also input and output codes.

  • Such standards would make it possible to use data prepared for, or even by, a computer made by on manufacturer to be on computer made by another with a minimum of alteration. Also it would avoid duplication of work in the preparation of, for example. Programming languages by several manufacturers.

  • The first meeting was held on April 27, 1960, in Brussels; it was decided that an association of manufacturer should be formed which would be called European Computer Manufacturer Association or for short ECMA, and a Committee was nominated to prepare the formation of the Association and to draw up By-laws and Rules.


ECMA Role in Javascript

  • In November 1996, Netscape submitted Javascript to ECMA International, as the starting point for a standard specification that all browser vendors could conform to. This led to the official release of the first ECMAScript language specification in June 1997, a general purpose, cross-platform programming language.

  • The standards process continued for a few years, with the release of ECMAScript 2 in June 1998 and ECMAScript 3 in December 1999. ECMAScript 4 began in 2000.

  • From 2016 to 2019, a new version of the ECMAScript standard was published each year, but the scope of changes was much smaller than the 5th or 6th editions. Thus Javascript can now be considered a mature language that has largely settled down.

  • By having standards in place, will help single Javascript to be executed similar way in all the browsers.


Node.js

What is Web Server?

  • From internet we get so many information, we perform several actions. But who provides us this and how? Well all these work is done by Web Server.

  • Web servers are basically simple computer programs, which handles the request sent by different client.

  • The server will respond to each client either by fetching details from:

    • Another server

    • Database

    • Fileserver

    • Performing computation in the webserver – could be CPU intensive job

  • Let's take an example; we have server which will show the current state of users affected by Covid19 in each country:

  • We will have several users ( clients ) requesting for the info at same time.

  • Let's say if we handle requests serially, the users would have to wait for a very long, then the portal will be not be of any use.

  • In traditional web servers like Apache, Tomcat we have mechanisms to handle this, it would either fork/thread. So it can seamlessly handle many requests at same time. Around 200+ requests can be handled in parallel from the single web server. The requests can scale up or down based on the server configuration.

  • Threads: In a layman term, imagine this as we watching movie, eating, talking and checking phone all at same time.


What is Node.js?

  • In 2009 Node.js was born, which made use of Javascript engines not limited to browsers, but introduces a lot of innovative thinking and approaches for Javascript server-side development. Chrome V8 engine is a core component of the popular Node.js runtine system.

  • What?? But you said Javascript is only for browsers? Yes before Node.js we would need a web server and a server side programming to perform actions on the web server such as open file, interact with database. To do that we use at least one these PHP, ASP, Java, Python, etc. server programming language.

  • But now we can have our HTTP/web server written in Javascript itself. Saviour!! Just know Javascript and you become full stack developer!!


How Node.js Work?

  • Let's continue our example when we have Node.js web server running, we also got to accept multiple clients right.

  • But in Javascript we don't have threads, as Node.js is single threaded.

  • It means only one request handled at a time, then how do we handle multiple requests?

  • To handle multiple requests in Node.js, it uses two concepts:

    • Asynchronous

    • Non-Blocking IO

  • Non-Blocking IO – From client the request hits the web server – then the web server reaches to database to fetch results it will take X amount of time. Rather waiting ideally, web servers goes and accepts another client who has sent request.

  • Asynchronous – Once client 1 completes reading from database it makes callback to server saying its ready, please send his output to the client 1.

  • Lets see how this is represented in a diagram:

Fig5: Node.js Architecture. Credits: https://www.simform.com/wp-content/uploads/2020/04/node.js-architecture.png

  • Now lets see from the below diagram how Node.js is connected to Javascript and its open source project V8 and libuv. 

Fig6: Node.js connected to Javascript and V8 and libuv Architecture. Credits: https://easyontheweb.com/Node.js-v8-and-libuv-under-the-hood-for-beginners/

  • Javascript the code which we write

  • Node.js world: is the middleman, executes the JS code that we've written with the help of C++ and gives us access to the APIs that are written in libuv and v8 libraries

  • V8: It is an open-source project created by Google. The main purpose of this open-source project is to execute Javascript code outside the browser. It basically compiles Javascript Code directly to native C++ code before executing it.

  • libuv: is a multi-platform C++ library that provides support for asynchronous I/O based operations such as file systems, networking and concurrency.

  • Node.js can be used for IO intensive workload, if we have single job doing much CPU – CPU intensive workload it is not good choice to have this.


Javascript Frameworks

What is Framework?

  • A Javascript framework is an application framework written in Javascript for building user interface.

  • Framework differ from a Javascript library:

    • A library offers function to be called by its parent code

    • Whereas a framework defines the entire application design

  • A developer does not call a framework; instead, the framework calls and uses the code in some particular way.


Common Frameworks

  • Examples frameworks are AngularJS, Ember.js, Metero.js and Vue.js, etc.

  • The below two frameworks are backed by giant names.

Technology

AngularJS

ReactJS

Developer

Google

Facebook

Technology type

Full-fledged MVC framework written in Javascript

Javascript library (View in MVC; requires Flux to implement architecture)

Concept

Brings Javascript into HTML Works with the real DOM client-side rendering

Brings HTML into Javascript Works the virtual DOM server-side rendering

Data binding

Two-way data binding

One-way data binding

Dependencies

Manages dependencies automatically

Requires additional tools to manage dependencies

Language

Javascript + HTML

Javascript + JSX

Suites best

Best for SPAs that update single view at a time

Best for SPAs that update many view at a time


Transpilers

We will end this blog by adding last few lines. We all would have heard compilers, which will compile code into machine code. But Transpilers are little different.

What is Transpilers?

Transpilers; or source-to-source compilers, are tools that read source code written in one programming language, and produce the equivalent code in another language.


Why Transpilers?

  • Anyone who's had to deal with browser compatibility issues before knows it's not as simple as writing Javascript that runs everywhere. That's because every browser uses a different Javascript engin: Chrome runs V8, Firefox runs SpiderMonkey, and Internet Explorer runs Chakra.

  • Each has different performance characteristics, each implements a different subset of latest ECMA standards features, and each is approaching full compliance with the spec at different rates. So its not quite time to write into latest format directly.

  • No we can still we write our source in the latest ECMA standards, and let a transpiler translate it to older version such as vanilla ES5 that works in every browser. If you need to support browser from the last millennium, you can even compile down to ES3.

  • Ideally you would be writing Tomorrow's Javascript, Today!!


Conclusion

Javascript can run on website to build dynamic pages, mobile app, desktop app and also now as backend server.

Seeing the Javascript evolution from the past 3 decades, it still has a real future. And now the popular industry like AIML also has modules built in Javascript such as Tensorflow.js!

Each JS framework has its own pros and cons, we need to analyze which will suit us. At times vanilla Javascript works amazing.

In this evolution of Javascript, there are many other tools and process adopted, but I have only included few and also content holds references from many sites. 


Reference

Wikipedia, Medium.com, Other references.

https://www.psypost.org/wp-content/uploads/2022/04/evolution-1024x512.jpg [credits for the front page image]


Original Blog Posted in OSFY

https://www.opensourceforu.com/2021/12/the-evolution-of-javascript/

For further research and updates maintaining the blog here.

Thursday, 8 August 2024

Book Lessons - How does Google Tests Software?

 



Testing is unavoidable aspect of development, marriage of development and testing is where Quality is achieved.  --Anonymous


I would like share the highlights, best practices and the strategies used by Goole in Testing their softwares., as mentioned in the the book “How Google Tests Software”.


Introduction

  • We all might wonder how does one of the biggest technology company called Google does testing. As they are solutions from operating system, to web apps, to enterprise, to commerce and social apps, etc. Specifically having much of their source code open.

  • You might be surprise to hear Google doesn't have a Testing Army to have the projects testing rather fewer dedicated testers in the entire organization. The testing team is part of a centralized organization and so called as Engineering Productivity Team (interesting name).

  • Google engineers prefer quality over features.

  • Let's see the actors who take responsibilities of the testing, types of tests done on the software, process and tools used. And finally the culture in the organization for testing.



Roles and Responsibilities

  • It's important to know the characters involved in the testing of the software.

  • SWE – Software engineer

    • Create design document

      • Choose data structures

      • Overall architecture

    • Write and review functional code that ships to users

    • Write lots of test code

  • SET – Software engineer in Test

    • A developer role – 100% of their time writing code

    • Review the designs and look closely at code quality and risk

    • SETs are partners of SWE codebase, but are more concerned in quality and test coverage

    • Write code for SWE to have them easily build TDD

  • TE - Test Engineer

    • Most of the time developer cum tester role

    • Its a role that puts testing on behalf of the users first and developers second

    • Write automation scripts and code that drives usage scenarios and mimics the user

    • Organize overall quality practices, interpret test results, drive test execution and build end-to-end test automation

    • Security, privacy, performance, reliability, usability, compatibility, globalization and other concerns are looked on



Types of Tests

  • Small Tests

    • Cover single unit of code in a completely faked environment

    • Unit tests, that verifies the behaviour of single class or function

  • Medium Tests

    • Cover multiple or single units of code in real or faked environment

    • Integration tests, validation of integration of one or more modules

  • Large Tests

    • Cover multiple number of units of code in the real environment

    • System or End-to-end tests, operate at high level and verify the application as a whole is working



SDLC Process at High Level

  • Idea is converted into POC/Google branded project

  • Team Structure – 

    • SWE

    • SET

    • TE (added in later stage of the project)

  • Explore the existing libraries, interface and protocols

  • Development and create unit test cases

  • Automation planning and increase the testability

  • CICD ( some projects works based on: Feedback based development / Bug based development)



Tools used and built internally

  • Unit Test Dashboard

    • Allow anyone to define their own project, with a set of build and test targets with a set of maintainers

    • The system would run all the tests for each project every day

  • Code Coverage

    • Tool for measuring whether a project's tests have a healthy mixture of small, medium and large tests

    • The general thumb rule: 70% to small / 20% to medium / 10% to large tests

  • Test Certified (TC)

    • A system of testing challenges that if a team completes, will earn the “certified” designation

    • To start all the projects will be Level 0 and the Levels are from 1-5

    • TC Level 1

      • Continuous build with test coverage bundles (small, medium, large)

    • TC Level 2

      • Requires smoke tests to pass before a submit

    • TC Level 3

      • Requires tests for all non-trivial changes

    • TC Level 4

      • Automate running of smoke tests and total test coverage should be at least 40%

    • TC Level 5

      • Activity use available analysis tools and total test coverage should be at least 60%

  • Google Test Analytics (GTA)

    • GTA is a simple web application that makes the data entry and visualization of risks little easier.

    • GTA supports the ACC model for Risk Analysis

    • ACC accomplishes through 3 views of the product

    • Attributes

      • Are the adjectives of the system. Qualities and characteristics that promote the product and distinguish from the competition

      • Eg: Google+

        • Social: Empowers the users to share information and what they're up to

        • Expressive: Users can express themselves through the features

        • Easy: Intuitive. Easy to figure out how to do what you want to do

    • Components

      • Are the nouns of the system. Core components or chunks of code makes to know what the product is.

      • Eg: Google+

        • Profile: Information and preferences of the logged in user

        • People: Profiles the users are connected with

        • More components are : Circles, Notifications, Interests, Posts, Comments, Photos

    • Capabilities

      • Are the verbs of the system. Actions the system performs at the command of the user.

      • Eg: Google+

        • Profile

          • Social: Shares profiles and preferences with friends and contacts

          • Expressive: Users can create online version of themselves

          • Expressive: Personalize your experiences with Google+

          • Easy: Easy to enter the update information

        • Like such all the components are mapped with appropriate attributes

  • Google Test Case Manager

    • To make it simple to write tests, provide a flexible tagging format that can tailored to any project

    • Makes test easily searchable, reusable and trackable

  • Buganizer

    • Bug tracking system

    • Simple to use and provides summary charts and reports

  • Quality Bots

    • Running regressions tests in virtual environment.

  • BITE Experiment

    • BITE stands for Browser Integrated Test Environment

    • This experiment is bringing as much as the testing activity, testing tools, testing data and reporting issues into the browser and cloud as possible

    • Reporting bugs (with recordings) and viewing bugs in chrome itself make it very simple to use

  • Diagnostic Utility

    • Issues submitted by Google Users, requires some technical data about the state of the Google software is needed

    • This utility, Google-signed executable is sent and executed to diagnose a user's machine

    • Gathering these details helps to fix the issues



Culture

  • The openness in the source code.

  • All engineers must reuse existing libraries, unless they have a good reason, as it benefits in time which will take to build and test.

  • Twenty percent of time is what called side projects, weekly one day is dedicated to work with the peer team or innovate startup POC project. Everyone enjoys this, Gmail and ChromeOS have started from these ideas.

  • Common infrastructure, linux distributions for engineering workstations and production deployment machines, centralized source code and modules.

  • Code Review is considered as most important and eagerness to do.

  • Dogfood, the term denotes to internal adoption of the software that are yet to release. Meant to convey the idea that if you make a product to sell to someone else, you should be willing to use it yourself to find out if it's any good.

  • Crowd sourcing, is a new phenomenon on the testing scene. Enter the crowd; a set of power users who are tech savvy and willing to help for reasonable compensation. Have programs in place to pay the best bug finders.

  • Culture of sharing ideas, supporting bottom-up experimentation and organization flexibility creates a fertile world.

  • It's okay to fail, Google's culture of supporting experimental projects which has led to many innovations and large junk of failed experiments. Learnings and improvements from the failure matters the most.

  • In-house developed tools don't need a lot of selling, weekly demos of the tools are done. Engineers come the way to adopt the tools.

  • Success is a collective issue.



Conclusion

Overall it was good reading experience with many examples from different google teams. Some of the points would seem to be repetitive, felt it is to emphasize the concepts. The concepts may not be new to us, but the process and making it meticulously followed is very interesting and we see now where they stand.


Note: The book I read was little old 2013 impression.



Reference

  • Book “How Google Tests Software” - James Whittaker * Jason Arbon * Jeff Carollo

Thursday, 25 July 2024

Interest Rates

 


Introduction

Interest rates refer to the cost of borrowing money or the return on investment expressed as a percentage. They are a critical tool in monetary policy and economics, influencing borrowing, saving, investing, and spending decisions throughout the economy.
  • Interest Rate (r): 
    • The interest rate represents the cost of borrowing money or the return on investment, expressed as a percentage per period.
    • It is usually an annual rate, but for calculations, it needs to be adjusted to match the compounding frequency of the other variables (monthly, quarterly, etc.).
  • Present Value (PV):
    • PV represents the current value of a sum of money that will be received or paid out in the future, discounted at the given interest rate.
    • It is also known as the principal amount. 
  • Future Value (FV):
    • FV is the value of an asset or cash at a specified date in the future, based on an assumed rate of growth over time.
    • It represents what an investment is expected to be worth in the future. 
  • Payment Amount (PMT):
    • PMT refers to a series of equal payments made at regular intervals, such as monthly or annually.
    • It is common in contexts like loans or annuities where regular payments are made.


Compounding

In one year how many times we get interest is known as compounding. The more the number of compounding the higher the returns because we are getting interest on interest.

Example: Future Values Based on Compounding Frequencies

Example: Present Values Based on Compounding Frequencies

Comparing interest rates compounded at different frequencies:


Types of Rates

Spot Rates

  • The spot rate (also known as the zero-coupon interest rate or the zero) is the rate earned on an investment when it is received at a single point in the future. 
  • In a situation where a single dollar is invested today and repaid as a lump-sum amount in the future, the spot rate will equate that future amount with the single dollar today. 
  • For example, $50 is invested today and $58 is returned to the investor two years from today. The spot rate is derived using the following equation, where R is determined to be 7.7033% and is applied annually:
    • 50(1+r)^2 = 58
    • (1+r)^2 = 58/50
    • (1+r)^2 = 1.16
    • sqrt((1+r)^2) = sqrt(1.16)
    • 1+r = 1.07703
    • r = 1 - 1.07703
    • r = 0.07703
    • r = 0.07703 * 100 #Convert to percentage
    • r = 7.703%
  • Formula:
    • FV = PV(1+r)^n 
      • Here r is the spot rate
  • The spot rate and the discount factor, d(t), provide the same information, such that the applicable discount factor for a spot rate of 7.7033% on a two-year investment is 0.86207. 
  • In other words, a $58 future amount, multiplied by 0.86207, is equal to $50. 
  • Financial calculator usage:
    • On a financial calculator, the discount factor and spot rate can be derived as long as one of the values is known. 
    • If the discount factor is known, by setting the present value equal to the discount factor, setting the future value to $1, and applying the number of years, the spot rate can be calculated. 
    • If the spot rate is known, that will be the interest rate, the future value will be $1, and the number of years is applied to determine the present value (the discount factor).
  • The formula to calculate the discount rate given the spot rate at time r, is:
    • d = ( 1/ (1 + (r/t)) )^n
      • d = discount rate
      • r = spot rate
      • n = years
      • t = time, yearly = 1, semi-annually = 0.5, quarterly 0.25, daily = 365
  • For a continuous compounding spot rate, the formula is:
    • d(t) = e^r(t)*t
  • Example of Spot Rate to Discount Factor conversion
  • Example of Discount Factor to Spot Rate conversion
  • Lets try to interpret the last example of Year = 3, DF = 0.8821 and see in detail how FV is reflecting:
    • 1yr = 0.8821 * (1 + 0.0427) = 0.9198
    • 2yr = 0.9198 * (1 + 0.0427) = 0.9591
    • 3yr = 0.9591 * (1 + 0.0427) = 1
  • All three terms - interest rate, discount rate, and spot rate - are related to the concept of time value of money and play a role in understanding borrowing and lending costs. 

    Interest Rate:

    • General Term: This is the broadest term encompassing the cost of borrowing money. It's the rate an investor expects to earn on a loan or bond, or the rate a borrower pays for using someone else's money.
    • Can Vary: Interest rates can vary depending on factors like loan type, borrower creditworthiness, and prevailing market conditions. For example, a credit card might have a higher interest rate than a mortgage for a house.
    • Interest Rate Example: Consider a bank loan with a quoted annual interest rate of 5%. If you borrow $10,000, the interest cost for one year, not accounting for any compounding within the year or adjusting for inflation, would simply be 5% of $10,000, which equals $500.

    Discount Rate:

    • Present Value Focus: In the context of bonds, it's the rate used to discount the future cash flows (coupons and principal repayment) of a bond to its present value.
    • Lower Rate = Higher Present Value: A higher discount rate translates to a lower present value for the bond, and vice versa.

    Spot Rate:

    • The spot rate, often referred to in the context of bond markets, specifically denotes the theoretical yield on a zero-coupon bond. In simpler terms, it is the rate of return on an investment that pays only at maturity and involves no intermediate cash flows like coupon payments. 
    • Specific Maturity: This is the interest rate for borrowing or lending money for a specific maturity in the loan market. Examples include interest rates on Treasury bills (short-term) or Treasury notes (longer-term).
    • Yield Curve Construction: Spot rates are used to construct the yield curve, which depicts the relationship between interest rates and maturities. By plotting spot rates for different maturities, you can see how interest rates change based on the length of the loan. They are critical in valuing bonds and in calculating the discount factors for different maturities. Financial professionals use these rates to derive the theoretical prices of bonds.
    • Spot Rate Example: Suppose a 5-year zero-coupon bond is trading at a price of $780, and its face value upon maturity is $1,000. The spot rate (yield to maturity) of this bond can be calculated using the formula that sets the present value equal to the price ($780 = $1,000 / (1 + spot rate)^5). Solving this would give you the yearly spot rate.

    Here's an analogy to understand the difference:

    • Imagine you're buying a new car. The interest rate on your car loan is the basic cost of borrowing the money. The discount rate is like a haggle factor - a higher discount rate (your discount) translates to a lower overall price (present value) of the car. Spot rates are like the advertised interest rates for different loan terms (e.g., 3-year loan vs. 5-year loan) offered by a bank.
    • While the spot rate specifically refers to the yield on a zero-coupon bond or a similar theoretical rate for a single period, the term interest rate is used in a much broader sense to indicate the cost of borrowing or the return on an investment. Both are critical in financial analysis and decision-making but serve different analytical needs and market functions.

    Key Differences:

    FeatureInterest RateDiscount RateSpot Rate
    DefinitionCost of borrowing/lending moneyRate used to discount future cash flows of a bond to present valueInterest rate for a specific loan maturity
    FocusGeneral cost of borrowingPresent value of bond cash flowsSpecific loan maturity
    VariabilityVaries based on factorsUsed for bond valuationPrevailing market rate for a specific maturity

Forward Rates

  • Forward rate
    • Forward rates are future spot rates that are based on current spot rates.
    • In theory, an investor should be indifferent and earn the same return for an investment that spans two years versus one that lasts one year and then requires reinvestment in the second year.
    • For example, an investor has $1,000 and can earn 2% for the first year. Alternatively, the investor is offered a two-year investment that pays 3.5%. 
    • The forward rate is the rate earned in the second year that should make the investor indifferent between the two options.
    • Forward Rate Formula for Non-Continuous
      • FR = ([ ((1 + Sm) ^ m) / ((1 + Sn) ^ n) ] ^ 1/m-n ) - 1
    • Forward Rate Formula for Continuous
      • FR = R2T2 - R1T1 / T2 - T1
    • Example 1:
      • Calculate Forward Rates for 7% = r and 3 = n with 10% = r and 5 = n
      • Formula FR = ([ ((1 + Sm) ^ m) / ((1 + Sn) ^ n) ] ^ 1/m-n ) - 1
      • Solution
        • S3 = 7%
        • S5 = 10%
        • FR = ([ ((1 + 0.10) ^ 5) / ((1 + 0.07) ^ 3) ] ^ 1/5-3 ) - 1
        • FR = 14.66% per annum
    • Example 2:
      • Assuming continuously compounded spot rates of 4.25 for 3 years and 4.40% for 3.5 years, calculate the forward rate for the period between Year 3 and Year 3.5.
      • Formula FR = R2T2 - R1T1 / T2 - T1
      • Solution
        • FR = ( (0.0425 * 3) - (0.0450 * 3.5) ) / (3.5 - 3)
        • FR = 5.30%
  • Forward rate agreement
    • A forward rate agreement (FRA) is a financial instrument that guarantees a specific rate to be paid or earned during a future period.
    • The FRA is worth zero when the current forward rate (F) is equal to the guaranteed rate (R). 
    • Assuming there is a difference, the present value of that difference between R and F, applied to the principal amount, equals the value of the FRA.
    • When R is greater than F, the value of the FRA is positive; when R is less than F, the value of the FRA is negative.

Par Rates

  • The par rate at maturity is the rate at which the present value of a bond equals its par value.
  • Par Rates Vs YTM
    • Par Rate:  
      • Definition: 
        • The interest rate (or discount rate) at which the present value of all a bond's future cash flows (coupons and principal repayment) equals the bond's par value (typically $100 or its face value). 
      • Focuses on: 
        • Theoretical scenario where a bond trades at its par value. 
      • Dependence: 
        • Depends on the prevailing spot rates in the market for different maturities. 
      • Relationship with Coupon Rate: 
        • When a bond is issued and trades at par, the par rate will be equal to the coupon rate. 
    • YTM:
      • Definition:
        • The internal rate of return (IRR) an investor expects to receive if they hold the bond until maturity and receive all promised cash flows (coupons and principal repayment).
      • Focuses on:
        • Actual market price of the bond.
      • Dependence:
        • Depends on both the bond's coupon rate and its current market price. 
      • Relationship with Coupon Rate:
        • Bond purchased at par (market price = par value): YTM = Coupon Rate
        • Bond purchased at a discount (market price < par value): YTM > Coupon Rate (investor earns higher return to compensate for buying at a discount)
        • Bond purchased at a premium (market price > par value): YTM < Coupon Rate (investor earns lower return to compensate for buying at a premium) 
    • Here's an analogy:
      • Think of Par Rate as the "ideal" interest rate for a bond, where supply and demand meet, and the bond trades exactly at its face value.
      • YTM is the "real-world" return you get based on the actual price you pay for the bond in the market. 
  • Formula Par Rate:
    • Pt = ( 2 ( 1 - d(N) )) / At
      • At = Annuity Factor
      • d = Discount Factor
      • N = Year
      • d(N) = Discount Factor of year N
    • Example 1:
      • The spot rates for each semiannual period over two years, along with their respective discount factors, are shown below.
      • Calculate the 2-year par rate.
      • Here 
        • T = 2
        • At = 0.9840 + 0.9662 + 0.9427 + 0.9201 = 3.813 
        • d(N) = 0.9201
      • Formula: 
        • Pt = ( 2 ( 1 - d(N) )) / At
      • Solution:
        • Pt = ( 2 ( 1 - 0.9201 )) /  3.813
        • Pt = 4.19%
      • The output can be interpreted as follows: a 2-year bond paying a coupon every six months at a rate of 4.19% per year will be worth exactly par.
    • Example 2:
      • Assuming a 2-year bond pays semiannual coupons and has a par value of $100, the 2-year par rate can be computed by incorporating bond discount factors from each semiannual period as follows.
      • Here 
        • T = 2
        • At = 0.9968 + 0.9920 + 0.9848 + 0.9771 = 3.9507
        • d(N) = 0.9771
      • Formula: 
        • Pt = ( 2 ( 1 - d(N) )) / At
      • Solution:
        • Pt = ( 2 ( 1 - 0.9771 )) /  3.9507
        • Pt = 0.0116
        • Pt = 1.16%
      • The par rate of 1.16% is exactly equal to the Year 2 swap rate of 1.16%. 
      • This equality occurs because swap rates are, in fact, par rates.
      • Therefore, because we used swap rates to represent bond coupon payments when deriving discount factors, we can also say that par rates represent bond coupon payments when a bond’s price is equal to its par value.

  • Formula Value of Bond:  
  • Example:
    • With a par rate of 4.19% and a coupon of 3.25%, and based on the discount factors given previously, the value of the bond is equal to:
    • Formula Par Rate:
      • V = 1 + [ ( (c - P ) / 2 ) * At ]
      • c = coupon rate
      • V = value of the bond
    • Example:
      • At = 0.9840 + 0.9662 + 0.9427 + 0.9201 = 3.813 
      • V = 1 + [ ( (0.035 - 0.0419 ) / 2 ) * 3.813 ]
      • V = 98.21% of par


Relationship Between Spot, Forward and Par Rates

The spot, forward, and par rates are all interrelated and reflect different aspects of interest rates in the bond market. Here's a breakdown of their relationship:

Spot Rate:

  • Represents the current market yield for a bond with a specific maturity.
  • It's the interest rate an investor would earn if they bought the bond today and held it until maturity.
  • Spot rates are typically derived from the yields of actively traded zero-coupon bonds or interpolated from the yield curve.

Forward Rate:

  • Represents the locked-in interest rate for a future borrowing or lending transaction based on current market expectations.
  • It reflects the market's anticipation of future spot rates at a specific point in time.
  • Forward rates are calculated using spot rates and are relevant for interest rate swaps and other derivative contracts.

Par Rate:

  • Represents the hypothetical yield for a bond if it were priced at its par value (face value) throughout its entire life.
  • It's not a directly observable market rate but a theoretical construct used for analysis.
  • Par rates are typically derived from spot rates and the concept of present value calculations.

Understanding the Relationship:

The relationship between these rates can be summarized as follows:

  • Normal Yield Curve: When the spot rate curve is upward-sloping (short-term rates are lower than long-term rates), forward rates are generally higher than both spot rates and par rates for the same maturities. This reflects the expectation of rising interest rates in the future.
  • Flat Yield Curve: When the spot rate curve is flat (all maturities have similar rates), forward rates are generally close to or may even equal the spot rates.
  • Inverted Yield Curve: When the spot rate curve is downward-sloping (short-term rates are higher than long-term rates), forward rates are generally lower than both spot rates and par rates for the same maturities. This reflects the expectation of falling interest rates in the future.

Here's a table summarizing the relationship:

Spot Rate CurveSpot Rate vs. Par RateForward Rate vs. Spot RateForward Rate vs. Par Rate
Upward SlopingSpot > ParForward > SpotForward > Par
FlatSpot ≈ ParForward ≈ SpotForward ≈ Par
Downward SlopingSpot < ParForward < SpotForward < Par

Term StructurePar RateSpot RateForward Rate
Upward SlopingLowMiddleHigh
FlatSameSameSame
Downward SlopingHighMiddleLow

Important Note:

  • In Upward sloping Spot Rate would be lesser than Forward Rate as the yields are higher in the long term bonds comparatively to short term bonds.
  • In Downward sloping Spot Rate would be higher than Forward Rate as yields are lower in the long term bonds compartively to short term bonds.
  • These are general relationships, and there can be slight variations depending on market conditions and specific bond characteristics.
  • The concept of par rates is more theoretical, while spot and forward rates are directly relevant to actual market transactions.

By understanding the relationship between spot, forward, and par rates, you can gain valuable insights into the bond market and future interest rate expectations.


Impact of Maturity on Bond Prices and Returns

Maturity plays a crucial role in bond prices and returns. 

  • The forward rate agreement (FRA) is positive when the guaranteed rate (R) exceeds the forward rate (F). In line with this relationship, the value of a bond will fall if its coupon rate exceeds the forward rate for the inal payment period.
  • An FRA is negative when the forward rate is greater than the guaranteed rate. The value of a bond will rise when the forward rate for the last period is greater than the coupon rate, which tends to happen in an upward-sloping term structure.

Example:

  • Imagine a situation where the 2-year, continuously compounded rate is 3% and the 3- year, continuously compounded rate is 3.5%. 
  • The forward rate for the third year will be equal to 4.5%. 
  • The strategy to deploy if an investor feels that the third-year rate will be less than 4.5% would be to borrow for two years at 3% and invest for three years at 3.5%. If the third-year rate does come in under 4.5%, she will make a proit because the overall borrowing rate will be less than 3.5%.
  • If the same investor feels that the third- year rate will be greater than 4.5%, she will invest for two years and borrow for three years. This will be a proitable strategy if the third-year rate turns out to be higher than 4.5%.

Swaps and Swap Rates

  • A swap is a derivatives transaction where two parties agree to exchange payments based on the movement of an underlying asset. 
  • A fixed rate for loating rate swap involves one party making payments based on a fixed rate and receiving payments based on a loating rate, while the counterparty has the opposite position.
  • Each party believes that interest rates are moving in opposite directions and is looking to synthetically produce a more favorable outcome based on rate movements. 
  • By deinition, a derivatives transaction is a zero-sum game: one party wins and one party loses. Based on the frequency of payment, a net payment will be made each period from the party that is losing to the party that is winning.
  • Example:
    • Fixed for Floating Rate Swap:
      • Company A: This company has a fixed-rate loan (let's say 5% interest rate) but believes interest rates are going to decrease in the future. They want to lock in a lower rate if that happens.
      • Company B: This company has a floating-rate loan (interest rate based on a benchmark like LIBOR) but believes interest rates are going to increase in the future. They want to protect themselves from rising rates.
    • The Swap Agreement: To manage their interest rate risk, these companies can enter into a fixed for floating rate swap:
      • Company A pays: A fixed interest rate (e.g., 5%) to Company B for a certain period (e.g., next 5 years).
      • Company B pays: A floating interest rate (e.g., LIBOR) to Company B for the same period.
    • The Exchange of Payments:
      • Each payment period (e.g., quarterly), both companies exchange the difference between their agreed rates and the actual floating rate.
      • Example: Let's say during the first quarter, LIBOR is 4%.
        • Company A (fixed rate) pays 5% to Company B.
        • Company B (floating rate) pays LIBOR (4%) to Company A.
        • Net Payment: Company B pays the difference (5% - 4% = 1%) to Company A.
    • Who Wins or Loses?
      • The outcome depends on the direction of interest rates:
      • If interest rates decrease: Company A benefits (they pay a fixed 5% but receive a higher floating rate based on the lower LIBOR).
      • If interest rates increase: Company B benefits (they pay a lower floating rate based on LIBOR, but receive the fixed 5% from Company A).
  • Important Note:
    • A swap is not a zero-sum game in the strictest sense, because there's no inherent winner or loser. 
    • Both parties aim to manage their interest rate risk based on their beliefs about future rate movements. 
    • There is however an exchange of cash flow, and depending on the direction of interest rates, one party might benefit more than the other.
  • Additional Points:
    • Swaps are customized contracts and can involve various payment frequencies, notional principal amounts, and underlying interest rate benchmarks.
    • Swaps are complex financial instruments and should be carefully understood before entering into such agreements.
  • Notional Principal:
    • The notional principal (which is never exchanged between the parties in an interest rate swap) is the amount ($10 million in the preceding example) that the interest rates are applied to in order to determine the net payment each period.
  • Swap Rates vs Par Rates
    • Par Rate vs. Market Price:
      • Par Rate: The interest rate that equates the present value of a bond's future cash flows (coupons and principal repayment) to its face value (typically $1,000). In simpler terms, it's the theoretical rate at which a bond would trade exactly at its face value.
      • Market Price: The actual price at which a bond trades in the market, which can be above or below par depending on prevailing interest rates.
    • Swap Rates and Par Rates:
      • The swap market plays a crucial role in defining par swap rates, which are not directly equivalent to par rates for bonds, but are closely related. Here's how it works:
      • Swap Rate Definition: A swap rate is the fixed interest rate agreed upon in a swap agreement, typically an interest rate swap. In a fixed for floating rate swap, one party pays a fixed rate and receives a floating rate (like LIBOR) over a specific period.
      • Par Swap Rate: This is a specific type of swap rate where the net present value (NPV) of the swap equals zero at its inception (beginning of the swap). In simpler terms, the present value of the fixed rate payments exactly offsets the present value of the expected floating rate payments over the swap's life.
    • How Swap Market Defines Par Swap Rates (Example):
      • Imagine a 2-year interest rate swap agreement:
      • Fixed Rate (unknown): Let's say this is the rate we're trying to solve for (the par swap rate for a 2-year swap).
      • Floating Rate: Assume the floating rate is based on a benchmark like LIBOR, which is constantly changing.
    • The swap market defines the par swap rate by finding the fixed rate that makes the swap attractive to both parties. Here's the logic:
      • Investor A: Prefers fixed income and wants to receive a predictable fixed rate.
      • Investor B: Prefers floating income and wants to receive a market-based floating rate (like LIBOR).
    • Par Swap Rate Calculation:
      • To achieve a zero NPV at inception, the present value of the fixed rate payments must equal the present value of the expected floating rate payments (discounted using the current spot rates for different maturities).
      • Financial professionals use complex calculations to determine this par swap rate. It considers factors like the current spot rates for different maturities, the expected path of future interest rates, and the creditworthiness of the swap counterparties.
    • Key Point:
      • The 2-year par swap rate determined in this swap agreement doesn't directly tell you the price of a 2-year bond. However, it provides a benchmark for what the fixed interest rate of a hypothetical 2-year bond should be to trade at par (face value) if such a bond existed with the same coupon rate as the floating leg of the swap.
      • In essence, the swap market offers a way to estimate the fair value of a fixed-rate bond based on the prevailing market interest rates embedded within swap agreements. This information is valuable to investors and financial institutions when pricing and analyzing fixed-income securities.


LIBOR and OIS

LIBOR and OIS are both important benchmarks in the financial world, but they serve different purposes and reflect different types of risk. Here's a breakdown to understand the key differences:

LIBOR (London Interbank Offered Rate):

  • Definition: An average interest rate at which banks in London lend unsecured funds to each other for different maturities (overnight, 1 month, 3 months, etc.).
  • Represents: The cost of borrowing between banks and reflects counterparty credit risk. Banks perceive lending to other banks as riskier than lending to governments, so LIBOR typically carries a higher rate than OIS.
  • Fluctuations: LIBOR can fluctuate based on factors like bank health, economic conditions, and overall risk aversion in the banking system.

OIS (Overnight Indexed Swap):

  • Definition: An interest rate swap agreement derived from a central bank's overnight rate. In the US, it's based on the Federal Funds Rate set by the Federal Reserve.
  • Represents: A virtually risk-free rate of return, as the swap involves exchanging a fixed rate for the overnight rate set by a central bank, which is considered highly creditworthy.
  • Stability: OIS rates are relatively stable compared to LIBOR, as they are directly tied to central bank policy rates.

The LIBOR-OIS Spread:

The difference between LIBOR and OIS rates (LIBOR - OIS) is a crucial metric for understanding credit risk in the banking system.

  • Narrow Spread: A narrow spread indicates low credit risk and confidence in the banking system's health.Banks are comfortable lending to each other at rates close to the risk-free rate.
  • Wide Spread: A wide spread indicates higher credit risk and potential stress in the banking system. Banks demand a higher premium (reflected in the spread) to lend to each other.

Here's an analogy:

  • Think of LIBOR as the interest rate you might ask your friend for a loan (reflects your friend's creditworthiness and risk of default).
  • OIS is like the interest rate offered by a reputable bank (considered risk-free). The spread between the two represents the additional risk premium you would charge your friend compared to a trusted bank.

In conclusion:

  • LIBOR reflects bank-to-bank lending rates and incorporates credit risk.
  • OIS reflects the risk-free rate set by central banks.
  • The LIBOR-OIS spread is a key indicator of credit risk in the banking system.

Yield Curve Shapes

Historically, the yield curve has taken on three fundamental shapes, as shown below:
Yield Curve Shapes
  • Normal Curve
    • For shorter loans the interest rate is low and for longer periods the interest rate is high
  • Flat Curve
    • Same interest rate throughout though generally not usual
  • Inverted Curve
    • During the recession in the short term higher interest rates whereas in the long term lesser interest rate

Parallel Shift

When the yield curve undergoes a parallel shift, the yields on all maturities change in the same direction and by the same amount. As indicated below, the yield curve's slope remains unchanged following a parallel shift.

Parallel Yield Curve Shift

  • The angle of the lines is the same.
  • For all the maturity interest rates have increased in the same direction and by the same amount.
  • For all maturity in real life is very rare to see interest rates increase the same basis point.


Non Parallel Shift

When the yield curve undergoes a nonparallel shift, the yields for the various maturities change by differing amounts. The yield curve's slope after a nonparallel shift is not the same as before the shift. Nonparallel shifts fall into two general categories: twists and butterfly shifts.

Yield curve twists

A yield curve twist refers to a situation where the interest rates for different maturities of bonds change unevenly. Yield curve twists are yield curve changes when the slope becomes either flatter or steeper. 

  • Flattening and Steepening: 
    • Flattening:
      • A flattening yield curve indicates that the difference (spread) between yields on long-term and short-term bonds is decreasing. 
      • Falling Long-Term Rates: 
        • This might happen due to decreased expectations for future inflation or economic growth, causing investors to move to safer, long-term investments. 
      • Rising Short-Term Rates: 
        • Frequently seen when central banks such as the Federal Reserve increase interest rates to combat inflation, pushing up rates on the short end. 
      • Example: 
        • Suppose the yield on a 10-year bond decreases from 3% to 2.5%, while the yield on a 2-year bond increases from 1% to 1.5%. The spread narrows, resulting in a flatter curve.
    • Steepening:
      • A steepening yield curve occurs when the spread between long-term and short-term bond yields increases. 
      • Rising Long-Term Rates:
        • If long-term economic prospects improve or there is an expectation of higher inflation, investors will demand higher yields for long-term bonds due to the increased risk of inflation eroding the value of future payments.
      • Falling Short-Term Rates:
        • This could occur when the central bank lowers interest rates to stimulate economic growth in response to a recession or a slowdown, reducing the yield on shorter-term securities.
      • Example:
        • If the yield on a 10-year bond rises from 2.5% to 3% and the yield on a 2-year bond decreases from 1.5% to 1%, the yield curve steepens due to the increasing spread.
  • Upward Twist and Downward Twist:
    • Upward Twist:
      • Definition:
        • An upward twist occurs when short-term interest rates are much lower than long-term rates, causing the yield curve to slope upwards.
      • Cause:
        • This shape can result from expectations of economic improvement in the future, where investors anticipate rising inflation or increased demand for borrowing in the long term.
      • Implications:
        • It can signal expectations of future economic growth and inflation, potentially affecting decisions on lending and borrowing durations.
    • Downward Twist:
      • Definition:
        • A downward twist happens when short-term interest rates are higher than long-term rates, causing the yield curve to slope downwards.
      • Cause:
        • This shape can result from expectations of economic slowdown or recession, where short-term rates rise due to central bank tightening or decreased demand for immediate borrowing.
      • Implications:
        • It may indicate economic caution or uncertainty, influencing decisions on investments and lending practices.
  • Bull:
    • In financial markets, "bull" typically refers to optimism or a rising market.
  • Bear: 
    • "Bear" generally signifies pessimism or a declining market.
  • Example: 
    • Investor A expects an upward-sloping term structure to flatten in the coming months, with long-term rates falling and short-term rates rising. Investor B expects the same term structure to go in the opposite direction. Describe the appropriate strategies for each investor.
    • Investor A: 
      • Expecting a Flattening Yield Term Structure Investor A anticipates that:  
        • Long-term interest rates will decrease. 
        • Short-term interest rates will increase. 
        • This leads to a flattening of the yield curve. 
      • Strategy: Investor A should:  
        • Take a long position in longer-term bonds: 
          • By buying longer-term bonds now, Investor A can benefit from the potential rise in bond prices as their yields drop. 
          • When bond yields decrease, the existing bonds with higher coupon rates become more valuable. 
        • Take a short position in shorter-term bonds: 
          • At the same time, Investor A should sell short-term bonds expecting their prices to drop as their yields rise. 
          • In this way, Investor A can potentially buy these same bonds back at a lower price in the future. 
      • Example: 
        • Suppose Investor A buys a 10-year bond with a yield of 3% and simultaneously shorts a 2-year bond with a yield of 1.5%. If the yield on the 10-year bond decreases to 2.5% while the yield on the 2-year bond increases to 2%, the price of the 10-year bond will increase (since bond prices move inversely to yields), and Investor A will profit. 
        • Conversely, the price of the 2-year bond will decrease, and the short position will also be profitable when covered.  
    • Investor B: 
      • Expecting a Steepening Yield Term Structure Investor B anticipates that:
        • Long-term interest rates will increase.
        • Short-term interest rates will decrease.
        • This would result in a steepening of the yield curve.
      • Strategy: Investor B should:
        • Take a short position in longer-term bonds:
          • Expecting that the yields will rise (and prices will fall), Investor B can profit by borrowing and selling long-term bonds now and buying them back at a lower price later as their yields increase.
        • Take a long position in shorter-term bonds:
          • Investor B should buy short-term bonds anticipating a fall in their yields and a corresponding rise in prices.
          • This would allow Investor B to sell these bonds at a higher price in the future.
      • Example:
        • Assuming Investor B shorts a 10-year bond with a current yield of 3% and buys a 2-year bond with a yield of 1.5%.
        • If the yield on the 10-year bond rises to 3.5% (thus reducing its price) and the yield on the 2-year bond drops to 1%, the price of the 2-year bond will increase. 
        • Hence, Investor B will profit from the short position by buying back the 10-year bond cheaper and from the long position as the price of the 2-year bond increases.  
    • Conclusion 
      • Both investors are employing strategies based on their forecasts about the direction of the yield curve movement.
      • These strategies hinge on opposing views about economic conditions like inflation expectations, economic growth forecasts, and central bank policies.
      • Each strategy aligns with a specific forecast scenario and involves handling the associated risks by balancing their investment positions according to expected changes in yield curve dynamics.
  • Economic Indicators: 
    • Flattening may indicate pessimistic economic outlooks or a reaction to interest rate hikes. 
    • Steepening often indicates optimistic economic expectations or an active response to economic slowdowns. 
  • Investment Strategies:
    • Investors will adjust their portfolios based on these movements. 
    • A steepening curve might prompt investment in long-term bonds to lock in higher returns before yields drop, while a flattening curve might lead investors to prefer short-term bonds due to lower risk and relatively better returns. 
  • In sum, movements in the yield curve—whether flattening or steepening—are watched closely by economists, traders, and policy makers as they reflect collective market expectations for future economic conditions and central bank actions. Interpreting these movements helps in making informed investment decisions and anticipating economic cycles.


Yield curve butterfly shifts

  • Yield curve butterfly shifts represent a specific form of change in the structure of the yield curve, which is different from the more generally discussed shifts like steepening or flattening. 
  • These shifts affect the curvature at the middle maturities relative to the shorter and longer maturities. 
  • Understanding positive and negative butterfly shifts can be crucial for bond traders and investors aiming to manage interest rate risks effectively.  
  • Positive Butterfly Shift (Becomes less curved):
    • This occurs when the yields on both the short-end and long-end of the curve move by a larger magnitude compared to the intermediate maturities. 
    • Conceptually, this flattens the middle part of the curve while steepening the extremes, making the overall curve look 'less curved' or flatter towards the center. 
    • Visually, if you were to graph this, the yield curve would resemble a less pronounced "U" shape.
    • Example:
      • If the yield on 2-year bonds increases by 50 basis points and 10-year bonds also increase by 50 basis points, but 5-year bonds increase only by 20 basis as its elasticity is different from LEAPs.
      • Thus, the midsection of the yield curve appears flatter relative to its ends.
  • Negative Butterfly Shift (More curvature introduced):
    • Here, the yields at the midterm maturities change by a greater degree than those at both the short and long ends of the curve.
    • This results in a more pronounced curve, especially around the middle maturities. 
    • This effect causes the middle part of the curve to become steeper relative to the ends, increasing the overall curvature of the yield curve. 
    • Example:  
      • If the yield on 2-year and 10-year bonds both increase by 10 basis points, but the yield on 5-year bonds increases by 40 basis points, the yield curve would show a pronounced dip or peak in the middle, depending on the context of other rates, enhancing its curvature. 
  • Strategies and Impact: 
    • Investment Decisions: 
      • Traders focusing on interest rate strategies can use predictions about butterfly shifts to position their portfolios. 
      • For example, if expecting a positive butterfly, one might over-weight shorter and longer maturities compared to intermediates. 
    • Risk Management: 
      • Understanding these shifts helps in hedging strategies, where the focus is on managing interest rate risks associated to various maturities. 
  • Applications: 
    • Bond Trading: 
      • Bond traders can leverage butterfly trades, which involve taking positions in bonds of three different maturities to capitalize on expected changes in the shape of the yield curve. 
    • Speculation and Hedging: 
      • Speculators might use derivatives like options on Treasury futures to speculate on these shifts, while institutional investors might adjust their portfolio’s duration by altering weights across different maturities to hedge against interest rate risks. 
  • Butterfly shifts highlight the nuanced changes in the yield curve that go beyond simple up or down movements. 
  • By understanding these shifts, traders and analysts can fine-tune their strategies to better anticipate and react to changes in economic indicators, central bank policies, or market sentiment dynamics.



Credits and References

  • https://economictimes.indiatimes.com/thumb/msid-102397550,width-1200,height-900,resizemode-4,imgsize-62394/interest-rates-what-is-it-and-how-does-it-affect-your-personal-finance-and-your-countrys-economy.jpg?from=mdr




Scarcity Brings Efficiency: Python RAM Optimization

  In today’s world, with the abundance of RAM available, we rarely think about optimizing our code. But sooner or later, we hit the limits a...