I am trying to import several tickers dataframes to PowerBi but i cannot find a way to create variables with the name of the ticker.
Here is my code:
import time
import pandas as pd
from datetime import date
tickers = ['ATVI', 'AMD', 'ABNB','AIR','GOOGL','AMZN','AAPL','ERT.BE','EQIX','INTC','JPM','LPL','MC.PA','MSFT','NVDA','PKX','SSUN.BE','SFT.BE','SONY','SPOT','TSM','TSLA','HO.PA','UBI.PA','UBS','DIS']
dataset = {}
today = int(time.mktime((date.today()).timetuple()))
for ticker in tickers:
df = pd.read_csv(f'https://query1.finance.yahoo.com/v7/finance/download/{ticker}?period1=1670371200&period2={today}&interval=1d&events=history&includeAdjustedClose=true')
df['ticker'] = ticker
df['evolution'] = df['Close'] - df['Close'].shift(1)
df['percentage'] = ((df['Close'] - df['Close'].shift(1))/df['Close'])*100
dataset[ticker] = pd.DataFrame(df)
ticker = dataset[ticker]
Ideally when importing this to PowerBi i would have one separate dataframe from each list value, ex: ATVI, DIS, NVDA…
Thanks in advance for your help
>Solution :
May be creating separate dataframes for each ticker symbol and then import them into Power BI.
one way by modifying your code to create a dictionary of dataframes, where each key is the ticker symbol, and the value is the corresponding dataframe :
import time
import pandas as pd
from datetime import date
tickers = ['ATVI', 'AMD', 'ABNB','AIR','GOOGL','AMZN','AAPL','ERT.BE','EQIX','INTC','JPM','LPL','MC.PA','MSFT','NVDA','PKX','SSUN.BE','SFT.BE','SONY','SPOT','TSM','TSLA','HO.PA','UBI.PA','UBS','DIS']
dataset = {}
today = int(time.mktime((date.today()).timetuple()))
for ticker in tickers:
df = pd.read_csv(f'https://query1.finance.yahoo.com/v7/finance/download/{ticker}?period1=1670371200&period2={today}&interval=1d&events=history&includeAdjustedClose=true')
df['ticker'] = ticker
df['evolution'] = df['Close'] - df['Close'].shift(1)
df['percentage'] = ((df['Close'] - df['Close'].shift(1))/df['Close'])*100
dataset[ticker] = df
# 'dataset' is a dictionary where each key is a ticker symbol and the value is the corresponding dataframe.
# export these dataframes to separate CSV files or use them directly in Power BI.
# Ex: Exporting each dataframe to a CSV file
for ticker, df in dataset.items():
df.to_csv(f'{ticker}_data.csv', index=False)
store each dataframe in the dataset dictionary with the ticker symbol as the key. You can then export each dataframe to a separate CSV file or use them directly.
When importing data into Power BI, you can import these CSV files individually too.