pythondataframeperiodyfinancetechnical-indicator

Problem about using talib to generate MACD dataframe using different period sets


import yfinance as yf
import pandas as pd
import talib

code = '2800'
para_dict = {
    'sample_period_list': [200],
    'fastperiod_list': [12, 16],
    'slowperiod_list': [26, 30],
    'signalperiod_list': [8, 12],
    'higher_percentile_list': [0.8],
    'profit_target': [0.04],
    'stop_loss': [-0.04]
}

start_date = '2020-01-01'
end_date = '2022-10-10'

df_dict = {}

df = yf.Ticker(code + '.HK').history(start=start_date, end=end_date)
df = df[df['Volume'] > 0]
df = df[['Open', 'High', 'Low', 'Close']]
# df['pnl_percentage'] = df['Open'].pct_change()

df = df.reset_index()

for fastperiod in para_dict['fastperiod_list']:
    for slowperiod in para_dict['slowperiod_list']:
        for signalperiod in para_dict['signalperiod_list']:
            macd_key = str(fastperiod) + '_' + str(slowperiod) + '_' + str(signalperiod)


            df['macd'], df['macdsignal'], df['macdhist'] = talib.MACD(df['Close'], fastperiod=fastperiod, slowperiod=slowperiod, signalperiod=signalperiod)

            df_dict[macd_key] = df

print(df_dict)


I cant get the right dataframe for different MACD periods, instead I generate the same dataframe using different MACD periods by below codes? WHY

I cant get the right dataframe for different MACD periods, instead I generate the same dataframe using different MACD periods by below codes? WHY


Solution

  • The reason is because you're pointing to the same dataframe , if you change one they all change so in your example they will be all equal to the last df.

    you can read more in it in those questions :

    Modifying one dataframe appears to change another

    Why can pandas DataFrames change each other?

    As a solution to your case , you need to use a copy of the dataframe not the actual dataframe :

    df_dict[macd_key] = df.copy()
    #instead of df_dict[macd_key] = df
    

    it will solve your issue