Normalizing stock market data with reactive DataFrame

Hello,

I am new to Panel and I am trying to normalize stock market data of an reactive DataFrame. I am getting an error and need a bit of help.

This is the minimal, reproducible example:

import pandas as pd
import panel as pn

# Create DateTimeIndex
dates = pd.date_range(start='2023-01-01', end='2023-01-10', freq='D')

# Price data
prices = [101.5, 98.2, 103.7, 100.4, 104.6, 97.8, 106.3, 99.5, 105.2, 108.0]

# Create DataFrame
df = pd.DataFrame(data={'Price': prices}, index=dates)

In a normal DataFrame I would do this to normalize the stock price:

# First Index
first_index = df.index[0]

# Normalize Price
df["Price_normalized"] = df["Price"] / df.loc[first_index, 'Price']

print(df)

However, in my case I am filtering the DataFrame with a DateRangeSlider. Because of this the first_index, on which i normalize, changes. It should always be the first price of the filtered DataFrame “rdf”. The basic pandas method does not work and I get an error.

rdf=pn.rx(df)

# First Index
first_index = rdf.index[0]

# Normalize Price
rdf["Price_normalized"] = rdf["Price"] / rdf.loc[first_index, 'Price']

I am getting the TypeError:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[33], line 7
      4 first_index = rdf.index[0]
      6 # Normalize Price
----> 7 rdf["Price_normalized"] = rdf["Price"] / rdf.loc[first_index, 'Price']

TypeError: 'rx' object does not support item assignment

Does somebody know, how to fix this? Thank you! :slight_smile:

1 Like

Not sure how to do item assignments with rx, but if you use pandas methods like query and assign, you could do it (not sure if it’s helpful since you need to rewrite existing code)

import pandas as pd
import panel as pn

# Create DateTimeIndex
dates = pd.date_range(start='2023-01-01', end='2023-01-10', freq='D')

# Price data
prices = [101.5, 98.2, 103.7, 100.4, 104.6, 97.8, 106.3, 99.5, 105.2, 108.0]

# Create DataFrame
df = pd.DataFrame(data={'Price': prices, 'Dates': dates})
rdf = pn.rx(df)
first_price = rdf.query('Dates == Dates.min()')["Price"].item()
rdf = rdf.assign(**{"Price_normalized": rdf["Price"] / first_price})
rdf.rx.value
1 Like

Thank you, that helped!

@ahuang11 , are we collecting limitations with .rx like this somewhere? Seems like this should be added to a list of things to either document or fix.

Not sure if it’s a limitation, or just inexperience, but created an issue

Adding link to code with possible solution to use assignment, by @ahuang11