Applying apply function on a pandas dataframe

Asked

Viewed 92 times

1

I have a code (CODIGO01) that calculates the moving averages (21 periods) of a particular (individual) stock exchange share (IBOV - B3). Then I created a loop for where it determines q an asset this in high trend after 6 high followed by moving averages (hypothesis, since there are more variables to determine this).

However, I want to make this loop for more than one asset, in case CODIGO02, ie it apply a function in each column of my code and return me only the name of the assets that are trending high (in this case, the name of the column). I tried to turn the loop for into a function and apply that function using pandas "apply" in each column (Axis=1, tried tbm Axis='Columns'). Only I am having error in function creation. When I run the function using apply aparace the message "Valueerror: Lengths must match to compare". How can I fix this?

Grateful for the attention.

import numpy as np
import pandas as pd
from pandas_datareader import data as wb
from mpl_finance import candlestick_ohlc
from pandas_datareader import data as wb
from datetime import datetime
import matplotlib.dates as mpl_dates
import matplotlib.pyplot as plt
import matplotlib.dates as mdates 

#Nome do Ativo
ativo = 'WEGE3.SA'
acao2 = ativo.upper()

#Data de Início e Fim da Análise
inicio = '2020-1-1'
fim = '2021-1-27'

#CRIANDO O DATAFRAME C MEDIAS MOVEIS DE 21/72 PERIODOS
df_bolsa = wb.DataReader(acao2, data_source='yahoo', start=inicio, end=fim)

df_bolsa.index.names = ['Data']
df= df_bolsa.copy(deep=True)
df['Data'] = df.index.map(mdates.date2num)

# Médias Moveis
df['ema21'] = df['Close'].ewm(span=21, adjust=False).mean()
df['ema72'] = df['Close'].ewm(span=72, adjust=False).mean()

#DF DE PLOTAGEM
df1=df
df2=df[-120:]

#REGRA TENDENCIA
alta=1
for i in range(6):
  if(df2.ema21[-i-1] < df2.ema21[-i-2]):
    alta=0

baixa=1
for i in range(6):
  if(df2.ema21[-i-1] > df2.ema21[-i-2]):
    baixa=0

if (alta==1 and baixa==0):
  a1 = ativo.upper()+ ' EM TENDÊNCIA DE ALTA'
elif (alta==0 and baixa==1):
  a1 = ativo.upper()+ ' EM TENDÊNCIA DE BAIXA!'
else:
  a1 = ativo.upper()+ ' EM LATERALIZAÇÃO'
  
#PLOTAGEM DOS RESULTADOS
print("---------------------------------------") 
print(a1)
print("---------------------------------------")

ohlc = df[['Data', 'Open', 'High', 'Low', 'Close']]

f1, ax = plt.subplots(figsize=(14, 8))

# plot the candlesticks
candlestick_ohlc(ax, ohlc.values, width=.6, colorup='green', colordown='red')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

label_ = acao2.upper() + ' EMA26'
label_2 = acao2.upper() + ' EMA09'
ax.plot(df.index, df1['ema21'], color='black', label=label_)
ax.plot(df.index, df1['ema72'], color='blue', label=label_)

ax.grid(False)
ax.legend()
ax.grid(True)

plt.title(acao2.upper() + ' : Gráfico Diário')
plt.show(block=True)

#CÓDIGO02

#PERÍODO DE AVALIAÇÃO
inicio = '2020-1-1'
fim = '2021-1-27'

#LISTA DOS ATIVOS
ativos = ['SAPR11.SA','WEGE3.SA']

#GERAÇÃO DO DATAFRAME
mydata = pd.DataFrame()
for t in ativos:
    mydata[t] = wb.DataReader(t, data_source='yahoo', start=inicio, end=fim)['Close']
df2 = mydata

#CÁLCULO MÉDIAS MÓVEIS
df3 = df2.apply(lambda x: x.rolling(window=21).mean())

#GERANDO A FUNÇÃO
def trend(x):
  tendencia_alta=1
  for i in range(6):
    if(df3.columns[-i-1:] > df3.columns[-i-2:]):
      tendencia_alta=0

  print()
  if(tendencia_alta==1):
    print('TENDÊNCIA DE ALTA')
  else:
    print('TENDÊNCIA DE BAIXA')

#TENTANDO APLICAR A FUNÇÃO EM CADA COLUNA DO DF3
df3.apply(trend, axis=1)´´´


  • Within the function trend you should use the x which is being received by parameter and not df3 in addition, the function should return something...

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.