0

For the following code the output returned is such:

enter image description here

The desired arrangement is however with the tickers raised and grouped/aggregated like:

enter image description here

All suggestions and feedback welcome.

Code sample

def prepare_data(symbol, look_back_period):
    start_date = date.today() - timedelta(days=look_back_period)
    end_date = date.today()

    prices_df = get_symbol_prices(symbol=symbol, start_date=start_date, end_date=end_date)
    prices_df = prices_df[['close']]

    df = pd.DataFrame(prices_df)
    df.index.name = 'datetime'
    df['symbol'] = symbol
    return df


def get_final_df(tickers, look_back_period):
    df = pd.DataFrame()

    for symbol in symbol_list:
        df = df.append(prepare_data(symbol=symbol, look_back_period=look_back_period))
    return df


def main():

    historical_df = get_final_df(tickers=TICKERS, look_back_period=LOOK_BACK_PERIOD)
    output_folder = 'E:/'
    file_name = 'HISTORICALPORTFOLIO.csv'
    historical_df.to_csv(os.path.join(output_folder, file_name))

1 Answers1

0

Here is the pivoted df:

df = pd.DataFrame({
    'datetime': ['2022-06-08', '2022-06-09', '2022-06-10', '2022-06-08', '2022-06-09', '2022-06-10', '2022-06-08', '2022-06-09', '2022-06-10', '2022-06-08', '2022-06-09', '2022-06-10', '2022-06-08', '2022-06-09', '2022-06-10'], 
    'value': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 
    'name': ['AAPL', 'AAPL', 'AAPL', 'ABNB', 'ABNB', 'ABNB', 'ADBE', 'ADBE', 'ADBE', 'AMD', 'AMD', 'AMD', 'AMZN', 'AMZN', 'AMZN']})

#if 'datetime' is your index, just add this before pivoting:
df = df.reset_index()

res = df.pivot(index='datetime', columns='name', values='value').reset_index().rename_axis(columns=None)

print(res)

     datetime  AAPL  ABNB  ADBE  AMD  AMZN
0  2022-06-08     0     3     6    9    12
1  2022-06-09     1     4     7   10    13
2  2022-06-10     2     5     8   11    14
Rabinzel
  • 7,757
  • 3
  • 10
  • 30