April 2, 2020 Python Q&A

Topics covered in this session include:

  • Overview of new Risk on / Risk off tool
  • Described the processes of how I think about writing code
  • Implemented a function and dictionary structure to simplify reading multiple symbols into a program

RiskOnOff.py

# -*- coding: utf-8 -*-
"""
Created on Sun Jan  5 11:02:36 2020

@author: Bruce1
"""

# =======================================================================
# Import Libraries
# =======================================================================
import pandas as pd 
import pandas_datareader.data as web
from   pathlib import Path
import matplotlib.pyplot as plt
#import numpy as np

# =======================================================================
# Setup Porgram Variables
# =======================================================================
symList = ['SPY', 'TLT']

startDate = '01/01/2000'

refreshData = False

#lookback     = 21
#lookbackSlow = 200
#lookbackEMA  = 9

#capital = 100000

# =======================================================================
# Gather data function
# =======================================================================
def gatherData(sym, startDate):
    import pdb; pdb.set_trace()

    savedFile = Path('./{}.xlsx'.format(sym))
    
    if savedFile.exists() == False or refreshData == True:
        print("")
        print("-> Fetching data from the web")
        df = web.DataReader(sym, data_source='yahoo', start=startDate)
    
        print("")
        print("-> Save data to file")  
        df.to_excel("{}.xlsx".format(sym))

    else:
        print("")
        print("-> Fetching data from file") 
        df = pd.read_excel(savedFile, index_col='Date', parse_dates=True)

    # =======================================================================
    # Inspect/Report on data
    # =======================================================================
    firstIndex = df.index.min()
    lastIndex  = df.index.max()
    records = len(df)
    print("")
    print("-> Importing ", sym)
    print("First Date = ", firstIndex)
    print("Last Date  = ", lastIndex)
    print("Total Days = ", records)

    if df.isnull().values.any() == True:
        print("WARNING: there are {} NaN in the data".format(df.isnull().values.sum()))
        print(df.isnull().values)
        
    return df

dfDict = {}

for sym in symList:
    
    dfDict[sym] = gatherData(sym, startDate)

import pdb; pdb.set_trace()

# =======================================================================
# Format/Normalize Data
# =======================================================================

# =======================================================================
# Calculate Correlation
# =======================================================================

# =======================================================================
# Visualize Data
# =======================================================================
Scroll to Top