tribo32
tribo32

Reputation: 335

How do I optimise an objective function based on dataframe data

I have a function an objective function which takes a numpy array of time series data which it uses to calculate an estimated return on investment over the time data. This function is shown below:

def bwp(x, *processed):
    pred,real = x
    money = 1000
    for i in range(0, len(processed)):
        if processed[i, 3] > pred and processed[i-1,4] > real:
            money = money + (money * processed[i, 4])
    return money * -1

I want to minimize this function, it is a cheap and discontinuous so I want to use a brute method to optimize this.

I am trying to optimize this with the following code:

def opt_2(processed):
    bounds = (slice(-1, 1), slice(-1, 1))
    resbrute = optimize.brute(bwp, ranges=bounds, args=processed, full_output=True, finish=optimize.fmin)
    print(resbrute[0])
    print(resbrute[1])

I get the error:

File "<input>", line 5, in bwp
TypeError: tuple indices must be integers or slices, not tuple

I am not sure what in bwp is causing this to fall over

EDIT: The input processed is a numpy array not a dataframe

EDIT: A sample of the data processed is:

2.90381543e+03  2.91549000e+03 -1.16745703e+01  0.00000000e+00 0.00000000e+00 -8.35888672e+00
2.89545654e+03  2.92187000e+03 -2.64134570e+01 -2.87858747e-03 2.18831140e-03 -8.35888672e+00
2.89380762e+03  2.92918000e+03 -3.53723828e+01 -5.69487318e-04 2.50182246e-03 -1.64892578e+00
2.89789600e+03  2.92579000e+03 -2.78940039e+01  1.41280259e-03 -1.15732048e-03  4.08837891e+00

Upvotes: 0

Views: 214

Answers (2)

joni
joni

Reputation: 7157

I don't really see the need to use a varying number of positional function arguments. Instead, simply pass the whole np.array processed by writing:

def bwp(x, processed):
    pred, real = x
    money = 1000
    for i in range(0, processed.shape[0]):
        if processed[i, 3] > pred and processed[i-1,4] > real:
            money = money + (money * processed[i, 4])
    return money * -1

def opt_2(processed):
    bounds = [(-1, 1), (-1, 1)]
    resbrute = optimize.brute(lambda x: bwp(x, processed), ranges=bounds, full_output=True, finish=optimize.fmin)
    print(resbrute[0])
    print(resbrute[1])

Note that I assume that processed is a np.array with shape (4, 6) as indicated in your question.

Upvotes: 1

Corralien
Corralien

Reputation: 120399

As processed is a tuple, you may have to explode into N variables as below:

def bwp(x, *processed):
    pred, real = x
    money = 1000
    v1, v2, v3, ... vN = processed
    ...

Your question lacks an example to be reproduced so don't hesitate to print(processed) to know what scipy.optimize.brute gives you as arguments.

Upvotes: 0

Related Questions