공부하기싫어
article thumbnail

람다 함수를 빌드하는 컨테이너 이미지 안의 python 코드에 dynamoDB 를 수정하는 코드와 x-ray-sdk 를 추가

 

람다 코드 수정 - dynamoDB table 업데이트 + X-Ray-SDK

python-boto3

lambda-bestk/lambda/app.py

import pyupbit
import numpy as np
import boto3


def get_ror(k=0.5):
    df = pyupbit.get_ohlcv("KRW-BTC", count=7)
    df['range'] = (df['high'] - df['low']) * k
    df['target'] = df['open'] + df['range'].shift(1)

    df['ror'] = np.where(df['high'] > df['target'],
                         df['close'] / df['target'],
                         1)

    ror = df['ror'].cumprod()[-2]
    return ror



def update_dynamodb_table(bestk):
    dynamodb = boto3.client('dynamodb')
    
    # define the table name and the key of the item to be updated
    table_name = 'table-for-Ethereum-Autotrade'
    item_key = {'Env': {'S': 'Dev'}}
    
    # define the attribute to be updated and its new value
    attribute_name = 'k-value'
    new_value = bestk
    
    # update the item with the new attribute value
    response = dynamodb.update_item(
        TableName=table_name,
        Key=item_key,
        UpdateExpression='SET #attr = :val',
        ExpressionAttributeNames={'#attr': attribute_name},
        ExpressionAttributeValues={':val': {'N': str(new_value)}}
    )
    return response


def handler(event, context):
    dict={}
    for k in np.arange(0.1, 1.0, 0.1):
        ror = get_ror(k)
        print("%.1f %f" % (k, ror))
        dict[k]=ror
    bestk=max(dict, key=dict.get)
    bestk=round(bestk, 1)
    result=update_dynamodb_table(bestk)

    return result

 

lambda-endpricewithAI/lambda/app.py

import json
import pyupbit
from prophet import Prophet
import boto3


def predict_price(ticker):
    """Prophet으로 당일 종가 가격 예측"""

    #최근 200시간의 데이터 불러오기
    df = pyupbit.get_ohlcv(ticker, interval="minute60")

    #시간(ds) 과 종가(y) 만 남김
    df = df.reset_index()
    df['ds'] = df['index']
    df['y'] = df['close']
    data = df[['ds','y']]

    #학습
    model = Prophet()
    model.fit(data)

    #24시간 미래 예측
    future = model.make_future_dataframe(periods=24, freq='H')
    forecast = model.predict(future)

    #예상 종가 도출
    closeDf = forecast[forecast['ds'] == forecast.iloc[-1]['ds'].replace(hour=9)]
    if len(closeDf) == 0:
        closeDf = forecast[forecast['ds'] == data.iloc[-1]['ds'].replace(hour=9)]
    closeValue = closeDf['yhat'].values[0]
    predicted_close_price = closeValue

    return predicted_close_price



def update_dynamodb_table(endprice):
    dynamodb = boto3.client('dynamodb')
    
    # define the table name and the key of the item to be updated
    table_name = 'table-for-Ethereum-Autotrade'
    item_key = {'Env': {'S': 'Dev'}}
    
    # define the attribute to be updated and its new value
    attribute_name = 'endprice'
    new_value = endprice
    
    # update the item with the new attribute value
    response = dynamodb.update_item(
        TableName=table_name,
        Key=item_key,
        UpdateExpression='SET #attr = :val',
        ExpressionAttributeNames={'#attr': attribute_name},
        ExpressionAttributeValues={':val': {'N': str(new_value)}}
    )
    return response



def handler(event, context):
    endprice=predict_price("KRW-ETH")
    result=update_dynamodb_table(endprice)

    return result

 

권한 추가

 

 

 

테스트