Financials with Pandas


In [2]:
import pandas as pd
import pandas.io.data as web

In [ ]:
data = web.get_data_yahoo('SPY', '2006-01-01')
data

px = data['Adj Close']
returns = px.pct_change()

def to_index(rets):
    index = (1 + rets).cumprod()
    first_loc = max(index.notnull().argmax() - 1, 0)
    index.values[first_loc] = 1
    return index

def trend_signal(rets, lookback, lag):
    signal = pd.rolling_sum(rets, lookback, min_periods=lookback - 5)
    return signal.shift(lag)

signal = trend_signal(returns, 100, 3)
trade_friday = signal.resample('W-FRI').resample('B', fill_method='ffill')
trade_rets = trade_friday.shift(1) * returns

# We can then convert the strategy returns to a return index and plot
# them (see Figure 11-1):

to_index(trade_rets).plot()

In [ ]: