람다 함수를 빌드하는 컨테이너 이미지 안의 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
권한 추가
테스트
'1인개발 메이킹로그 > [Infra+k8s+App] 가상화폐 자동매매' 카테고리의 다른 글
[AWS-Server] 6. S3 bucket 에 프로세스 로그 저장 (0) | 2023.04.07 |
---|---|
[AWS-Server] 5. 람다함수에서 EC2 로 명령 전달 (0) | 2023.04.04 |
[AWS-Server] 3. 람다함수에 Cloudwatch EventBridge 연결 (0) | 2023.04.02 |
[AWS-Server] 2. EC2에서 python 으로 dynamoDB Table, SSM Parameter Store 읽기 (0) | 2023.03.31 |
[AWS-Server] 1. 컨테이너 이미지로 람다 함수 띄우기 (0) | 2023.03.31 |