DadOverflow.com

Musings of a dad with too much time on his hands and not enough to do. Wait. Reverse that.

Reading HTML into Dataframes, Part 2

In a previous post, I provided a simple example of using pandas to read tables from a static HTML file you have on disk. This is certainly valid for some use cases. However, if you’re like me, you’ll have other use cases where you’ll want to read tables live from the Internet. Here are some steps for doing that.

Step 1: Select an appropriate “web scraping” package

My go-to Python package for reading files from the Internet is requests. Indeed, I started this example with requests, but quickly found it wouldn’t work with the particular page I wanted to read. Some pages on the internet already contain their data pre-loaded in the HTML. Requests will work great for such pages. Increasingly, though, web developers are using Javascript to load data on their pages. Unfortunately, requests isn’t savvy enough to pick up data loaded with Javascript. So, I had to turn to a slightly more sophisticated approach. Selenium proved to be the solution I needed.

To get Selenium to work for me, I had to perform two operations:

  1. pip/conda install the selenium package
  2. download Mozilla’s gecko driver to my hard drive

Step 2: Import the packages I need

Obviously, you’ll need to import the selenium package, but I also import an Options library and Python’s time package for reasons I’ll explain later:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import time

Step 3: Set up some Options

This is…optional (pun completely intended)…but something I like to do for more aesthetic reasons. By default, when you run selenium, a new instance of your browser will launch and run all the commands you programmatically issue to it. This can be very helpful debugging your code, but can also get annoying after a while, so I suppress the launch of the browser window with the Options library:

options = Options()
options.headless = True  # stop the browser from popping up

Step 4: Retrieve your page

Next, instantiate a selenium driver and retrieve the page with the data you want to process. Note that I pass the file path of the gecko driver I downloaded to selenium’s driver:

driver = webdriver.Firefox(options=options, executable_path="C:\geckodriver-v0.24.0-win64\geckodriver.exe")
driver.get("https://www.federalreserve.gov/monetarypolicy/bst_recenttrends_accessible.htm")

Step 5: Take a nap

The website you’re scraping might take a few seconds to load the data you want, so you might need to slow down your code a little while the page loads. Selenium includes a variety of techniques to wait for the page to load. For me, I’ll just go the easy route and make my program sleep for five seconds:

time.sleep(5)  # wait 5 seconds for the page to load the data

Step 6: Pipe your table data into a dataframe

Now we get to the good part: having pandas create a dataframe from the data on the web page. As I explained in Part 1, the data you want must be loaded in a table node on the page you’re scraping. Sometimes pages load data in div tags and the like and use CSS to make it look like the data are in a table, so make sure you view the source of the web page and verify that the data is contained in a table node.

Initially in my example, I tried to pass the entire HTML to the read_html function, but the function was unable to find the tables. I suspect the tables may be too deeply nested in the HTML for pandas to find, but I don’t know for sure. So, I used other features of selenium to find the table elements I wanted and passed that HTML into the read_html function. There are several tables on this page that I’ll probably want to process, so I’ll probably have to write a loop to grab them all. This code only shows me grabbing the first table:

df_total_assets = pd.read_html(driver.find_element_by_tag_name("table").get_attribute('outerHTML'))[0]

Step 7: Keep things neat and tidy

A good coder cleans up his resources when he’s done, so make sure you close your selenium driver once you’ve populated your dataframe:

driver.quit()

Again, the data you’ve scraped into the dataframe may not be in quite the shape you want it to be, but that’s easily remedied with clever pandas coding. The point is that you’ve saved much time piping this data from its web page directly into your dataframe. To see my full example, check out my code here.

Reading HTML into Dataframes, Part 1

Recently, I asked a co-worker for a list of data on which I needed to work. Instead of sending me his spreadsheet as an email attachment, he pasted his spreadsheet directly into the body of an email. How in the world am I supposed to work with that? Pandas can help!

I saved his email out to disk as an HTML file. Outlook converted his pasted spreadsheet into a HTML table. Then, I just used Pandas’ read_html function to read the HTML file. It automatically found the table and converted it into a dataframe for me. Problem solved!

Step 1: Save your file as an HTML file

If the data you want to process is in a table in the body of an email, about your only option is to save that email to disk as an HTML file. Save the email, then I’d recommending opening the file in a text editor like Notepad++ and making sure the data you want to process was saved within a table element. In my example here, I simply grabbed three tables of data from the Internet and pasted them all into a single HTML file.

Step 2: Import pandas

import pandas as pd

Step 3: Read in your HTML file

Note that the read_html function returns a list of dataframes:

list_of_dfs = pd.read_html('multiple_tables.html')

Now, with your list of dataframes, you can iterate over it, find the dataframe of the data you want to work with, and have at it.

for df in list_of_dfs:
    print(df.head())

Your data might not be in quite the shape you want, but pandas has lots of ways to shape a dataframe to your particular specifications. The important point is that pandas was able to read in your data in seconds versus the time it would have taken to transform the data into a CSV or some other arrangement for parsing.

Get your documentation together

Almost seven years ago, I listened to an episode of the Survival Podcast that I still think about from time to time–an episode on estate planning. Many years later, I finally listened to it again so I could take some notes on the important documents attorney Mark Matthews (the individual interviewed in the podcast) considered important documents to create. I’m sure the law has changed much since then, but I suspect most of these documents are still important, so I will write my notes out here.

Financial Power of Attorney

A Financial Power of Attorney is a document that grants another person–an “agent”–the ability to act as you in financial matters. If you in some way become incapacitated, your agent will have access to your money to pay your bills and other expenses. One fear with a power of attorney is that the agent will simply abscond with your assets. By law, though, your agent must act as a fiduciary: someone who has a duty of care and loyalty to you. Another fear is that once the power of attorney is signed, the agent immediately inherits that power. That’s not necessarily the case: yes, you can craft the document to take effect immediately, but, alternatively, you can state that the document goes into effect only when you become “incapacitated” or “incompetent” or even “detained under duress” (if you were kidnapped abroad or jailed for a prolonged period of time).

Advanced Medical Directive

The second important document Mr. Matthews mentioned is the Advanced Medical Directive. Two important components of the Advanced Medical Directive are the Healthcare Power of Attorney and the Living Will. The Healthcare Power of Attorney designates an individual to act on your behalf in matters of healthcare. One important responsibility of this individual is managing and distributing your medical records to appropriate third parties. As obtaining medical information from doctors and hospitals can be difficult, this provision can be pretty important.

The Living Will clearly establishes how you wish to be treated should you succumb to certain medical conditions that leave you, say, living only by the grace of a machine. A Living Will makes it clear to your surviving family how they should deal with you in those situations–“pull the plug” or not and under what conditions. There is no guessing “what Mom would have wanted” and, therefore, no need for guilt or quarrel among the surviving family.

Traditional Will

Mr. Matthews mentioned Wills only after a lengthy discussion of the Financial Power of Attorney and Advanced Medical Directives, so he would seem to value those two documents above the third. Wills address a variety of concerns:

  • Who inherits what assets
  • Where minor children are concerned, who becomes the guardians of these children
  • Who is the Executor–the person in charge of dispensing the Will

Apparently, with the execution of a Will, a bond must sometimes be paid. It seems your Will can address some of those concerns–whether or not the executor must post a bond, whether or not a bondsman must be hired. Mr. Matthews called that “surety”.

Although a lot of people have drawn up wills, do your survivors know of your will and even where it is? Consider these questions:

  • Have you told your executor that he or she is your executor?
  • Does your executor know where your will is?
  • If your will is in your safe deposit box, will your survivors be able to access it after your gone?

In short, you may have a Will, but if no one knows about it or can get a copy of it, you don’t have an “executable plan.” [Cue the old tree-falling-in-the-woods joke.]

Memorandum of Distribution

A fear many have with traditional wills is that when they draw up the will, they may have a particular way they want to divvy up their assets among their survivors; however, years later, they may decide they want to change that distribution arrangement. Does that mean they have to tear up their current wills and pay more legal fees to draw up a new onewith their new distribution arrangements? In some States, the answer is “no.” Some States like Virginia honor a separate Memorandum of Distribution of Tangible Personal Property. If your State honors such a document, you can draw up a will that references this separate document that details how you wish your assets to be distributed. Then, on your own, you can write up your own Memorandum of Distribution without additional legal fees. If, later, you decide to change that distribution, you can tear up your current Memorandum and write a new one.

Bequeath the gift of Peace

One insight here from Mr. Matthews I found valuable was dispelling the attitude of just “splitting your assets X ways between your X kids” (fill in X for the number of children you have). It seems to me that, in addition to distributing your assets to your survivors according to your wishes and in the most tax efficient manner possible, you should also aim to leave your family in as much peace as possible. This means drawing up proper Advanced Medical Directives so that you can absolve your survivors of any guilt and fear they might have over making those decisions for you. This also means being very specific regarding the divvying up of your assets. Stating vaguely that your assets should be evenly split among your heirs will likely result in your heirs fighting over who gets your boat or vintage car or baseball card collection. Don’t be vague–be specific.

HIPAA Authorization Document

A HIPAA Authorization Document is a “short form” release of information authorization that your healthcare power of attorney agent can use to gather and distribute your medical information without otherwise having to fax around your entire Advanced Medical Directive. This saves time and paper, but more importantly, it preserves your privacy in that you’re only sending around this short authorization form and not your full Advanced Medical Directive with your Living Will and all those personal details contained therein.

Trusts

Everyone says “trusts are not for everyone,” but it seems to me that trusts should probably be for many people–just see my next section on Estate Taxes. Apparently, there are many flavors of trusts. Mr. Matthews discussed three:

  • Revocable Living Trust: the Revocable Living Trust is a common form of a trust. This is a trust that you set up during your lifetime and can change it at will. With this instrument, you can move your money into the trust then write up instructions to, say, incrementally distribute your funds to your children over time. You can even include instructions to have the funds of the trust invested in something that will allow the funds to grow as they sit and wait to be distributed.
  • Marital Trust: this is a trust that you establish with your spouse. If you die before your spouse and you have funds that will be subject to estate taxes, instead of passing those funds to your spouse and subjecting him or her to those estate taxes, you can instead shelter those funds in a Marital Trust.
  • Irrevocable Life Insurance Trust: this is a trust that owns a life insurance policy on you and serves as another avenue of sheltering money away from the brutal federal estate taxes.

Estate Taxes

This interview occurred in 2012. At that time, US federal law exempted the first five million dollars of a person’s estate from the estate tax. In 2013, the law changed: only the first one million dollars of a person’s estate was exempt from being taxed. In 2012, the estate tax was 35%. According to Mr. Matthews, in 2013, the tax was raised to 55%. [side note: the law may have changed again since the interview but, today, it would seem that the tax rate is 40% and the exemption seems to now be at $11 million].

The IRS has their own formula for determining what parts of your estate are subject to estate taxes. This includes your money and your house, among other assets, but, interestingly, it also includes your life insurance policies. So, if you have a one million dollar life insurance policy, that’s one million dollars subject to estate taxes, even though life insurance payouts themselves are not subject to income taxes. Go figure. So, it’s not unimaginable that a thoughtful, frugal, middle class family might bump up against or exceed the IRS’s exemption. In such instances, a trust can help soften the kick-in-the-face that is the US government. One memorable line from the interview: many heirs are “asset rich but cash poor.” If you think a portion of your estate might be subject to estate taxes, try not to leave your heirs with that bill.

Finding a good Estate Planner

So how do you go about finding an estate planner as thoughtful as Mr. Matthews?

  • You can check with your State bar association as they will be able to refer estate planning attorneys
  • Mr. Matthews recommended checking with Wealth Counsel, an organization he belongs to, for referrals
  • In general, as you converse with your estate planner, make careful observation: is your attorney truly listening to you? Is he restating your goals back to you? Is he taking notes?

Get on it

I am quite derelict in getting these documents drawn up myself, but I’m hopeful I can get at least a few of these done this year. In addition to listening to this particular podcast some time ago, I also learned about the site Get Your Sh*t Together, a site dedicated to just these tasks. I’ve not used the site–don’t know if it’s free or not–but it might be worth checking out.

« Older posts

© 2019 DadOverflow.com

Theme by Anders NorenUp ↑