코드의 중복 줄이기

랜디 Randy·2024년 1월 5일
0

현재 코드

        # KOSPI and KOSDAQ's weekly price change rate
        # KOSPI
        weekly_kospi_full = stock.get_index_price_change(monday, friday, KOSPI)
        kospi_result = ((weekly_kospi_full.iloc[0,1] / weekly_kospi_full.iloc[0,0]) - 1) * 100
        total_weekly.at[idx, 'KOSPI'] = kospi_result

        # KOSDAQ
        weekly_kosdaq_full = stock.get_index_price_change(monday, friday, KOSDAQ)
        kosdaq_result = ((weekly_kosdaq_full.iloc[0,1] / weekly_kosdaq_full.iloc[0,0]) - 1) * 100
        total_weekly.at[idx, 'KOSDAQ'] = kosdaq_result

코스피와 코스닥을 구하는 로직이 똑같아서 중복이 발생하고 있습니다.

중복 줄이기

하나의 함수로 만들어버렸습니다.

# KOSPI and KOSDAQ's weekly price change rate
        def korea_weekly_price_change_rate(monday, friday, korea_index, idx):
          weekly_index_full = stock.get_index_price_change(monday, friday, korea_index)
          index_result = ((weekly_index_full.iloc[0,1] / weekly_index_full.iloc[0,0]) - 1) * 100
          total_weekly.at[idx, korea_index] = index_result
          return True

        korea_weekly_price_change_rate(monday, friday, KOSPI, idx)
        korea_weekly_price_change_rate(monday, friday, KOSDAQ, idx)

👍🏻👍🏻👍🏻

profile
데이터는 계단, 직관은 다리

0개의 댓글