Build a Robo Advisor with Python From Scratch Automate your financial and investment decisions MEAP Rob Reider 2024 scribd download
Build a Robo Advisor with Python From Scratch Automate your financial and investment decisions MEAP Rob Reider 2024 scribd download
com
https://ebookname.com/product/build-a-robo-advisor-with-
python-from-scratch-automate-your-financial-and-investment-
decisions-meap-rob-reider/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookname.com/product/data-science-from-scratch-first-
principles-with-python-1st-edition-joel-grus/
ebookname.com
https://ebookname.com/product/writing-a-c-compiler-build-a-real-
programming-language-from-scratch-1st-edition-nora-sandler/
ebookname.com
https://ebookname.com/product/automate-the-boring-stuff-with-python-
practical-programming-for-total-beginners-2nd-edition-al-sweigart/
ebookname.com
https://ebookname.com/product/growth-employment-and-poverty-in-latin-
america-1st-edition-cruces/
ebookname.com
The Historical Imagination in Nineteenth Century Britain
and the Low Countries Hugh Dunthorne
https://ebookname.com/product/the-historical-imagination-in-
nineteenth-century-britain-and-the-low-countries-hugh-dunthorne/
ebookname.com
https://ebookname.com/product/effective-project-management-
traditional-agile-extreme-5th-edition-robert-k-wysocki-ph-d/
ebookname.com
https://ebookname.com/product/relativity-gravitation-and-cosmology-a-
basic-introduction-2005-en-356s-ta-pei-cheng/
ebookname.com
https://ebookname.com/product/afghanistan-the-soviet-invasion-and-the-
afghan-response-1979-1982-m-hassan-kakar/
ebookname.com
Introduction to Multiple Antenna Communications and
Reconfigurable Surfaces 1st Edition Emil Björnson
https://ebookname.com/product/introduction-to-multiple-antenna-
communications-and-reconfigurable-surfaces-1st-edition-emil-bjornson/
ebookname.com
Build a Robo-Advisor with Python (From Scratch)
1. welcome
2. 1_The_Rise_of_Robo_Advisors
3. 2_An_Introduction_to_Portfolio_Construction
4. 3_Estimating_Expected_Returns_and_Covariances
5. 4_ETFs:_The_Building_Blocks_of_Robo_Portfolios
6. 5_Monte_Carlo_Simulations
7. 6_Financial_Planning_Using_Reinforcement_Learning
8. 7_Measuring_and_Evaluating_Returns
9. 8_Asset_Location
10. 9_Tax-Efficient_Withdrawal_Strategies
11. 10_Optimization_and_Portfolio_Construction
12. 11_Asset_Allocation_by_Risk:_Introduction_to_Risk_Parity
13. 12_The_Black-Litterman_Model
14. 13_Rebalancing:_Tracking_a_Target_Portfolio
15. 14_Tax-Loss_Harvesting:_Improving_after-tax_returns
welcome
Thank you for purchasing the MEAP version of our book, Build a Robo-
Advisor with Python (From Scratch). We’ve enjoyed writing it, and we hope
you’ll enjoy - and benefit from - reading it. We look forward to hearing your
feedback and suggestions for making it even better.
We hope that readers will learn about both finance and Python by reading the
book. It isn’t intended to teach either of those topics from the ground up - we
expect that readers will have a basic understanding of both financial concepts
and Python programming - but accessibility is important to us. If there are
places where you feel we are assuming too much knowledge of either, please
let us know. We also hope you’ll let us know if you feel like any chapters are
too basic. We recognize that not all readers will benefit from every chapter,
but we hope that every chapter is useful to someone.
In this book
welcome 1 The Rise of Robo Advisors 2 An Introduction to Portfolio
Construction 3 Estimating Expected Returns and Covariances 4 ETFs: The
Building Blocks of Robo Portfolios 5 Monte Carlo Simulations 6 Financial
Planning Using Reinforcement Learning 7 Measuring and Evaluating Returns
8 Asset Location 9 Tax-Efficient Withdrawal Strategies 10 Optimization and
Portfolio Construction 11 Asset Allocation by Risk: Introduction to Risk
Parity 12 The Black-Litterman Model 13 Rebalancing: Tracking a Target
Portfolio 14 Tax-Loss Harvesting: Improving after-tax returns
1 The Rise of Robo Advisors
This chapter covers
The increasing popularity of robo advisors
Key features and a comparison of popular robo advisors
Python in the context of robo advising
In this book, we show how anyone with a basic understanding of Python can
build their own robo advisor. We hope this will be useful for anyone who
wants to work in this area or wants to apply these algorithms for their own
portfolio or advise others.
Aside from the core asset allocation, there are a handful of features that robo
advisors provide. We will cover most of these in more detail later in the
book; here we only provide a high-level description of each one.
Aside from these important features, robo advisors vary in two additional
dimensions - their management fee and the minimum account size. While
there is some dispersion in these values, both are usually quite low compared
to traditional investment advisors, making most robo advisors accessible to
clients in the earliest stages of their careers.
This is not to say that robo advisors can't expand into areas that have
traditionally been the domain of human advisors. For example, financial
advisors are often called upon to help retirees with defined-benefit pension
plans on whether to take a lump sum or monthly payments for life. The same
Python programs used to analyze Social Security can be adapted to analyze
pensions. Of course, there are some things that robo advisors will never be
able to do - software will never get you basketball tickets (no matter how
large your account gets) or treat you to dinner.
1.2 Advantages of Using a Robo Advisor
There are several advantages of using a robo advisor over either using a
human advisor or do-it-yourself investing. We highlight three of those
advantages here.
Surveys show that about 30% of Americans use a financial advisor of some
kind. Fee-based financial advisors charge fees based on a percentage of assets
under management (AUM), an annual retainer, or an hourly charge, and
sometimes a combination of these. In addition to fee-based financial advisors,
some advisors instead follow a commission-based model, where they are
compensated by charging commissions on financial transactions and products
like life insurance or annuities. For those that charge an AUM fee, which is
the largest category, the average fee is about 1% per year. Robo advisor fees
are a fraction of that (see table above). In addition, robo advisors usually have
much lower minimum account sizes than financial advisors.
Even small savings, when accumulated over decades, can make a big
difference. A 1% annual fee charged by a traditional human advisor may not
seem like much, but the cost compounds over time. Imagine starting out with
a $100,000 investment which earns a 7% return each year, before fees. The
1% fee charged by a traditional advisor reduces the return to 6% annually.
This means that after 30 years, the $100,000 investment would grow to about
$570,000. Not bad, but let’s compare this to a typical robo advisor charging
0.25% per year. With the robo advisor, the investment would grow to about
$710,000 - almost 25% more!
To illustrate how consequential those decisions can be and how much you
can save by employing the best strategy for a given set of circumstances, the
figure below shows how long your money will last for those four strategies.
The specific set of assumptions and the details of the strategy will be covered
later, but the point is that it makes a big difference. The optimal strategy can
extend your assets by many years.
Figure 1.1 Decumulating tax-efficiently can make your money last longer
1.2.3 Avoid Behavioral Biases
It is well-documented that investors are subject to numerous behavioral
biases, many of which can be avoided by algorithm-based automated trading.
Disposition effect Studies have shown that investors tend to hold onto
losing stocks, hoping to get back to break even. However, robo advisors
realize it’s often useful to sell losing stocks to harvest tax losses.
Herd behavior Investors tend to be influenced by others, which
explains why they dive into stocks during bubbles and panic during
crashes. Herding might have conferred benefits when fleeing predators
in prehistoric times, but it is not a great investment strategy. Robo
advisors, on the other hand, unemotionally rebalance gradually toward
stocks during crashes and away from stocks during bubbles.
Overtrading Several studies on overtrading have all reached the same
conclusion: the more active a retail investor tends to be, the less money
they make. Individual investors may incorrectly assume that if they are
not paying brokerage commissions, there is no cost to frequent trading.
However, commissions are only one cost. The bid/ask spread, the
difference between the price you can buy a stock and sell a stock on an
exchange, is a significant component of trading costs. Also, frequent
trading leads to short-term capital gains, which is not tax efficient. Robo
advisors methodically factor these costs into account when they make
trades.
Figure 1.2 Break-even analysis on the age to start claiming Social Security
In this break-even analysis, the x-axis represents the age you expect to die,
and the y-axis represents the present value of your Social Security payments
until death. As you can see from the graph, in this simple analysis that
compares claiming at 62 vs. 70, if you expect to live past 82, you are better
off waiting until 70 to claim Social Security, and if you expect to die before
82, you are better off claiming at 62. As the chart shows, if you live to 90 and
claim at 70, the present value of all payments is about $500k.
What is this analysis missing, and how can Python be used to improve the
analysis? First of all, the analysis gets exponentially more complicated when
spouses are considered, and the Social Security rules can get very
complicated. Although the break-even analysis above can be done in a
spreadsheet, taking into account couples and all the Social Security rules
would overwhelm a spreadsheet and must be coded in a computer language
like Python.
Throughout the book, we aim to not only explain what robo advisors
currently do but also introduce various tools that few, if any, advisors
currently use. We already mentioned the chapter on using AI to solve
financial planning problems. We also have a chapter on “asset location,”
which involves strategically distributing different types of assets among
existing taxable, tax-deferred, and tax-exempt accounts to minimize taxes.
Whereas asset allocation involves tradeoffs between risk and reward, asset
location is close to a free lunch. However, the strategy can get quite complex,
which perhaps explains why it has not been widely adopted.
All of these qualities make Python easy to learn and work with for any
programmer. But what makes Python a good language for robo advising? As
Python’s popularity has grown, the number of mathematical and statistical
packages has grown as well. Applications in this book will lean heavily on
pre-existing packages, including:
We should also talk about what Python isn’t. Python’s interpreted nature
means it will never be as fast as low-level compiled languages like C or
Fortran. If your application requires top speed, a compiled language may be a
better choice. This also means that bugs only show up when code is run and
won’t be found during compilation. Overall, we still think that despite these
limitations, Python is a great choice for this book. Robo advising doesn’t
require lightning speed, and we think that the ease of use and extensive
libraries and documentation outweigh any disadvantages in execution speed.
This book won’t assume that readers are Python experts but will assume a
basic familiarity. For an introduction to programming in Python, we
recommend “The Quick Python Book” by Naomi Ceder as a great place to
start.
All chapters contain examples in Python, and many include function and
class definitions. These can be found at the GitHub page for this book:
https://github.com/robreider/robo-advisor-with-python. On the GitHub page,
file names correspond to chapter numbers. Within each chapter, later code
builds on earlier code. For example, a code section in the middle of a chapter
might rely on a function defined earlier or on a package imported earlier.
Additionally, class definitions with many methods may be broken into
multiple code sections. We recommend copying or importing code from
GitHub rather than straight from the text if you are working in Python while
reading an electronic version of the book.
You want to better understand personal finance to help you with your
own finances. There is no shortage of books on personal finance for do-
it-yourself investors, but this book focuses on topics that can clearly
save you money and goes into them in depth. You won’t see chapters
found in other personal finance books like “Live within your means” or
“Don’t buy complex financial products”. Even if you have no interest in
applying these techniques in Python, the book is written so that you can
skip the Python examples and still understand the principles behind what
the algorithms do.
You are interested in working for a financial advisor or wealth
manager. As we mentioned, the number of robo advisors is growing,
and the incumbents are also getting into robo advising. Traditional
wealth managers are also using the same techniques for their clients. A
quick search on indeed.com for jobs as a “financial advisor” currently
lists over 20,000 jobs. This book provides relevant skills that are used in
the industry.
You are a Financial Advisor and would like to provide your clients with
a larger set of tools. According to the Bureau of Labor Statistics, as of
2022, there were 283,000 financial advisors in the United States. The
financial advisory business is obviously very competitive, and providing
sophisticated services gives a firm a competitive advantage. Advisors
can differentiate themselves in this crowded field and create a
competitive advantage by offering more advanced tools like the ones
described in this book. A financial advisor who can automate guidance
can service many more clients while still providing customized advice.
You are interested in useful, practical applications of Python. There is
no better way to learn Python than by applying it to interesting, practical
problems and observing intuitive results. This book will use numerous
Python libraries to solve wealth management problems. We will use a
convex optimization library and a hierarchical tree clustering library to
perform asset allocation, a statistical and random number library for
Monte Carlo simulations, and a root-finding library for measuring
portfolio performance. If you're interested in learning about AI, Chapter
6 provides several fully worked examples, from start to finish, of how
you can apply AI to solve financial planning problems.
Throughout the book, you may find that certain rules, regulations, investment
vehicles, or account types are specific to investors in the US. In most cases,
however, the concepts discussed should apply to investors outside of the US,
even if the specifics of some rules or assumptions need to be modified.
1.6 Summary
Robo advisors use algorithms to automate some of the functions of
human financial advisors.
Robo advisors have several advantages over human advisors: they have
lower fees, they can save a considerable amount of money using tax
strategies, and they can help investors avoid some well-documented
behavioral biases that detract from their performance.
Python, with its extensive libraries, can be used to implement many of
the functions of a robo advisor, from asset allocation to tax loss
optimization to Monte Carlo simulations for financial planning.
2 An Introduction to Portfolio
Construction
This chapter covers
Creating risk-reward plots
Using matrix operations to compute portfolio returns and volatilities
Calculating, plotting, and deriving the math behind the efficient frontier
Introducing a risk-free asset and the idea of the Capital Allocation Line
Gauging an investor’s risk tolerance through questionnaires
Using slider widgets to help an investor visualize the risk-reward
tradeoff
Let's start off with a simple example with only three assets: First Energy
(FE), Walmart (WMT), and Apple (AAPL). The analysis that follows can
always be generalized to include as many assets as you would like. In this
example, the assets are individual stocks, but they could easily be bonds,
ETFs, commodities, cryptocurrencies, or even hedge funds. The problem we
want to address is what are the optimal weights to assign to these three assets.
We will start off by taking the approach of the Nobel Prize-winning work of
Harry Markowitz. The Markowitz approach recognizes that investors have
two conflicting objectives. Of course, they want high returns, but they also
want low risk, and in the last section of this chapter, we discuss how to
balance these competing objectives.
Let's say the annual standard deviation of returns, or volatility of returns (we
will use these two terms interchangeably), for FE, WMT, and AAPL are
15%, 20%, and 35%, respectively. We can also represent this as a vector:
We can plot these three stocks in mean-standard deviation space, which some
call a "risk-reward" plot, using the code in Listing 2.1:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
Figure 2.1 shows the risk-reward plot when we run the code in Listing 2.1.
Suppose we represent the weights for FE, WMT, and AAPL as 1, 2, and
3, respectively. In that case, we can again write this in vector notation:
and the expected return on the portfolio is just the weighted average of the
expected returns on the three assets that make up the portfolio:
We can write this in vector notation as the dot product of vectors and :
There are several ways to do this calculation using Python and NumPy (see
the box below). In this and the following chapters, we'll use the matrix
multiplication operator @, which has a clear and concise syntax that makes
the code more readable. Listing 2.2 demonstrates how to use the operator @ to
compute the expected returns of a portfolio given the weights and expected
returns of each asset. If you run Listing 2.2, the portfolio's expected return is
9.5%.
In Listing 2.2, we transposed the second vector of weights, not the first
vector of means. Whereas in mathematics we assume vectors are column
vectors, in Python when you create a list or a one-dimensional NumPy
array, it is assumed to be a row vector. Also note that in order to take the
transpose of a vector, it has to be a NumPy array and not a list, so you
would have to create the vector of weights using, for example, w =
np.array([0.2, 0.3, 0.5]) rather than using a list w = [0.2, 0.3,
0.5].
When using the @ operator for matrix multiplication, the NumPy library
automatically applies broadcasting rules, which makes it unnecessary in
many cases to transpose one of the arrays. In other words, you can
simplify the dot product in Listing 2.2 by using mu_p = mu @ w instead
of mu_p = mu @ w.T. But if you do that, be careful that the broadcasting
rules are working the way you think they should be working.
The operator '*', when applied to arrays, does an element-by-element
multiplication rather than a matrix multiplication (multiplying entire
rows in the first matrix by entire columns in the second matrix). If we
had used an element-by-element multiplication mu * w instead of the
matrix multiplication w @ mu in Listing 2.2, it would not return the
weighted sum of expected returns for the three stocks, which is a scalar,
but rather a one-dimensional array with three elements.
To make things even more complicated, NumPy has a data structure
called a NumPy matrix, which differs from a NumPy array. If you
convert the NumPy arrays to NumPy matrices, then the '*' operator does
a true matrix multiplication, not an element-by-element multiplication.
and if and are the same, it's just the variance of the asset:
Listing 2.3 Computing the covariance matrix from volatilities and correlations
Covariance matrix:
[[0.0225 0.003 0.008925]
[0.003 0.04 0.0182 ]
[0.008925 0.0182 0.1225 ]]
For assets and writing each term in terms of covariances, we can generalize
the volatility of a portfolio as a double summation:
Random documents with unrelated
content Scribd suggests to you:
composer’s works. For, far from being an imitator of Schumann’s
style, he appeared at once in his own strong personality and as a
stranger, who even in Leipsic was not understood. Yet he found
publishers for three pianoforte sonatas, a scherzo, a trio and several
songs. For years the interest in him was confined to a small circle. He
stayed for a while in Hanover, making from there several concert
tours with Joachim or Stockhausen, the great singer, another
devoted friend, visiting also Schumann in his retreat in the Endenich
hospital. In his variations on a theme from Schumann’s Op. 99, he
gave a touching expression to his sympathy with the master’s
sufferings. After the publication of these and the ballads Op. 10,
Brahms devoted several years to profound study. Schumann’s praise
had not spoiled him, nor was he discouraged by the lack of success.
For a few seasons he was the director of the orchestra and chorus in
Detmold, spending also some time in Hamburg and in travelling.
Meanwhile he finished many songs and choruses, two serenades for
orchestra, and two sextets. In Jan., 1859, he played in Leipsic his first
great pianoforte concerto; most of the criticisms thereon were,
however, such as to now excite our mirth. It was in Switzerland and
Vienna that his genius found a sincere recognition. About thirty
years ago the writer first saw Brahms in his Swiss home; at that time
he was of a rather delicate slim-looking figure, with a beardless face
of ideal expression. Since then he has changed in appearance, until
now he looks the very image of health, being stout and muscular, the
noble, manly face surrounded by a full gray beard. The writer well
remembers singing under his direction, watching him conduct
orchestra rehearsals, hearing him play alone or with orchestra,
listening to an after-dinner speech or private conversation, observing
him when attentively listening to other works, and seeing the modest
smile with which he accepted, or rather declined, expressions of
admiration.
The Alpine summits and glaciers had great attractions for Brahms,
but also the welcome which he was always sure to find in Basel and
Zürich. For his permanent home he selected Vienna, in 1862, where
he was surrounded by the spirits of the classic masters. He was
received most favorably. His interpretation of Bach, Beethoven,
Schubert and Schumann was particularly praised. He was appointed
chorus master of the Sing-Academie for a season, and prepared a
memorable performance of Bach’s Passion Music. Yet his genius
would not allow him to devote much time to such services, and once
only in later years he accepted a similar appointment, directing from
1872–1875 the concerts of the “Society of the Friends of Music.”
Aside from this all his time was devoted to composing, interrupted
only by frequent journeys to performances of his works, and by
giving valuable assistance in the revision of the works of Couperin,
Mozart and Chopin. During the first years of his residence in Vienna
he finished many important chamber works, variations, waltzes and
Hungarian dances for the pianoforte, and vocal compositions of
every kind. The first great success was won by the “German
Requiem,” begun after the death of his mother in 1866, and
completed, for the greater part, in Switzerland, in the two following
years. After the first famous performance in the Bremen Cathedral in
the spring of 1868, it was soon heard in other cities and was greatly
admired, although certain features were severely criticised. Other
works of high importance followed: the “Song of Destiny,” “Rinaldo,”
the “Rhapsody,” Op. 53, the “Song of Triumph” for the celebration of
the happy ending of the Franco-German war, besides many songs,
chamber works, and the charming Love-Song Waltzes. By all these
works Brahms rose gradually higher and higher in the general
estimation both at home and abroad. But he steadfastly avoided the
one field in the reform of which all musical interest seemed to centre,
—the opera. Perhaps the time will come when we may be fully
informed as to his relation to dramatic music and the reasons which
kept him away from the stage. Much might be guessed. But it is
needless to pay attention to mere rumors and suppositions. There
were other fields in which he was called upon to achieve great things.
Nothing shows better the greatness of Brahms’ artistic character
than the fact that, in spite of Schumann’s prophecy and many early
instrumental masterpieces, he waited with his first symphony until
he was a man of over forty years. Four great symphonies have
appeared between 1876 and 1885, preceded by orchestral variations
on a theme of Haydn; also, during the same time, two overtures, a
second pianoforte concerto, one for violin, two smaller choruses with
orchestra, chamber works, piano pieces and songs. Another great
choral composition, “Deutsche Fest-und Gedenksprüche,” a double
concerto for violin and violoncello, Gipsy songs and many other vocal
and chamber works complete the list of his more recent
compositions. And more great things may be expected from him. If
there is anything inspiring in the present aspect of musical art, it is
the fact that Johannes Brahms is still among us, physically and
mentally as strong as if perpetual youth were granted to him. Indeed,
the graces and heroes have not only kept watch at his cradle, but
guided him throughout his long career.
JOHANNES BRAHMS.
In early youth.
Those who have met him will never forget the impression of his
strong personality. Nor will those who saw him conduct or heard him
play ever enter into the superfluous discussion whether he was a
great leader of orchestra and chorus or a master of his instrument.
For in both directions he was not only equal to the most exacting
demands, but always appeared as if inspired, and inspiring
everybody who sang or played under him or listened to the genius of
his music. At the pianoforte and the conductor’s desk he is a king,
but socially he appears unaffected and easy, neither reticent nor
predominating in conversation, jolly and kind among friends and
children. He has never married. Many honors have been conferred
upon him: the degrees of Doctor of Music by the University of
Cambridge, England, in 1877, and of Doctor of Philosophy by the
Breslau University in 1879; also several orders and the membership
of many societies and institutes. Throughout the musical world his
music, especially his instrumental works, is now received with
enthusiasm, although still finding a strong opposition on the part of
many critics of either too conservative or too progressive tendencies.
Yet the time is not far distant when it will be generally granted a high
position in the history of our art.
JOHANNES BRAHMS.
Louis Keeserborn
CARL GOLDMARK