简体   繁体   中英

Resampling daily ohlcv data to weekly and monthly

I have resampled daily ohlcv data to weekly and monthly to get the % return of the week and month.

now i realized when i resample it back to the daily i have no values in beetwen the monthly days what of course makes sense. But i´m not sure how i can transfer this data back while keeping the weekly and monthly %. What do you guys think what the best method would be since i want to apply this to the top 50 currencies per market cap.

Sorry i´ma python/panda noob :D

import pandas as pd
import datetime
import pandas_datareader.data as web
import numpy as np
df = pd.read_csv("ethusdt.csv",parse_dates=["time"], index_col="time")

ohlc_dict = {
    'open':'first',
    'high':'max',
    'low':'min',
    'close':'last',
    'volume':'sum',
    'daily_change':'sum'
    }

df = df.resample('W').agg(ohlc_dict)

df['weekly_change'] = ((df['close'] / (df['open'])-1)*100)

ohlc_dict = {
    'open':'first',
    'high':'max',
    'low':'min',
    'close':'last',
    'volume':'sum',
    'daily_change':'sum',
    'weekly_change':'sum'
    
    }

df = df.resample('M').agg(ohlc_dict)

df['monthly_change'] = ((df['close'] / (df['open'])-1)*100)

ohlc_dict = {
    'open':'first',
    'high':'max',
    'low':'min',
    'close':'last',
    'volume':'sum',
    'daily_change':'sum',
    'weekly_change':'sum'
    
    }

df = df.resample('D').agg(ohlc_dict)

When you resample a DataFrame called df, into a DataFrame also called df like below, you overwrite your daily data with aggregated data and you cannot get it back.

ohlc_dict = {
    'open':'first',
    'high':'max',
    'low':'min',
    'close':'last',
    'volume':'sum',
    'daily_change':'sum'
    }
df = df.resample('W').agg(ohlc_dict)

If you instead make the aggregated data a new DataFrame with a different name, you keep the old data around in the DataFrame called df and do your processing in the new DataFrame. Like this:

weeklydf = df.resample('W').agg(ohlc_dict)
weeklydf['weekly_change'] = ((weeklydf['close'] / (weeklydf['open'])-1)*100)


Now if you want to add this new "weekly_change" column to the daily DataFrame you can simply do:

df["weekly_change"] = weeklydf["weekly_change"]

Ofcourse, the "weekly_change" column will only have values every week, with NaN in between, but all the other columns will still be in daily resolution with all data present. You can do a similar procedure to get the monthly data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM