Feb-21-2023, 07:27 PM
Dear All,
I have a bunch of stock prices (about 100) and I want to dynamically compute their moving average, daily returns etc and have them in 1) the same dataframe 2) a new dataframe for each analysis. The code I have written is given below. I am struggling to create dynamically the new column names and also to copy over the computed statistics in a new frame. Can anyone help me.
Thanks a lot.
Best Regards,
PDat
I have a bunch of stock prices (about 100) and I want to dynamically compute their moving average, daily returns etc and have them in 1) the same dataframe 2) a new dataframe for each analysis. The code I have written is given below. I am struggling to create dynamically the new column names and also to copy over the computed statistics in a new frame. Can anyone help me.
Thanks a lot.
Best Regards,
PDat
import pandas as pd
import matplotlib.pyplot as plt
# Large list of around 100 stock prices to be imported via for e.g. a csv file. small example shown below
Data={'Stock1':[1,2,3,4,5,6,7,8,9,10],'Stock2':[10,20,30,40,50,60,70,80,90,100],
'Stock3':[100,200,300,400,500,600,700,800,900,1000]}
Stock_Prices=pd.DataFrame(Data)
# Need to dynamically calculate the simple 3-day moving averages of the 100 stocks with new columns names as Stock1_MA,
# Stock2_MA etc and 1) add them to the right in the same data frame and 2) to create a new data frame with the new columns
# Manually this is done as below but needs to be done dynamically
#Stock_Prices['Stock1_3D MA']=Stock_Prices['Stock1'].rolling(3).mean()
#Stock_Prices['Stock2_3D MA']=Stock_Prices['Stock2'].rolling(3).mean()
#Stock_Prices['Stock3_3D MA']=Stock_Prices['Stock3'].rolling(3).mean()
MovingAverage = {}
for i in range (0,3):
MovingAverage[i] = Stock_Prices.rolling(3).mean()
MA=pd.DataFrame(MovingAverage)
# Code does not work and also column names remain static in MovingAverage
MovingAverage
