Skip to content Skip to sidebar Skip to footer

Daily To Weekly Data Conversion Extra Line In Output

I'm looking to convert daily data into weekly data. Input data OUTPUT DATA AT PRESENT AFTER CONVERTING TO WEEKLY candle_date open high low close

Solution 1:

   def convert_dailydata_to_weeklydata(daily_data):
        # Print function name
        SupportMethods.print_func_name()

        # Loop over the rows until a row with Monday as date is present
        row_counter_start = 0
        while True:
            if datetime.weekday(daily_data['candle_date'][row_counter_start]) == 0:
                break
            row_counter_start += 1

        # # Loop over the rows until a row with Sunday as date is present
        # row_counter_end = len(daily_data.index) - 1
        # while True:
        #     if datetime.weekday(daily_data['candle_date'][row_counter_end]) == 6:
        #         break
        #     row_counter_end -= 1
        # print(daily_data)
        # print(row_counter_end)

        # Copy all rows after the first Monday row of data is reached
        daily_data_temp = daily_data[row_counter_start:]

        # Getting week number
        daily_data_temp['Week_Number'] = pd.to_datetime(daily_data_temp['candle_date']).dt.week

        # Getting year. Weeknum is common across years to we need to create unique index by using year and weeknum
        daily_data_temp['Year'] = pd.to_datetime(daily_data_temp['candle_date']).dt.year

        # Grouping based on required values
        df = daily_data_temp.groupby(['Year', 'Week_Number']).agg(
            {'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum', 'market_cap': 'sum'})

        # Reset index
        df = df.reset_index()

        # Create week date (start of week)
        # The + "1" isfor the day of the week.Week numbers 0-6 with 0 being Sunday and 6 being Saturday.
        df['week_date'] = pd.to_datetime(df['Year'].astype(str) + df['Week_Number'].astype(str) + "1", format='%G%V%w')

        # Set indexes
        df = df.set_index(['Year', 'Week_Number'])

        # Re-order columns into a new dataframe
        weekly_data = df[["week_date", "open", "high", "low", "close", "volume", "market_cap"]]
        weekly_data = weekly_data.rename({'week_date': 'candle_date'}, axis=1)

        # Drop index columns
        weekly_data.reset_index(drop=True, inplace=True)

        # Return data by dropping curent week's data
        if datetime.weekday(weekly_data.head(-1)['candle_date']) != 0:
            return weekly_data.head(-1)
        else:
            return weekly_data

Post a Comment for "Daily To Weekly Data Conversion Extra Line In Output"