pandas_resampling.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import pickle
  2. import pandas as pd
  3. import quandl
  4. import matplotlib.pyplot as plt
  5. from matplotlib import style
  6. style.use('seaborn')
  7. api_key = 'rFsSehe51RLzREtYhLfo'
  8. def state_list():
  9. fifty_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')
  10. return fifty_states[0][0][1:]
  11. def initial_state_data():
  12. states = state_list()
  13. main_df = pd.DataFrame()
  14. for abbv in states:
  15. query = 'FMAC/HPI_' + str(abbv)
  16. df = quandl.get(query, authtoken=api_key)
  17. df.columns = [str(abbv)]
  18. df[abbv] = (df[abbv] - df[abbv][0]) / df[abbv][0] * 100.0
  19. if main_df.empty:
  20. main_df = df
  21. else:
  22. main_df = main_df.join(df)
  23. pickle_out = open('fifty_states_pct.pickle', 'wb')
  24. pickle.dump(main_df, pickle_out)
  25. pickle_out.close()
  26. def HPI_Benchmark():
  27. df = quandl.get('FMAC/HPI_USA' , authtoken=api_key)
  28. df['United States'] = (df['Value'] - df['Value'][0]) / df['Value'][0] * 100.0
  29. pickle_out = open('us_pct.pickle', 'wb')
  30. pickle.dump(df, pickle_out)
  31. pickle_out.close()
  32. # fig = plt.figure()
  33. ax1 = plt.subplot(1,1,1)
  34. # initial_state_data()
  35. pickle_in = open('fifty_states_pct.pickle' , 'rb')
  36. HPI_data = pickle.load(pickle_in)
  37. # HPI_Benchmark()
  38. pickle_in = open('us_pct.pickle','rb')
  39. benchmark = pickle.load(pickle_in)
  40. # HPI_data = HPI_data.pct_change()
  41. # HPI_data.plot(ax=ax1)
  42. # benchmark['United States'].plot(ax=ax1, color='k', linewidth=10)
  43. # plt.legend().remove()
  44. HPI_complete_data = HPI_data
  45. HPI_complete_data['United States'] = benchmark['United States']
  46. US1YR = benchmark['United States'].resample('A').mean() # new method of resampling
  47. HPI1YR = HPI_data.resample('A').mean() # can change rate of sampling and method of sampling
  48. US1YR.plot(ax=ax1)
  49. benchmark['United States'].plot(ax=ax1)
  50. plt.legend(['Yearly sampled', 'Monthly sampled']) # original data is sampled monthly
  51. plt.show()