converting daily stock data to weekly-based via pandas in Python

后端 未结 4 887
栀梦
栀梦 2020-12-23 10:48

I\'ve got a DataFrame storing daily-based data which is as below:

Date              Open        High         Low       Close   Volume
2010-01-04         


        
4条回答
  •  星月不相逢
    2020-12-23 11:16

    I had the exact same question and found a great solution here.

    https://www.techtrekking.com/how-to-convert-daily-time-series-data-into-weekly-and-monthly-using-pandas-and-python/

    The weekly code is posted below.

    import pandas as pd
    import numpy as np
    
    print('*** Program Started ***')
    
    df = pd.read_csv('15-06-2016-TO-14-06-2018HDFCBANKALLN.csv')
    
    # ensuring only equity series is considered
    df = df.loc[df['Series'] == 'EQ']
    
    # Converting date to pandas datetime format
    df['Date'] = pd.to_datetime(df['Date'])
    # Getting week number
    df['Week_Number'] = df['Date'].dt.week
    # Getting year. Weeknum is common across years to we need to create unique index by using year and weeknum
    df['Year'] = df['Date'].dt.year
    
    # Grouping based on required values
    df2 = df.groupby(['Year','Week_Number']).agg({'Open Price':'first', 'High Price':'max', 'Low Price':'min', 'Close Price':'last','Total Traded Quantity':'sum'})
    # df3 = df.groupby(['Year','Week_Number']).agg({'Open Price':'first', 'High Price':'max', 'Low Price':'min', 'Close Price':'last','Total Traded Quantity':'sum','Average Price':'avg'})
    df2.to_csv('Weekly_OHLC.csv')
    print('*** Program ended ***')
    

提交回复
热议问题