Пример #1
0
from pandas.io.data import DataReader
from datetime import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
randn = np.random.randn

f = lambda x: float(x)

SPX = DataReader("SP500",  "fred", datetime(2013,1,1), datetime(2013,05,05) ) #SPX
SPX=SPX['SP500'].replace('.',np.nan).fillna(method='ffill')
SPX=pd.DataFrame(SPX)
SPX=SPX.applymap(f)

#dr = pd.date_range('1/1/2013', periods=20, freq=3 * pd.datetools.bday)

start = datetime(2013, 1, 1)
end = datetime(2013, 5, 11)
#startrng = pd.bdate_range(start,end,freq='BQS-MAR')
#startrng = pd.bdate_range(start,end,freq='BMS')                                      #first business day of month
startrng = pd.bdate_range(start,end,freq='WOM-2TUE')                                  #second Tuesday of month

#startrng = startrng + pd.datetools.WeekOfMonth(week=1,weekday=4) - pd.datetools.BDay()
print startrng


SPX=SPX.reindex(startrng)
print SPX
Пример #2
0
LI3=pd.date_range(start, end, freq='D')

#functions--------------------
f = lambda x: float(x)


df = DataReader('SP500', "fred", start,end)
df=df.applymap(f)

#calculate average per year
annual_df = df.resample('M', how='mean')
print annual_df.to_string()

#calculate return index
df['ret'] = df['SP500'].pct_change()
df=df.reindex(columns=['SP500','ret'])
df['ri'] = (1 + df['ret']).cumprod()

# calculate monthly returns
m_returns = df['ri'].resample('BM', how='last').pct_change()
print m_returns

# turn business day into full days
df=df.resample('D')
# print df.to_string()

#plot DEC 2012 closes
plt.plot(df['SP500'].ix['2012-12'])
plt.show()