Search code examples
pythonfinance

Create multiple dataframes with a loop in Python


So I got this part of code that I want to make shorter:

df_1 = investpy.stocks.get_stock_recent_data('Eco','Colombia',False)
df_2 = investpy.stocks.get_stock_recent_data('JPM','United States',False)
df_3 = investpy.stocks.get_stock_recent_data('TSM','United States',False)
df_5 = investpy.stocks.get_stock_recent_data('CSCO','United States',False)
df_8 = investpy.stocks.get_stock_recent_data('NVDA','United States',False)
df_9 = investpy.stocks.get_stock_recent_data('BLK','United States',False)

As I use the same code and only a few things change from one line to another I think I migth solve this using a function. I create this one:

def _get_asset_data(ticker, country, state):
    investpy.stocks.get_stock_recent_data(ticker, country, state)

So I tried this:

_get_asset_data('TSLA', 'United States', False) print(_get_asset_data)

<function _get_asset_data at 0x7f323c912560>

However, I do not know how to make each set of data that I receive as a result of this function to be stored in a data frame for each company.I tried a for loop but got nowhere.

Any ideas? ¡Thank you in advance for your attention and cooperation!


Solution

  • Here is one approach based on the code given. You should refrain from using it in practice, as it contains redundant code, which makes it hard to maintain. You'll find a more flexible approach below.

    Based on your solution

    import investpy
    import pandas as pd
    
    def _get_asset_data(ticker, country, state=False):
        return investpy.stocks.get_stock_recent_data(ticker, country, state)
    
    df_1 = _get_asset_data('Eco','Colombia')
    df_2 = _get_asset_data('JPM','United States')
    df_3 = _get_asset_data('TSM','United States')
    df_5 = _get_asset_data('CSCO','United States')
    df_8 = _get_asset_data('NVDA','United States')
    df_9 = _get_asset_data('BLK','United States')
    
    final = pd.concat([df_1, df_2, df_3, df_5, df_8, df_9], axis=1)
    final
    

    More versatile solution:

    import investpy
    import pandas as pd
    
    
    def _get_asset_data(ticker, country, state=False):
        return investpy.stocks.get_stock_recent_data(ticker, country, state)
    
    
    stocks = [
        ('Eco', 'Colombia'),
        ('JPM', 'United States'),
        ('TSM', 'United States'),
        ('CSCO', 'United States'),
        ('NVDA', 'United States'),
        ('BLK', 'United States'),
        ]
    
    results = []
    
    for stock in stocks:
        result = _get_asset_data(*stock)
        results.append(result)
    
    final = pd.concat(results, axis=1)
    final