Home > Enterprise >  Python 'list.insert()' only saves the last result of calculation loop
Python 'list.insert()' only saves the last result of calculation loop

Time:01-15

I was making my automatic stock strategy yield calculation program with Python. Here's my code:

import FinanceDataReader as fdr 
import numpy as np
# ...(more modules for python)

pd.options.display.float_format = '{:.5f}'.format

file_list = os.listdir('/home/sejahui/projects/stock_data_excel')

for i in range(20): 

os.chdir('/home/sejahui/projects/stock_data_excel')
odd = file_list[i]

data = pd.read_excel('/home/sejahui/projects/stock_data_excel/' str(odd))

def calMACD(data, short=5, long=25, signal=9):
    data.sort_index()
    
    data['MVA_25']=data['Close'].ewm(span=long, adjust=False).mean()
    data['MVA_5']=data['Close'].ewm(span=short, adjust=False).mean()
    data['MACD']=data['Close'].ewm(span=short, adjust=False).mean() - data['Close'].ewm(span=long, adjust=False).mean()
    data['Signal']=data['MACD'].ewm(span=signal, adjust=False).mean( )
    #data['Buy_sign']=(data['MACD']-data['Signal']) >=600
    data['Buy_sign']=np.where(data['MACD']-data['Signal'] >=451, 'Buy' , 'Sell' )
    #data['Target_1']=(data['Close']-data['Close'].shift(1))/data['Close'].shift(1)*100
    #data['Target_1']=np.where(data['Buy_sign']=='Buy', (data['Change']) 1,1)
    #data['Target_2']=np.where(data['Buy_sign']=='Sell', (data['Change']) 1,1)
    #data['Real_world']= 1000000*data['Target_1']
    #data['Real_world_2']= 1000000*data['Target_2'] 
    #data['Condition'] = np.where(data['Real_world']<1000000, data['Real_world']-data['Real_world'].shift(-2),1)
    ##data['Condition_2'] = np.where(data['Real_world']<1000000, data['Target_1'].shift(-2),1)
    #data['Moneyflow'] = 
    #plt.plot(data['Date'], data['Real_world'])
    #data[data.Buy_sign !='Sell']
    
    

    '''
    data['Target_1']=np.where(data['Buy_sign']=='Buy', data['Change'],1)
    data['Target_2']=np.where(data['Buy_sign']=='Sell', data ['Change'],1)
    data['Yield']=np.where(data['Buy_sign']=='Sell', data['Target_1']/data['Target_2'],1 )
    '''

    '''
    data['Result']=data['Target_1'].cumprod()
    data['Result_2']=data['Target_2'].cumprod()
    data['??????'] = data['Result'] - data['Result_2']
    '''

    return data


Adjusted = calMACD(data)
Adjusted.drop(['Change'], axis=1, inplace = True)
Filtered = Adjusted[Adjusted.Buy_sign!='Sell'].copy()

#print(Filtered)
#Filtered = (Adjusted.Buy_sign =='Buy') #(Adjusted.Condition = 1.0)
#Master = Adjusted.loc[Adjusted,['Date','Buy_sign','Target_1','Real_world',]]
#print(Adjusted)


def backtester(Filtered):
    Filtered['Change'] = ((Filtered['Close'] - Filtered['Close'].shift(1)) / Filtered['Close'].shift(1)) 1
    #data['Target_1']=np.where(data['Buy_sign']=='Buy', (data['Change']) 1,1)
    Filtered['Real_world'] = 1000000*Filtered['Change']
    #Filtered['Condition'] = np.where(Filtered['Real_world']<1000000, Filtered['Real_world'].shift(-2)-Filtered['Real_world'],1)
    Filtered['Condition'] = np.where(Filtered['Real_world']<1000000, Filtered['Change'].shift(-2),1)
    #Filtered['Target_1'] = np.where(Filtered['Buy_sign']=='Buy', (Filtered['Change']) 1,1)
    #Filtered['Condition'] = np.where(Filtered['Real_world']<1000000, Filtered['Real_world'].shift(-2)-Filtered['Real_world'],1)

    return Filtered 
    
s = backtester(Filtered)

e = s[s.Condition!=1.00000]

x = e.dropna()

y = x['Condition']

list_1 = []

write_wb = Workbook()
write_ws = write_wb.create_sheet('MACD&Signal gap data sheet')
write_ws = write_wb.active
write_ws['A1'] = 'Name'
write_ws['B1'] = 'Profit'





try:
    print(geometric_mean(y)*1000000*12)

except StatisticsError as e:
    print ('Sell is empty':',odd)
else:
    d = (geometric_mean(y)*1000000*12)
    print(d,odd)
    list_1.insert(i,d)

 Print(list_1)

Here's the part where I'm troubling with:

s = backtester(Filtered)

e = s[s.Condition!=1.00000]

x = e.dropna()

y = x['Condition']

list_1 = []


try:
    print(geometric_mean(y)*1000000*12)

except StatisticsError as e:
    print ('Sell is empty':',odd)

else:
    d = (geometric_mean(y)*1000000*12)
    print(d)
    list_1.insert(d)

print(list_1) 

When I initiate the code where I am having problems, list only saves the last result of 'try, except, else' function. My intention was saving all the results. What change should I give to save all the results?

Here's the output of the list:

 [11772769.197974786]

CodePudding user response:

Your problem is that you are using insert instead of append and the main difference that insert takes a second argument for the position that you want to insert your element at and when none is provided it is 0 by default so you are consistently inserting at the same index resulting in a list with only the last element at the first position.

To fix that simply use append instead.

else:
    d = (geometric_mean(y)*1000000*12)
    print(d)
    list_1.append(d)

CodePudding user response:

You want to use append, not insert. see Python Data Structures

Change list_1.insert(d) to list_1.append(d)

The insert is defaulting to index 0 and just updating it each time.

Edit: Just noticed your answer is in the question title.

  •  Tags:  
  • Related