Python Forum
Need help with creating dynamic columns with for loops for stock prices
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with creating dynamic columns with for loops for stock prices
#1
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

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
Reply
#2
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.0
To create a new data frame with only the new columns containing the moving averages,can use filter().
>>> 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
PaDat likes this post
Reply
#3
(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.0
To create a new data frame with only the new columns containing the moving averages,can use filter().
>>> 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..
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Nested for loops: Iterating over columns of a DataFrame to plot on subplots dm222 0 1,726 Aug-19-2022, 11:07 AM
Last Post: dm222
  SMA (simple moving avg) Not receiving Data (stock prices). gdbengo 2 1,468 Jul-31-2022, 08:20 PM
Last Post: paulyan
  Creating a loop with dynamic variables instead of hardcoded values FugaziRocks 3 1,505 Jul-27-2022, 08:50 PM
Last Post: rob101
  Trouble creating loops Den 3 2,325 Oct-23-2019, 05:59 PM
Last Post: ibreeden
  Creating Dynamic Objects MacFie 4 3,190 Jun-13-2019, 02:48 PM
Last Post: MacFie
  Different prices per hour kemper 1 2,034 Jan-29-2019, 11:06 AM
Last Post: Larz60+
  Bill calculator with different prices JHPythonLearner 10 5,061 Sep-15-2018, 12:14 AM
Last Post: volcano63
  Troubble creating loops in PyQt LavaCreeperKing 0 5,544 Mar-02-2017, 08:05 PM
Last Post: LavaCreeperKing
  Creating Dynamic Variable Names Dragonexpert 3 8,147 Oct-22-2016, 02:17 PM
Last Post: Dragonexpert

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020