How to loop through variables w/ trend trading system

I built a simple moving average trading system like so:

import pandas as pd
import numpy as np

def trendfunc(f1,fastnum,slownum):
    f1['Change'] = f1['Close'].pct_change()
    f1['Fast'] = f1['Close'].rolling(window=fastnum,center=False).mean() 
    f1['Slow'] = f1['Close'].rolling(window=slownum,center=False).mean() 
    f1['Trend'] = f1['Fast'] - f1['Slow'] 
    f1['Position'] = np.where(f1['Trend'].shift(2)>0,1,0) 
    f1['Result'] = f1['Position']*f1['Change']
    f1 = f1.dropna()
    f1['MktVAMI'] = f1['Change']+1
    f1['MktVAMI'].iloc[0] = 1000
    f1['MktVAMI'] = f1['MktVAMI'].cumprod()
    f1['MktHi'] = f1['MktVAMI'].cummax()
    f1['MktDD'] = (f1['MktVAMI']/f1['MktHi'])-1
    f1['MktMaxDD'] = f1['MktDD'].cummin()
    f1['SysVAMI'] = f1['Result']+1
    f1['SysVAMI'].iloc[0] = 1000
    f1['SysVAMI'] = f1['SysVAMI'].cumprod()
    f1['SysHi'] = f1['SysVAMI'].cummax()
    f1['SysDD'] = (f1['SysVAMI']/f1['SysHi'])-1
    f1['SysMaxDD'] = f1['SysDD'].cummin()
    keep = ['Date','MktVAMI','MktMaxDD','SysVAMI','SysMaxDD']
    f2 = f1[keep].tail(1)
    return f2

tkrs = ['spy']

for tkr in tkrs:
    df1 = pd.read_csv(f'C:\\Path\\To\\Date\\{tkr}.csv')
    FastMA = 50
    SlowMA = 200
    AA = trendfunc(df1,FastMA,SlowMA)

In the code above, I use one "fast" moving average (FastMA = 50) and one "slow" moving average (SlowMA = 200). I’d like to be able to loop through several possible values for both FastMA and SlowMA.

So, I might want to use:

FastMA = [10,20,30]
FastMA = [100,200,300]

Where I end up with 9 possible combination each of which is fed to the "trendfunc" function.

I’d also like to append each result to a dataframe with the values used for the respective variables so I could then export that dataframe and compare results.

My loop skills aren’t very strong when it comes to multi level nesting and appending to a dataframe hence this post. Please help. Thx.

>Solution :

You can use nested loops to iterate through all the combinations and call your function for each combo. Then yo can store the results in the dataframe and append the values of FastMA and slowMA to it also.

import pandas as pd
import numpy as np

tkrs = ['spy']

results = pd.DataFrame(columns=['FastMA', 'SlowMA', 'MktVAMI', 'MktMaxDD', 'SysVAMI', 'SysMaxDD'])

fast_ma_list = [10, 20, 30]
slow_ma_list = [100, 200, 300]

for fast_ma in fast_ma_list:
    for slow_ma in slow_ma_list:
        for tkr in tkrs:
            df1 = pd.read_csv(f'C:\\Path\\To\\Date\\{tkr}.csv')
            AA = trendfunc(df1, fast_ma, slow_ma)
            AA['FastMA'] = fast_ma
            AA['SlowMA'] = slow_ma
            results = results.append(AA, ignore_index=True)

print(results) # Do whatever with results

The nested loops are used to iterate through all the possible combinations of FastMA and SlowMA. For each combination, the trendfunc() is called and the output is stored in the AA dataframe. The values of FastMA and SlowMA are then appended to the AA dataframe, and the AA df is then appended to the results df.

Hopefully this helps 🙂

Leave a Reply