stockstats

repository·master·Indexed 23 days ago

https://github.com/jealous/stockstats

A helper library providing a wrapper for pandas DataFrames to enable easy calculation of stock technical indicators. It supports inline calculations for Moving Averages, Momentum, Trend, and Volatility indicators through column-based access patterns, as well as signal crossover detection and financial utilities like Typical Price and Log Returns.

Tokens
2.7K
Snippets
10
Records
18
Agent score
31%

What's inside stockstats

  1. How to use column naming patterns for indicators

    master

    Indicators are accessed using specific string patterns in the DataFrame. You can control the column and the window size using these patterns:

    1. Full Control: <column>_<window>_<indicator>

      • high_5_sma: 5-period simple moving average of the high price.
      • close_10_ema: 10-period exponential moving average of the close price.
      • high_-1_d: 1-period delta of the high price (negative window looks backward).
    2. Indicator with varying window: <indicator>_<window>

      • rsi_6: 6-period RSI.
      • cci_10: 10-period CCI.
      • atr_13: 13-period ATR.
  2. Load and wrap data with StockDataFrame

    master

    The StockDataFrame class acts as a wrapper for a pandas.DataFrame. You can initialize it using the wrap function or StockDataFrame.retype.

    To ensure compatibility, your DataFrame should include the following columns (case-insensitive):

    • close: the close price of the period
    • high: the highest price of the interval
    • low: the lowest price of the interval
    • volume: the volume of stocks traded during the interval
    • date: timestamp of the record (optional, used as index by default)

    You can use unwrap to convert the StockDataFrame back into a standard pandas.DataFrame.

    import pandas as pd
    from stockstats import wrap
    
    # from CSV
    df = wrap(pd.read_csv('stock.csv'))
    
    # from yfinance (disable multi-level index for compatibility)
    import yfinance as yf
    df = wrap(yf.download('AAPL', multi_level_index=False))
  3. Access multi-line indicators

    master

    Some indicators automatically generate multiple related columns. To ensure these columns are calculated and added to the DataFrame, use the .get() method on the StockDataFrame before attempting to access the individual columns.

    # MACD generates three columns at once
    df.get('macd')
    print(df[['macd', 'macds', 'macdh']].tail())
    
    # Bollinger Bands
    df.get('boll')
    print(df[['boll', 'boll_ub', 'boll_lb']].tail())
  4. Detect signal crossovers

    master

    You can detect signal crossovers (e.g., a fast moving average crossing a slow moving average) using specific naming conventions for column access. The syntax for a cross-up (golden cross) is {column1}_{window1}_{indicator}_{direction}_{column2}_{window2}_{indicator}.

    Example: df['close_10_sma_xu_close_50_sma'] detects when the 10-period SMA of the close column crosses above the 50-period SMA of the close column.

    # cross-over detection
    golden_cross = df['close_10_sma_xu_close_50_sma']  # 10 SMA crosses above 50 SMA
  5. Configure indicator default parameters with set_dft_window()

    master

    Some indicators have default window sizes or parameters that can be changed globally using set_dft_window(indicator_name, parameters).

    Note: Changes are global and will not affect existing columns. To re-evaluate indicators with new parameters, you must remove the existing columns first.

    Examples:

    • Single value (window): set_dft_window('rsi', 14)
    • Tuple of values: set_dft_window('macd', (12, 26, 9)) or set_dft_window('kama', (10, 5, 34))
    set_dft_window('tema', n)
    set_dft_window('kama', (10, 5, 34))
    set_dft_window('macd', (12, 26, 9))
    set_dft_window('rsi', n)
  6. Access Typical Price and Log Returns

    master

    The library provides built-in access to common financial calculations:

    • Typical Price: Accessed via df['middle']. It is the average of high, low, and close. If amount (total cash flow) is available, it uses amount / volume for higher accuracy.
    • Log Return: Accessed via df['log-ret']. Calculated as ln(close / last_close).
    df['middle']
    df['log-ret']
  7. Use Delta and Shift utilities

    master

    You can calculate price changes (deltas) and shift columns using string patterns:

    Delta (Difference between periods)

    • <column>_<window>_d: Difference between current and $n$ periods ago.
    • <column>_delta: Shortcut for <column>_-1_d (current vs previous).
    • Example: df['close_delta'] or df['high_2_d'] (high price delta between current and 2 days later).

    Shift (Moving data forward/backward)

    Shift columns backward or forward. Negative values shift forward.

    # Example of shifting columns
    # df[['close', 'close_-1_s', 'close_2_s']]
    df['close_delta']
    df['close_-1_d']
    df['high_2_d']
  8. Perform cross-over and comparison operations

    master

    The library provides patterns to detect when two columns cross or satisfy comparison logic:

    Cross-overs

    • <A>_xu_<B>: A crosses up B.
    • <A>_xd_<B>: A crosses down B.
    • <A>_x_<B>: A crosses B (either direction).

    Comparisons

    Use standard comparison operators between two columns A and B:

    • <A>_le_<B> (Less than or equal)
    • <A>_ge_<B> (Greater than or equal)
    • <A>_lt_<B> (Less than)
    • <A>_gt_<B> (Greater than)
    • <A>_eq_<B> (Equal)
    • <A>_ne_<B> (Not equal)
    kdjk_xu_kdjd
    kdjk_xd_kdjd
    kdjk_x_kdjd
    close_ge_70
  9. Initialize all indicators with df.init_all()

    master

    To quickly generate a large number of technical indicators (including shortcuts like KDJ, BOLL, and MFI), use the df.init_all() method.

    Warning: This operation generates many columns and should be used with caution.

    df.init_all()
  10. Count non-zero values in a range

    master

    You can count how many times a condition was met within a specific rolling window using the pattern <column>_<window>_c.

    Steps:

    1. Create a boolean column based on a condition (e.g., df['res'] = df['middle'] > df['close']).
    2. Access the count using the pattern on that boolean column.

    Example: Count how many times typical price was larger than close in the past 10 periods

    tp = df['middle']
    df['res'] = df['middle'] > df['close']
    # Access the count of True values in the last 10 periods
    count_column = df['res_10_c']
  11. Access indicators with default and custom windows

    master

    Indicators are calculated lazily upon first access. You can access indicators using their name as a column key. For indicators requiring a window (period), you can use the default window by using the indicator name, or specify a custom window using the format {indicator}_{window}.

    Example:

    • df['rsi'] uses the default 14-period RSI.
    • df['rsi_6'] uses a 6-period RSI.
    • df['close_20_sma'] calculates a 20-period SMA on the close column.
    • df['high_10_ema'] calculates a 10-period EMA on the high column.
    # indicators with default windows
    rsi = df['rsi']           # 14-period RSI (default)
    rsi6 = df['rsi_6']        # 6-period RSI
    
    # moving averages on any column
    sma = df['close_20_sma']  # 20-period SMA of close
    ema = df['high_10_ema']   # 10-period EMA of high