# bandwith portfolio rebalancing in python

I want to calculate a bandwith rebalancing machanism for a portfolio of two assets. As soon as the performance of one ov the assets gets bigger or smaller than the other one + a defined tolerance level, one starts a recalculation of the relative value from that point of time on. The code explained below tries to do exactly that.

Below you find the code I wrote to calculate a relative change in value of df.a and df.b while df is a dataframe. What has to be calculated is basically df["c"] = df.a/df.a.iloc[df.d].values. df.d is set equal to df.t if df.a/df.a.iloc[df.d].values is bigger or smaller than df.b/df.b.iloc[df.d].values * (1+ tolerance)

The problem is that the code currently brings the following error code: ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', u'occurred at index 2011-01-01 00:00:00')and I absolutely don't know why...

import pandas as pd
import numpy as np
import datetime

randn = np.random.randn
rng = pd.date_range('1/1/2011', periods=10, freq='D')

df = pd.DataFrame({'a': [1.1, 1.2, 2.3, 1.4, 1.5, 1.8, 0.7, 1.8, 1.9, 2.0], 'b': [1.1, 1.5, 1.3, 1.6, 1.5, 1.1, 1.5, 1.7, 2.1, 2.1],'c':[None] * 10},index=rng)

df["t"]= np.arange(len(df))
tolerance = 0.3

def set_t(x):
if df.a/df.a.iloc[df.d].values < df.b/df.b.iloc[df.d].values * (1+tolerance):
return  df.iloc[df.index.get_loc(x.name) - 1]['d'] == df.t
elif df.a/df.a.iloc[df.d].values > df.b/df.b.iloc[df.d].values * (1+tolerance):
return df.iloc[df.index.get_loc(x.name) - 1]['d'] == df.t

df['d'] = df.apply(set_t, axis =1)

#df["d"]= [0,0,0,3,3,3,6,7,7,7] this should be the coutcome for d

df["c"] = df.a/df.a.iloc[df.d].values


The desired outcome looks like this:

              a    b         c  d  t
2011-01-01  1.1  1.1  1.000000  0  0
2011-01-02  1.2  1.5  1.090909  0  1
2011-01-03  2.3  1.3  2.090909  0  2
2011-01-04  1.4  1.6  1.000000  3  3
2011-01-05  1.5  1.5  1.071429  3  4
2011-01-06  1.8  1.1  1.285714  3  5
2011-01-07  0.7  1.5  1.000000  6  6
2011-01-08  1.8  1.7  1.000000  7  7
2011-01-09  1.9  2.1  1.055556  7  8
2011-01-10  2.0  2.1  1.111111  7  9


Any ideas how to solve that?

• any luck here? I tried to the same thing and couldn't solve it either. – vol_of_vol Sep 27 '15 at 19:06
• an if statement is normally applied to a scalar, but your if statement is being applied to an array-like thingy, making it ambiguous, For example 0 is clearly false and 1 is clearly true but what about [0 1 0 1 1 1 0], is it true or false, nobody knows. – noob2 Sep 28 '15 at 19:53
• A similar question was answered here stackoverflow.com/questions/30745160/… – jacob Oct 17 '18 at 7:48