Rampy sri
Rampy sri

Reputation: 1

Sample 30day increments and create a new data frame from existing daily frame

I am storing daily data into a dataframe and wish to create a new data frame which has only data for last day of the month ( or last 30days or say 60days) and plot those periods returns for the given time frame in bar chart. I tried using resample function, however, it skips the last business day and returns NA for last day in some months.

Is there any way to calculate the 30-day rolling return from start to end with a stub period of end ( < 30 days) shown in the plot using a few lines of code?

s1 = yf.download("^GSPC", start="2005-02-01", end="2007-12-31")

s1.resample('M', convention='end').asfreq()

Upvotes: 0

Views: 96

Answers (1)

inquirer
inquirer

Reputation: 4823

You can try this: reset the indexes and group the dataframe by year and month, using aggregation.

import yfinance as yf
import pandas as pd

s1 = yf.download("^GSPC", start="2005-02-01", end="2007-12-31")

s1 = s1.reset_index()

df = (s1.groupby([s1['Date'].dt.year, s1['Date'].dt.month], as_index=False)
      .agg({'Date' : 'first', 'Open': 'first', 'High': 'max',
       'Low': 'min', 'Close': 'last', 'Volume': 'sum'})).set_index('Date')

print(df)

Upvotes: 0

Related Questions