# Optimize a non-linear function in Python

I am trying to optimize a function using scipy.optimize, but it does not converge. I have a trading strategy with a default stop-loss based on the lowest price over 20 days. I want to optimize this stop-loss with 2 variables (i.e. I want it to be higher or lower depending on these variables). The result of the objective function is the total return. What is the best way to do this?

>> df
close   stop_loss   variable_1   variable_2
0   111.79  114.080429  -1.124674   -0.573896
1   113.04  114.080429  -0.750894   -0.574460
2   113.07  114.080429  -0.653854   -0.572659
3   111.06  114.080429  -1.014128   -0.520336
4   109.65  112.613320  -1.258951   -0.424078

def objective(x, df):

long_ = df['close'] > (df['stop_loss'] * (df['variable_1'] * x[0] + 1) * (df['variable_2'] * x[1] + 1))
returns = ((df['close'].pct_change(1).shift(-1) * long_).dropna() + 1).cumprod()
return  -returns[-1]

res = minimize(objective, np.array([1, 1]), args=(df), method='nelder-mead', options={'tol': 1e-8, 'disp': True})

• Did you tried other optimization algorithms, for example genetic algorithm? Aug 8, 2022 at 13:41
• I am not familiar with genetic algorithms. Is there a particular one you would suggest? Aug 8, 2022 at 18:09
• Try the simplest one that you find for start. If you're using python try this one github.com/rmsolgi/geneticalgorithm Aug 9, 2022 at 14:29

## 1 Answer

Hi and welcome to the DS community. A couple of quick questions.

1. Any specific reasons using 'nelder-mead' method
2. You mind sharing the a sample dataset in order to better gauge the problem
• 1. No. I also tried BFGS and the result is the same. 2. I added it to the question. + The first line of code acts as an indicator function. This might not be appropriate to use with scipy.optimize. The issue is the result I am trying to optimize depends on variables that themselves are optimized. I think it can be solved with reinforcement learning, but perhaps not with traditional optimization. Aug 8, 2022 at 12:47