[Python] Get economic data with DataReader

The following chart was introduced on twitter. VIX_SP500rtn.png This chart is

The horizontal axis is VIX (VIX), and the vertical axis is the rate of increase / decrease for 100 days (about half a year). There is a positive correlation between the VIX level and the subsequent rate of increase / decrease, not a random walk. Since the current VIX is about 40, it seems unlikely that the return after half a year will be negative from the past cases (investment is at your own risk!)

It means that.

This chart was created using Python's pandas_datareader to obtain the VIX (Fed Index) and S & P 500 Index from the Federal Reserve Bank of St. Louis website.

Save the code here.

First, load the library.

python


import pandas as pd
import numpy as np
import pandas_datareader.data as web

import datetime
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

1. Get data with DataReader

python


#Specify the start date and last date of the data to be acquired
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2020, 5, 1)


#S&Get P500 data
# 'SP500'Is S&P500 ticker symbol.
# 'fred'However, it specifies the Federal Reserve Bank of St. Louis as the data source.
#The rest is the start date and the last day.
eq = web.DataReader('SP500', 'fred', start, end)

#Get VIX data
# 'VIXCLS'Is the VIX ticker symbol.
vix = web.DataReader('VIXCLS','fred', start, end)

#Combine the acquired data into one data frame
df = pd.DataFrame(index = eq.index)
df['Equity'] = eq
df['VIX'] = vix
df.dropna(inplace = True)

You can get various economic and financial data from the Federal Reserve Bank of St. Louis. St. Louis Federal Reserve Bank of St. Louis Website The symbol ticker is at the very end of the URL of each data.

Example: In the case of VIX, it will be VIXCLS at the end of the following address. https://fred.stlouisfed.org/series/VIXCLS

2. Create a graph

python


#Function to make a graph
def chart(days):
    dfd = df.copy()
    dfd['Return'] = (dfd['Equity'].shift(-days) /  dfd['Equity'] -1)
    dfd.dropna(inplace = True)
    plt.figure(figsize = (8,4))
    plt.scatter(x = dfd['VIX'], y = dfd['Return'], alpha = 0.6, c = dfd['VIX'])
    plt.xlabel('VIX')
    plt.ylabel(str(days)+' days Return')
    plt.title('VIX and S&P500 '+str(days)+' days Returns (USD base)')
    plt.savefig('VIX_SP500rtn',bbox_inches="tight")

#Execute function by specifying how many days of return to calculate
chart(100)

↓ This graph is made.

VIX_SP500rtn.png

plt.scatter(x = dfd['VIX'], y = dfd['Return'], alpha = 0.6, c = dfd['VIX']) ↑ By c = dfd ['VIX'] of this code, the color of the points in the graph is changed according to the value of VIX to create a gradation effect.

Bonus 1: VIX chart

python


df['VIX'].plot(title = 'VIX', figsize = (8,4))

VIX.png

Bonus 2: SP500 Chart

python


df['Equity'].plot(title = 'S&P500', figsize = (8,4))

VIX.png

in conclusion

With DataReader, you can get not only economic data of the St. Louis Fed, but also various data such as stock prices and exchange rates. See DataReader Documentation for more information.

Recommended Posts

[Python] Get economic data with DataReader
Get Youtube data with python
Get additional data in LDAP with python
[Note] Get data from PostgreSQL with Python
Data analysis with python 2
Get date with python
Data analysis with Python
Get stock price data with Quandl API [Python]
I tried to get CloudWatch data with Python
Get country code with python
Sample data created with python
Get Twitter timeline with python
Get thread ID with python
Get started with Python! ~ ② Grammar ~
Get stock price with Python
Get home directory with python
Get keyboard events with python
Get Alembic information with Python
Read json data with python
Get financial data with python (then a little tinkering)
Get data from database via ODBC with Python (Access)
Get Leap Motion data in Python.
Get started with Python! ~ ① Environment construction ~
Link to get started with python
Get data from Quandl in Python
Get reviews with python googlemap api
Get the weather with Python requests
Get web screen capture with python
Get the weather with Python requests 2
Get rid of dirty data with Python and regular expressions
How to get started with Python
Python data structures learned with chemoinformatics
[Small story] Get timestamp with Python
Get Qiita trends with Python scraping
Get data from analytics API with Google API Client for python
Easy data visualization with Python seaborn.
Process Pubmed .xml data with python
Data analysis starting with python (data visualization 1)
Get additional data to LDAP with python (Writer and Reader)
Get started with Python in Blender
Data analysis starting with python (data visualization 2)
Get weather information with Python & scraping
Python application: Data cleansing # 2: Data cleansing with DataFrame
[Introduction to Python] How to get data with the listdir function
Get data from MySQL on a VPS with Python 3 and SQLAlchemy
Try to get CloudWatch metrics with re: dash python data source
Receive textual data from mysql with python
Get html from element with Python selenium
Process Pubmed .xml data with python [Part 2]
Add a Python data source with Redash
Retrieving food data with Amazon API (Python)
Generate Japanese test data with Python faker
[Python] Get the variable name with str
Convert Excel data to JSON with python
[Python] Use string data with scikit-learn SVM
Download Japanese stock price data with python
Get Google Fit API data in Python
Manipulate DynamoDB data with Lambda (Node & Python)
Convert FX 1-minute data to 5-minute data with Python
Get Youtube data in Python using Youtube Data API
Get Started with TopCoder in Python (2020 Edition)