Iterrate And Save Each Stock Historical Data In Dataframe Without Downloading In Csv
I would like to pull historical data from yfinance for a specific list of stocks. I want to store earch stock in a separate dataframes (each stock with its own df). I can download
Solution 1:
You don't need to download data multiple times. You just have to split whole data with groupby
and create variables dynamically with locals()
:
stocks = ['TSLA', 'MSFT', 'NIO', 'AAPL', 'AMD', 'ADBE', 'ALGN', 'AMZN',
'AMGN', 'AEP', 'ADI', 'ANSS', 'AMAT', 'ASML', 'TEAM', 'ADSK']
data = yfinance.download(stocks, start='2015-01-01', end='2021-09-12')
for stock, df indata.groupby(level=1, axis=1):
locals()[stock] = df.droplevel(level=1, axis=1)
df.to_csv(f'{stock}.csv')
Output:
>>>TSLAAdjCloseCloseHighLowOpenVolumeDate2014-12-31 44.48199844.48199845.13600244.45000144.618000114875002015-01-02 43.86200043.86200044.65000242.65200044.574001238220002015-01-05 42.01800242.01800243.29999941.43199942.910000268425002015-01-06 42.25600142.25600142.84000040.84199942.012001313095002015-01-07 42.18999942.18999942.95600141.95600142.66999814842000.....................2021-09-03 733.570007733.570007734.000000724.200012732.250000152461002021-09-07 752.919983752.919983760.200012739.260010740.000000200398002021-09-08 753.869995753.869995764.450012740.770020761.580017187930002021-09-09 754.859985754.859985762.099976751.630005753.409973140777002021-09-10 736.270020736.270020762.609985734.520020759.59997615114300
[1686 rowsx6columns]
>>>ANSSAdjCloseCloseHighLowOpenVolumeDate2014-12-31 82.00000082.00000083.48000381.91000483.0800023046002015-01-02 81.63999981.63999982.62999781.01999782.0899962826002015-01-05 80.86000180.86000182.07000080.77999981.2900013215002015-01-06 79.26000279.26000281.13999978.76000281.0000003443002015-01-07 79.70999979.70999980.90000278.95999979.919998233300.....................2021-09-03 368.380005368.380005371.570007366.079987366.0799872930002021-09-07 372.070007372.070007372.410004364.950012369.6099852495002021-09-08 372.529999372.529999375.820007369.880005371.0799873258002021-09-09 371.970001371.970001375.799988371.320007372.5199891949002021-09-10 373.609985373.609985377.260010372.470001374.540009278800
[1686 rowsx6columns]
Solution 2:
You can create global or local variable like
globals()["TSLA"] = "some value"print(TSLA)
locals()["TSLA"] = "some value"print(TSLA)
but frankly it is waste of time. It is much more useful to keep it as dictionary.
With dictionary you can use for
-loop to run some code on all dataframes.
You can also seletect dataframes by name. etc.
Examples:
df_max = {}
for name, dfin df_.items():
df_max[name] = df.max()
name = input("What to display: ")
df_[name].plot()
Post a Comment for "Iterrate And Save Each Stock Historical Data In Dataframe Without Downloading In Csv"