I want to create a constant volume chart in python. Here is an example with a constant volume of 50 and some sample data: import pandas as pd import numpy as np date_rng = pd.date_range(start='2024-01-01', end='2024-12-31 23:00:00', freq='h') # Create a dataframe with the date range df = pd.DataFrame(date_rng, columns=['timestamp']) # Add the 'price' column with random floating numbers between 70 and 100 df['price'] = np.round(np.random.uniform(70, 100, size=(len(date_rng))), 2) # Add the 'volume' column with random integers between 1 and 10 df['volume'] = np.random.randint(1, 11, size=(len(date_rng))) constantvolume = 50 df['cumsum'] = np.cumsum(df['volume']) df['mod'] = df['cumsum']/ constantvolume df['whole'] = np.ceil(df['mod']) df['next_num'] = df['whole'].shift(-1) - df['whole'] df['mod2'] = df[df['next_num'] > 0]['cumsum'] % constantvolume df['mod2'] = df['mod2'].fillna(0) dfa = df.groupby(df['whole']).agg({'price': ['min', 'max', 'last', 'first'], 'timestamp': 'first', 'volume': 'sum'}) dfa.columns = ['low', 'high', 'close', 'open', 'timestamp', 'volume'] dfa['timestamp'] = pd.to_datetime(dfa['timestamp']) dfa.set_index('timestamp', inplace=True) dfa Now this is very close to what I want to do. The only issue is that the volume in each row is not exactly the defined quantity of 50 because the cumsum doesnt always add to 50. So what I would have to do is where next_num >0, see if there is the volume = to the defined constant volume, if yes good if no then split the next row with the same timestamp and same price but split the volume in two parts so that the mod is zero and then move on. The desired result is that in the final dataframe the volume = constantvolume in all rows exactly, with the exception of the last row where it could be different. The only way I can think of is a loop which I dont think is the best way and will be very slow as the actual dataframe as 1mn rows... Continue reading...