File size: 806 Bytes
517c0ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import pandas as pd

def calculate_sma(data, column='close', period=21):
    """
    Calculates the Simple Moving Average (SMA) for a specified column in the data DataFrame.

    Args:
        data (pd.DataFrame): The input DataFrame containing the price data.
        column (str): The name of the column to calculate the SMA on. Default is 'close'.
        period (int): The period over which to calculate the SMA. Default is 21.

    Returns:
        pd.Series: A pandas Series containing the SMA for the specified period.
    """
    sma = data[column].rolling(window=period, min_periods=1).mean()
    return sma

# Example usage:
# Assuming `data` is a pandas DataFrame with a 'close' column containing closing prices:
# sma21 = calculate_sma(data, column='close', period=21)
# data['SMA_21'] = sma21