• What’s a better investment stocks or real estate? Let’s write some Python code.

    I was recently chatting with a buddy about investing in real estate or stocks and which was better. I decided to use Python to analyze what that investment would look like. I used data from FRED and yfinance which is one of my favorite sources for historical data. Although they do not offer smaller timeframes.

    The first thing I’m going to do is set the dates I’m interested in.

    beginning_date = '1900-01-01'
    date_today = datetime.now()
    end_date = date_today

    I’m not going to use FRED and YFinance which are two Python plugins to download historical data.

    df = yf.download('^gspc',beginning_date,date_today,progress=True).drop(columns=['Open','High','Low','Close','Volume']).rename(columns={'Adj Close':'SP500'})
    df = df.rename(columns={'Adj Close':'SP500'})
    df['MSPUS'] = pdr.DataReader('MSPUS','fred',beginning_date,date_today)
    df = df.rename(columns={'MSPUS':'Median_House_price'})

    The stock market index symbol from Yahoo is ^gspc as you can see in the code above. The median house price is MSPUS from FRED.

    df = df.ffill(axis=0)
    df['Median_House_price_pct_change'] = df['Median_House_price'].pct_change()*100
    df['SP500_pct_change'] = df['SP500'].pct_change()*100
    df = df.dropna()
    df['Median_House_price_pct_change_cumsum'] = df['Median_House_price_pct_change'].cumsum()
    df['SP500_pct_change_cumsum'] = df['SP500_pct_change'].cumsum()
    df = df.dropna()
    df['spread'] = df['SP500_pct_change_cumsum'].sub(df['Median_House_price_pct_change_cumsum'])

    The Median house price data is quarterly so I’m using ffill to forward fill the data.

    What I’m essentially doing next is creating columns in my DataFrame for the following:

    • Percent change of asset * 100 to get the return as a percentage.
    • Cumultively summing all of the returns to get a percentage of return from a specific date.
    • Calculating the rolling spread between the two assets.

    My DataFrame now looks like this.

    If I plot the cumulative sum I get this.

    fig1 = px.line(df, x=df.index, y='Median_House_price_pct_change_cumsum', color_discrete_sequence=['red'])
    fig2 = px.line(df, x=df.index, y='SP500_pct_change_cumsum', color_discrete_sequence=['blue'])
    fig3 = go.Figure(data=fig1.data + fig2.data)

    This shows stocks overall since 1963 have outperformed housing.

      fig1 = px.line(df, x=df.index, y='spread', color_discrete_sequence=['red'])

    This code actually plots the spread between the two assets.

    Now I’m going to create some more columns in my DataFrame

    df_annual['SP500_pct_change'] = df['SP500_pct_change'].resample('1A').sum()
    df_annual['Median_House_price_pct_change'] = df['Median_House_price_pct_change'].resample('1A').sum()
    df_annual['SP500_pct_change_cumsum'] = df_annual['SP500_pct_change'].cumsum()
    df_annual['Median_House_price_pct_change_cumsum'] =  df_annual['Median_House_price_pct_change'].cumsum()
    df_annual['YoY_spread'] = df_annual['SP500_pct_change'].sub(df_annual['Median_House_price_pct_change'])
    df_annual['cumulative_spread'] = df_annual['SP500_pct_change_cumsum'].sub(df_annual['Median_House_price_pct_change_cumsum'])

    What I’m doing here is resampling my data to annual as it is broken down currently by quarter. The main difference in this code is I’m computing an annual year-over-year return of S&P 500 vs. median house price in the United States. Here is the new DataFrame header.

    I’m going to replot this data using the annualized data. Should be almost identical to my first chart.

    fig1 = px.line(df_annual, x=df_annual.index, y='Median_House_price_pct_change_cumsum', color_discrete_sequence=['red'])
    fig2 = px.line(df_annual, x=df_annual.index, y='SP500_pct_change_cumsum', color_discrete_sequence=['blue'])
    fig3 = go.Figure(data=fig1.data + fig2.data)

    And finally, I’m computing the annualized year-over-year spread between S&P 500 and median housing prices. This gives a better idea of the annual returns as opposed to the cumulative returns. Where the bar graph is above 0 indicates the stock market outperformed real estate that year. If the bar is below 0 that indicates the real estate market outperformed the stock market.

    And finally the cumulative spread.

  • ValueError: cannot set WRITEABLE flag to True of this array

    If you’re getting this error when trying to read a simple .h5 file. Change your code when you originally create the .h5 file to specify format=’table’ This should resolve the issue.

    This code does not work

    This code does work

  • Get thousands in repair costs if your vehicle was damaged on the US60 back in November

    If you’re like me and live east of the US60 there is a good chance you were driving home one random day in November only to be hit with a barrage of rocks and other asphalt materials. The cause of this was neglect by ADOT when they ripped off the asphalt layer of the freeway and didn’t clean it up properly. If you drove through this you can get the repairs paid for by the state of Arizona. Below is how I filed my claim.

    Here are the steps:

    • Get quotes to fix your vehicle and include them
    • Take a picture of the damage print it out and send it with the form
    • Take a picture of your registration and send it with the form
    • Take a picture of your license plate and send it with the form
    • Google tracks everywhere you go if this feature is turned on using something called Google Maps Timeline. I would include this as well showing travel through the area on that specific day. I don’t know if this is necessary but it makes it a lot harder to refudiate your claim. Here is my sample that I included.
    • Mail all of this to the Attorney General and if he’s not busy playing with nunchucks that day the state will send out an insurance adjuster they will then ask you to sign a form called “RELEASE OF ALL CLAIMS” and if everything checks out you will receive a check in the mail for your repairs.

    And last step, cash check.

  • The annoyance of Arizona politicians endlessly bashing California to pander to Arizona citizens

    I’m reading this article tonight on the Wall Street Journal where Mark Brvnovich ignorantly tries to bash California in an attempt to somehow boost his own *accomplishments.

    He uses this NRF organized retail crime survey on two occasions to bash California. He states the following:

    According to a 2020 survey by the National Retail Federation, three of the top 10 cities affected by organized retail crimes are in California.

    We expect our efforts will deter such theft and hope our task force becomes a model for California and other states.

    Here is the actual report he’s referencing.

    The issue with this report is there’s an almost perfect correlation to the cities impacted by crime and the largest cities by GDP. You can compare the list yourself here.

    This clearly isn’t a problem associated to policy as much as it is just a problem that comes with having a successful local economy. Perhaps instead of pointlessly bashing our neighbors to gain political points we could just focus on ourselves? Please Arizona can we just start electing normal human beings to our run our state?

  • Send SMS alerts from your trading algorithms in Python

    Occasionally there may be some important alerts that you want your trading algorithms to send to you that require immediate attention. One that I use frequently is daily account drawdown. Here’s how you can set up Twilio to send you a text message when your account enters a certain percentage of drawdown.

    Head over to Twilio

    You do need to purchase a number to text from. It costs $1/month. You can find that here.

    You’ll now need to go to your general settings page to retrieve your live credentials.

    The next step is to install Twilio on your operating system. I use Ubuntu this can be done with the following command

    sudo pip3 install twilio

    Great now you’re ready to code.

    The first thing you want to do is write a simple Python script to test your message sending capabilities. In the below code you’ll want to change a few variables:

    account_sid – Change with your Twilio information found on your account page.

    Auth_token – Change with your Twilio information found on your account page.

    Using the format +19998887777 change to_num to your cell

    Using the format +19998887777 change from_num to your Twilio phone number

    def send_sms(to_num,from_num,body_message):
        import os
        from twilio.rest import Client
        account_sid = 'Enter your account sid here'
        auth_token = 'Enter your account token here'
        client = Client(account_sid, auth_token)
            message = client.messages.create(
        except Exception as e:
    if __name__ == '__main__':

    Now that we have a function that can send text messages we just need to incorporate this into our code.

Facebook Comments Box