Data:
{'Open': {0: 159.18000000000001, 1: 157.99000000000001, 2: 157.66, 3: 157.53999999999999, 4: 155.03999999999999, 5: 155.47999999999999, 6: 155.44999999999999, 7: 155.93000000000001, 8: 155.0, 9: 157.72999999999999},
'Close': {0: 157.97999999999999, 1: 157.66, 2: 157.53999999999999, 3: 155.03999999999999, 4: 155.47999999999999, 5: 155.44999999999999, 6: 155.87, 7: 155.0, 8: 157.72999999999999, 9: 157.31}}
Code:
import pandas as pd
d = #... data above.
df = pd.DataFrame.from_dict(d)
df['Close_Stdev'] = pd.rolling_std(df[['Close']],window=5)
print df
# Close Open Close_Stdev
# 0 157.98 159.18 NaN
# 1 157.66 157.99 NaN
# 2 157.54 157.66 NaN
# 3 155.04 157.54 NaN
# 4 155.48 155.04 1.369452
# 5 155.45 155.48 1.259754
# 6 155.87 155.45 0.975464
# 7 155.00 155.93 0.358567
# 8 157.73 155.00 1.065190
# 9 157.31 157.73 1.189378
Problem:
The above code has no problems. However, is it possible for rolling_std
to be able to factor in its window of observation the first four values in Close
and the fifth value in Open
? Basically, I want rolling_std
to calculate the following for its first Stdev:
157.98 # From Close
157.66 # From Close
157.54 # From Close
155.04 # From Close
155.04 # Bzzt, from Open.
Technically, this means that the last value of the observed list is always the last Close
value.
Logic/Reason:
Obviously, this is stock data. I'm trying to check if it's better to factor in the Open
price of a stock for the current trading day in the calculation of standard deviation rather than stop at just checking the previous Close
s.
Desired Result:
# Close Open Close_Stdev Desired_Stdev
# 0 157.98 159.18 NaN NaN
# 1 157.66 157.99 NaN NaN
# 2 157.54 157.66 NaN NaN
# 3 155.04 157.54 NaN NaN
# 4 155.48 155.04 1.369452 1.480311
# 5 155.45 155.48 1.259754 1.255149
# 6 155.87 155.45 0.975464 0.994017
# 7 155.00 155.93 0.358567 0.361151
# 8 157.73 155.00 1.065190 0.368035
# 9 157.31 157.73 1.189378 1.291464
Extra Details:
This can easily be done in Excel by using the formula STDEV.S
and selecting the numbers as seen in the screenshot below. However, I want this done in Python and pandas
for personal reasons (I'm highlighting F6
, it's not just visible due to Snagit's effect).