Jonathan Tong
Jonathan Tong

Reputation: 3

How to create a new dataframe by sorted data

I would like to find out the row which meets the condition RSI < 25. However, the result is generated with one data frame. Is it possible to create separate dataframes for any single row?

Thanks.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas_datareader import data as wb

stock='TSLA'

ck_df = wb.DataReader(stock,data_source='yahoo',start='2015-01-01')

rsi_period = 14

chg = ck_df['Close'].diff(1)

gain = chg.mask(chg<0,0)
ck_df['Gain'] = gain

loss = chg.mask(chg>0,0)
ck_df['Loss'] = loss

avg_gain = gain.ewm(com = rsi_period-1,min_periods=rsi_period).mean()
avg_loss = loss.ewm(com = rsi_period-1,min_periods=rsi_period).mean()

ck_df['Avg Gain'] = avg_gain
ck_df['Avg Loss'] = avg_loss

rs = abs(avg_gain/avg_loss)

rsi = 100-(100/(1+rs))

ck_df['RSI'] = rsi

RSIFactor = ck_df['RSI'] <25

ck_df[RSIFactor]

Upvotes: 0

Views: 1336

Answers (2)

Zanshin
Zanshin

Reputation: 1272

To split the rows found by @Omkar's solution into separate dataframes you might use this function taken from here: Pandas: split dataframe into multiple dataframes by number of rows;

def split_dataframe_to_chunks(df, n):
    df_len = len(df)
    count = 0
    dfs = []

    while True:
        if count > df_len-1:
            break

        start = count
        count += n
        dfs.append(df.iloc[start : count])
    return dfs

With this you get a list of dataframes.

Upvotes: 0

Omkar Sabade
Omkar Sabade

Reputation: 783

If you want to know at what index the RSI < 25 then just use:

ck_df[ck_df['RSI'] <25].index

The result will also be a dataframe. If you insist on making a new one then:

new_df = ck_df[ck_df['RSI'] <25].copy()

Upvotes: 1

Related Questions