Debug and improve adjustforsplits() in the following code(): [code] Why does it…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Debug and improve adjust_for_splits() in the following code():
def ensure_series_types(df, price_col):
df['date'] = pd.to_datetime(df['date'])
df = df.sort_values('date').reset_index(drop=True)
for col in ['volume', price_col]:
df[col] = pd.to_numeric(df[col], errors='coerce')
return df
def validate_raw_prices(df, price_col):
invalid_price_mask = df[price_col] <= 0
inconsistent_mask = pd.Series(False, index=df.index)
if 'low' in df.columns and 'high' in df.columns:
inconsistent_mask = (df['low'] > df['high'])
local_error_mask = invalid_price_mask | inconsistent_mask
df = df[~local_error_mask].copy()
return df
def handle_stale_periods(df, price_col, max_stale_days=5):
stale_groups = (df[price_col].diff() != 0).cumsum()
period_lengths = df.groupby(stale_groups)[price_col].transform('size')
long_stale_mask = period_lengths > max_stale_days
is_intermediate_stale_row = (stale_groups.duplicated(keep='first') &
stale_groups.duplicated(keep='last'))
rows_to_drop_mask = long_stale_mask & is_intermediate_stale_row
df = df[~rows_to_drop_mask].copy()
return df
def adjust_for_splits(df, price_col, tolerance=0.05):
split_ratios = {
# Splits
-0.50: 2,
-0.666: 3,
-0.75: 4,
# Reverse Splits
1.0: 0.5,
2.0: 1/3,
3.0: 1/4,
}
df['pct_change'] = df[price_col].pct_change()
for pct, ratio in split_ratios.items():
# Detect pct_changes that resemble splits
is_potential_split = np.isclose(df['pct_change'], pct, atol=tolerance)
if is_potential_split.any():
print('split')
split_indices = df.index[is_potential_split]
for idx in split_indices:
if idx == 0: continue
# Check the next few days to ensure the price doesn't revert
price_before = df.loc[idx - 1, price_col]
price_at = df.loc[idx, price_col]
if idx + 3 < len(df):
price_after = df.loc[idx + 1:idx + 3, price_col].median()
if not np.isclose(price_after, price_at, rtol=0.1):
continue
# Adjust all prices before this date
df.loc[:idx-1, price_col] = df.loc[:idx-1, price_col] / ratio
df['pct_change'] = df[price_col].pct_change()
return df
# Load historical series
latest = (datetime.now() - timedelta(days=365 * 6))
meta = []
file_list = os.listdir(data_path)
for file in tqdm(file_list, total=len(file_list)):
if not file.endswith('.csv'):
continue
parts = os.path.splitext(file)[0].split('-')
symbol, exchange, currency = parts[0], parts[1], parts[2]
if not ((verified_df['symbol'] == symbol) & (verified_df['currency'] == currency)).any():
continue
# Load and clean raw series
# try:
df = load(data_path + file)
df = ensure_series_types(df, price_col)
df = validate_raw_prices(df, price_col)
df = handle_stale_periods(df, price_col)
df = adjust_for_splits(df, price_col)
if df['date'].max() > latest:
latest = df['date'].max()
meta.append({
'symbol': symbol,
'currency': currency,
'exchange_api': exchange,
'df': df[['date', price_col, 'volume', 'pct_change']],
})
# except Exception as e:
# print(f"ERROR {file}: {e}")
meta = pd.DataFrame(meta)
copied = meta.copy()
copied['df'] = copied['df'].apply(lambda x: x.copy())
Why does it calculate price_before? And what is it doing exactly?
adjust_for_splits function is designed to adjust stock prices for splits and reverse splits.price_before variable is calculated as the stock price before the potential split date (idx - 1).price_before is not used anywhere in the function. It seems to be a leftover from a previous implementation.def adjust_for_splits(df, price_col, tolerance=0.05):
"""
Adjust stock prices for splits and reverse splits.
Parameters:
df (DataFrame): DataFrame containing stock prices.
price_col (str): Column name of the price data.
tolerance (float): Tolerance for detecting potential splits.
Returns:
DataFrame: DataFrame with adjusted prices.
"""
split_ratios = {
# Splits
-0.50: 2,
-0.666: 3,
-0.75: 4,
# Reverse Splits
1.0: 0.5,
2.0: 1/3,
3.0: 1/4,
}
df['pct_change'] = df[price_col].pct_change()
for pct, ratio in split_ratios.items():
# Detect pct_changes that resemble splits
is_potential_split = np.isclose(df['pct_change'], pct, atol=tolerance)
if is_potential_split.any():
print('split detected')
split_indices = df.index[is_potential_split]
for idx in split_indices:
if idx == 0:
continue
# Check the next few days to ensure the price doesn't revert
price_at = df.loc[idx, price_col]
if idx + 3 < len(df):
price_after = df.loc[idx + 1:idx + 3, price_col].median()
if not np.isclose(price_after, price_at, rtol=0.1):
continue
# Adjust all prices before this date
df.loc[:idx, price_col] = df.loc[:idx, price_col] * ratio
df['pct_change'] = df[price_col].pct_change()
return df
price_before variable: It was not being used anywhere in the function.df.loc[:idx-1, price_col] = df.loc[:idx-1, price_col] / ratio to df.loc[:idx, price_col] = df.loc[:idx, price_col] * ratio to correctly adjust prices for splits and reverse splits.You can test the adjust_for_splits function with a sample DataFrame:
import pandas as pd
import numpy as np
# Create a sample DataFrame
df = pd.DataFrame({
'date': ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05'],
'price': [100, 50, 25, 25, 25]
})
# Convert date to datetime and set as index
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
# Adjust for splits
df = adjust_for_splits(df, 'price')
print(df)