Created
January 4, 2016 20:27
-
-
Save prithwi/339f87bf9c3c37bb3188 to your computer and use it in GitHub Desktop.
daily stock to weekly stock values
Now (pandas 1.0.5) we don't even need to define the take_first and take_last functions. 'first'
and 'last'
would work fine.
output = df.resample('W') # Weekly resample
.agg({'Open': 'first',
'High': 'max',
'Low': 'min',
'Close': 'last',
'Volume': 'sum'})
output.index = output.index + pd.DateOffset(days=-6) # to put the labels to Monday
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks all of you:
the final code that worked for me after reading all of those comments and some other:
`import pandas as pd
import pandas_datareader as web
import datetime
ticker = "MMM"
start = datetime.datetime(2018, 2, 5)
end = datetime.datetime(2018, 2, 25)
f = web.DataReader(ticker, 'yahoo', start, end)
f.index = pd.to_datetime(f.index)
def take_first(array_like):
return array_like[0]
def take_last(array_like):
return array_like[-1]
output = f.resample('W').agg({'Open': take_first,
'High': 'max',
'Low': 'min',
'Close': take_last,
'Adj Close': take_last,
'Volume': 'sum'}) # to put the labels to Monday
output = output[['Open', 'High', 'Low', 'Close','Adj Close', 'Volume']]
output.index = output.index + pd.DateOffset(days=-6)
print (output)`