Optimization - Sequence multiple combination of parameters
-
With reference to this old thread:
https://community.backtrader.com/topic/2227/optimization-sequence-multiple-combination-of-parameters
This is exactly the question I have but my lack of coding experience is stopping me understand the response.
"You can create your own iterators for param1 and param2 and let them cooperate. When iterator_param1 returns 2 (for example), iterator_param2 can only return 9."
If i have
tuple1 = (0.2, 0.3, 0.4) tuple2 = (0.3, 0.4, 0.5)
How can I code what is spoken about above to get them to cooperate?
To clarify, on running the parameters should not be every combination but 0.2 and 0.3 together and 0.3 and 0.4 together etc.
I tried
param1=iter(tuple1), param2 = iter(tuple2)
But every combination was looped so I guess I am way off track.
Can anyone advise?
Many thanks
-
In order to do this, we need to pass in the pairs as one variable. So we need a tuple like:
((0.2, 0.3), (0.3, 0.4), (0.4, 0.5))
To create such a tuple, let's use zip to combine your two tuples:
tuple1 = (0.2, 0.3, 0.4) tuple2 = (0.3, 0.4, 0.5) tuple(zip(tuple1, tuple2)) output: ((0.2, 0.3), (0.3, 0.4), (0.4, 0.5))
We can then add this in to the optstrategy as follows:
tuple1 = (0.2, 0.3, 0.4) tuple2 = (0.3, 0.4, 0.5) combo_vars = tuple(zip(tuple1, tuple2)) cerebro.optstrategy(OptParams, combo_vars=combo_vars)
Then to receive this data in the strategy, we can have only one variable, not two, since it is receiving a tuple of two numbers.
params = (("combo_vars", 0),)
Make sure to include the trailing comma.
Finally you will need to pull the values out of the tuple and assign them to variables.
def __init__(self): vars = self.p.combo_vars self.var1 = vars[0] self.var2 = vars[1]
Here is the whole code.
import backtrader as bt class OptParams(bt.Strategy): params = (("combo_vars", 0),) def __init__(self): vars = self.p.combo_vars self.var1 = vars[0] self.var2 = vars[1] print(f"Var1: {self.var1}, Var2: {self.var2}") if __name__ == "__main__": # Create a Data Feed data = bt.feeds.GenericCSVData( dataname="data/2006-day-001.txt", dtformat=("%Y-%m-%d"), timeframe=bt.TimeFrame.Days, compression=1, ) cerebro = bt.Cerebro() cerebro.adddata(data) tuple1 = (0.2, 0.3, 0.4) tuple2 = (0.3, 0.4, 0.5) combo_vars = tuple(zip(tuple1, tuple2)) cerebro.optstrategy(OptParams, combo_vars=combo_vars) cerebro.run()
And if you run this, you will get a print out of:
Var1: 0.2, Var2: 0.3 Var1: 0.3, Var2: 0.4 Var1: 0.4, Var2: 0.5
-
@run-out Thank you for not only taking the time to help out but also really grateful for the explanation of each step. This is massively helpful for me.
Thank you again.
-