-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCore Logic.py
More file actions
40 lines (33 loc) · 1.55 KB
/
Copy pathCore Logic.py
File metadata and controls
40 lines (33 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import pandas as pd
import logging
def load_and_validate_data(filepath: str) -> pd.DataFrame:
"""Loads CSV and validates the required structure."""
try:
# Load the dataset
df = pd.read_csv(filepath)
except FileNotFoundError:
logging.error(f"Input file missing: {filepath}")
raise
except pd.errors.EmptyDataError:
logging.error("Input CSV is completely empty or invalid.")
raise
# Validate that the 'close' column exists [cite: 27, 38]
if 'close' not in df.columns:
logging.error("Required column 'close' is missing.")
raise ValueError("Missing 'close' column.")
# Validate the dataframe actually has rows [cite: 27]
if df.empty:
logging.error("Dataset contains no data rows.")
raise ValueError("Empty dataset.")
return df
def compute_signals(df: pd.DataFrame, window: int) -> pd.DataFrame:
"""Computes the rolling mean and generates the binary signal."""
# Compute rolling mean on 'close' [cite: 41]
df['rolling_mean'] = df['close'].rolling(window=window).mean()
# Generate signal: 1 if close > rolling_mean, else 0 [cite: 45]
# IMPORTANT: The assignment asks how we handle the first window-1 rows.
# Pandas naturally puts NaNs in the rolling_mean for the first (window-1) rows.
# In Python, (Any Number > NaN) evaluates to False.
# Therefore, those initial rows will safely and consistently evaluate to a signal of 0.
df['signal'] = (df['close'] > df['rolling_mean']).astype(int)
return df