Feb-22-2023, 04:34 AM
(Feb-21-2023, 08:16 PM)snippsat Wrote: Can try this.
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) for col in Stock_Prices.columns: Stock_Prices[f"{col}_3D MA"] = Stock_Prices[col].rolling(3).mean()>>> Stock_Prices Stock1 Stock2 Stock3 Stock1_3D MA Stock2_3D MA Stock3_3D MA 0 1 10 100 NaN NaN NaN 1 2 20 200 NaN NaN NaN 2 3 30 300 2.0 20.0 200.0 3 4 40 400 3.0 30.0 300.0 4 5 50 500 4.0 40.0 400.0 5 6 60 600 5.0 50.0 500.0 6 7 70 700 6.0 60.0 600.0 7 8 80 800 7.0 70.0 700.0 8 9 90 900 8.0 80.0 800.0 9 10 100 1000 9.0 90.0 900.0To create a new data frame with only the new columns containing the moving averages,can usefilter()
.
>>> ma = Stock_Prices.filter(regex='_3D MA$') >>> ma Stock1_3D MA Stock2_3D MA Stock3_3D MA 0 NaN NaN NaN 1 NaN NaN NaN 2 2.0 20.0 200.0 3 3.0 30.0 300.0 4 4.0 40.0 400.0 5 5.0 50.0 500.0 6 6.0 60.0 600.0 7 7.0 70.0 700.0 8 8.0 80.0 800.0 9 9.0 90.0 900.0
Thanks a lot snippsat.. This is really helpful!
Best Regards..