File size: 1,458 Bytes
1a01da0
 
1c344c6
1a01da0
1c344c6
1a01da0
 
1c344c6
 
1a01da0
 
1c344c6
1a01da0
1c344c6
1a01da0
1c344c6
1a01da0
1c344c6
1a01da0
 
1c344c6
1a01da0
1c344c6
 
1a01da0
1c344c6
 
 
 
 
 
 
 
1a01da0
 
1c344c6
 
 
 
 
 
 
 
 
 
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
41
42
43
44
45
46
import pandas as pd

def calculate_sma(data, window):
    """
    Calculate the Simple Moving Average (SMA) for the given data.

    Parameters:
    - data (pd.Series): The stock data (typically closing prices).
    - window (int): The period over which to calculate the SMA.

    Returns:
    - pd.Series: The calculated SMA values.
    """
    return data.rolling(window=window, min_periods=1).mean()

def calculate_21_50_sma(data):
    """
    Calculate both the 21-period and 50-period SMAs for the given stock data.

    Parameters:
    - data (pd.DataFrame): The stock data, expected to have a 'Close' column.

    Returns:
    - pd.DataFrame: The input data frame with added columns for the 21-period and 50-period SMAs.
    """
    if 'Close' not in data.columns:
        raise ValueError("Data frame must contain a 'Close' column.")

    # Calculate the SMAs
    data['SMA_21'] = calculate_sma(data['Close'], 21)
    data['SMA_50'] = calculate_sma(data['Close'], 50)

    return data

if __name__ == "__main__":
    # Example usage
    # Generate a sample DataFrame with 'Close' prices
    dates = pd.date_range(start='2023-01-01', periods=100, freq='D')
    close_prices = pd.Series((100 + np.random.randn(100).cumsum()), index=dates)
    sample_data = pd.DataFrame({'Close': close_prices})

    # Calculate the 21 and 50 period SMAs
    sma_data = calculate_21_50_sma(sample_data)

    print(sma_data.head())  # Print the first few rows to verify