コード例 #1
0
 def test_fi2(self):
     target = 'FI'
     result = ForceIndexIndicator(close=self._df['Close'],
                                  volume=self._df['Volume'],
                                  n=13,
                                  fillna=False).force_index()
     pd.testing.assert_series_equal(self._df[target].tail(),
                                    result.tail(),
                                    check_names=False)
コード例 #2
0
 def setUpClass(cls):
     cls._df = pd.read_csv(cls._filename, sep=",")
     cls._params = dict(close=cls._df["Close"],
                        volume=cls._df["Volume"],
                        window=13,
                        fillna=False)
     cls._indicator = ForceIndexIndicator(**cls._params)
コード例 #3
0
 def setUpClass(cls):
     cls._df = pd.read_csv(cls._filename, sep=',')
     cls._params = dict(close=cls._df['Close'],
                        volume=cls._df['Volume'],
                        n=13,
                        fillna=False)
     cls._indicator = ForceIndexIndicator(**cls._params)
コード例 #4
0
def add_volume_ta(df: pd.DataFrame, high: str, low: str, close: str, volume: str,
                  fillna: bool = False, colprefix: str = "") -> pd.DataFrame:
    """Add volume technical analysis features to dataframe.

    Args:
        df (pandas.core.frame.DataFrame): Dataframe base.
        high (str): Name of 'high' column.
        low (str): Name of 'low' column.
        close (str): Name of 'close' column.
        volume (str): Name of 'volume' column.
        fillna(bool): if True, fill nan values.
        colprefix(str): Prefix column names inserted

    Returns:
        pandas.core.frame.DataFrame: Dataframe with new features.
    """

    # Accumulation Distribution Index
    df[f'{colprefix}volume_adi'] = AccDistIndexIndicator(
        high=df[high], low=df[low], close=df[close], volume=df[volume], fillna=fillna).acc_dist_index()

    # On Balance Volume
    df[f'{colprefix}volume_obv'] = OnBalanceVolumeIndicator(
        close=df[close], volume=df[volume], fillna=fillna).on_balance_volume()

    # Chaikin Money Flow
    df[f'{colprefix}volume_cmf'] = ChaikinMoneyFlowIndicator(
        high=df[high], low=df[low], close=df[close], volume=df[volume], fillna=fillna).chaikin_money_flow()

    # Force Index
    df[f'{colprefix}volume_fi'] = ForceIndexIndicator(
        close=df[close], volume=df[volume], n=13, fillna=fillna).force_index()

    # Money Flow Indicator
    df[f'{colprefix}volume_mfi'] = MFIIndicator(
        high=df[high], low=df[low], close=df[close], volume=df[volume], n=14, fillna=fillna).money_flow_index()

    # Ease of Movement
    indicator = EaseOfMovementIndicator(high=df[high], low=df[low], volume=df[volume], n=14, fillna=fillna)
    df[f'{colprefix}volume_em'] = indicator.ease_of_movement()
    df[f'{colprefix}volume_sma_em'] = indicator.sma_ease_of_movement()

    # Volume Price Trend
    df[f'{colprefix}volume_vpt'] = VolumePriceTrendIndicator(
        close=df[close], volume=df[volume], fillna=fillna).volume_price_trend()

    # Negative Volume Index
    df[f'{colprefix}volume_nvi'] = NegativeVolumeIndexIndicator(
        close=df[close], volume=df[volume], fillna=fillna).negative_volume_index()

    # Volume Weighted Average Price
    df[f'{colprefix}volume_vwap'] = VolumeWeightedAveragePrice(
        high=df[high], low=df[low], close=df[close], volume=df[volume], n=14, fillna=fillna
    ).volume_weighted_average_price()

    return df
コード例 #5
0
def handler(event, context):
    # DynamoDb
    dynamodb = boto3.resource('dynamodb')
    tableName = os.environ['DATABASE']
    table = dynamodb.Table(tableName)

    # Get stock data
    stock = yf.Ticker('^GSPC')
    stock_data_weekly = stock.history(period="5y", interval="5d")
    stock_data_daily = stock.history(period="2y", interval="1d")

    # Calculate impulse system weekly
    macd_hist = MACD(stock_data_weekly["Close"], fillna=True).macd_diff()
    ema = EMAIndicator(
        stock_data_weekly["Close"], n=13, fillna=True).ema_indicator()
    shouldBeGreen = ema.iloc[-1] > ema.iloc[-2] and macd_hist.iloc[-1] > macd_hist.iloc[-2]
    shouldBeRed = ema.iloc[-1] < ema.iloc[-2] and macd_hist.iloc[-1] < macd_hist.iloc[-2]
    colorWeekly = 'green' if shouldBeGreen else 'red' if shouldBeRed else 'blue'

    # Calculate impulse system daily
    macd_hist = MACD(stock_data_daily["Close"], fillna=True).macd_diff()
    ema = EMAIndicator(
        stock_data_daily["Close"], n=13, fillna=True).ema_indicator()
    shouldBeGreen = ema.iloc[-1] > ema.iloc[-2] and macd_hist.iloc[-1] > macd_hist.iloc[-2]
    shouldBeRed = ema.iloc[-1] < ema.iloc[-2] and macd_hist.iloc[-1] < macd_hist.iloc[-2]
    colorDaily = 'green' if shouldBeGreen else 'red' if shouldBeRed else 'blue'

    # Caculate ForceIndex 13 days
    indicator_fi = ForceIndexIndicator(
        stock_data_daily["Close"], stock_data_daily["Volume"], 13, fillna=True).force_index()

    lastForceIndexValue = indicator_fi.iloc[-1]

    lastFIDecimal = Decimal(lastForceIndexValue)

    lastFI = round(lastFIDecimal, 0)

    lastCloseData = stock_data_daily.iloc[-1]["Close"]

    lastCloseDecimal = Decimal(lastCloseData)
    lastClose = round(lastCloseDecimal, 2)

    # daily timestamp
    date = datetime.utcnow()
    future = date + timedelta(days=14)
    expiryDate = round(future.timestamp() * 1000)
    dateString = date.strftime("%Y-%m-%d")

    id = str(uuid.uuid4())

    entry = {
        'symbol': '^GSPC',
        'id': id,
        'date': dateString,
        'ttl': expiryDate,
        'weeklyImpulse': colorWeekly,
        'dailyImpulse': colorDaily,
        'forceIndex13': lastFI,
        'lastClose': lastClose,
    }

    table.put_item(Item=entry)

    return entry
コード例 #6
0
def handler(event, context):

    # Setup dynamodb table
    dynamodb = boto3.resource('dynamodb')
    tableName = os.environ['DATABASE']
    table = dynamodb.Table(tableName)

    # Get stock data
    stock = yf.Ticker(event['symbol'])

    if (event['date']):
        endDate = datetime.strptime(event['date'], "%Y-%m-%d")
    else:
        endDate = datetime.utcnow()

    startDate = endDate - timedelta(weeks=156)
    stock_data = stock.history(end=endDate, start=startDate, interval="1d")

    # Get Force Index result
    indicator_fi = ForceIndexIndicator(stock_data["Close"],
                                       stock_data["Volume"],
                                       2,
                                       fillna=True).force_index()
    shouldGoLong = indicator_fi.iloc[-1] < 0 and indicator_fi.iloc[-2] > 0

    dailyData = stock_data.iloc[-1]

    openValue = dailyData["Open"]
    openPrice = Decimal(openValue)
    roundedOpenPrice = round(openPrice, 2)
    highValue = dailyData["High"]
    highPrice = Decimal(highValue)
    roundedHighPrice = round(highPrice, 2)

    lowValue = dailyData["Low"]
    lowPrice = Decimal(lowValue)
    roundedLowPrice = round(lowPrice, 2)

    closeValue = dailyData["Close"]
    closePrice = Decimal(closeValue)
    roundedClosePrice = round(closePrice, 2)

    volumeValue = dailyData["Volume"]
    volumePrice = Decimal(volumeValue)
    roundedVolumePrice = round(volumePrice, 2)

    dailyEntry = {
        'type': 'force_index',
        'result': 'long' if shouldGoLong else 'short',
        'open': roundedOpenPrice,
        'high': roundedHighPrice,
        'low': roundedLowPrice,
        'close': roundedClosePrice,
        'volume': roundedVolumePrice
    }

    # Write to database
    table.update_item(Key={
        'symbol': event['symbol'],
        'date': event['date']
    },
                      UpdateExpression='SET daily = :dailyEntry',
                      ExpressionAttributeValues={':dailyEntry': dailyEntry})

    # Return for next step in step functions
    return dailyEntry