天天看點

easytrader庫實作主力進出交易政策?(完整源碼示例)

作者:紫夜星辰zsabin

下面是一個簡單的主力進出交易政策的實作範例,供參考:

easytrader庫實作主力進出交易政策?(完整源碼示例)
from easytrader import *
import talib
import time

# 初始化easytrader接口
user = use('ht')   # 使用華泰證券交易接口
user.prepare('account.json')

# 擷取需要交易的股票代碼
target_stock = '600519'   # 股票代碼
amount = 100   # 購買數量

# 定義均線參數
short_period = 5   # 短期均線
middle_period = 10   # 中期均線
long_period = 20   # 長期均線

# 擷取股票的曆史資料
history_data = user.get_history_data(target_stock, 'D', 60)   # 擷取近60日的日線資料
(注:以上擷取股票的曆史資料已失效,需另尋可用的資料來源)
# 計算白線、黃線、紫線三條均線
close_prices = [float(item['price']) for item in history_data]
white_line = talib.SMA(close_prices, short_period)
yellow_line = talib.SMA(close_prices, middle_period)
purple_line = talib.SMA(close_prices, long_period)

# 擷取最新的股票價格和日期
latest_price = float(history_data[-1]['price'])
latest_date = history_data[-1]['date']

# 判斷目前價格在三條均線之間的位置
if latest_price > white_line[-1] and white_line[-1] > yellow_line[-1] and yellow_line[-1] > purple_line[-1]:
    # 白線向上突破黃線、紫線且三線向上發散,買入股票
    buy_price = latest_price
    user.buy(target_stock, price=buy_price, amount=amount)
    print('{} {} 在 {} 買入 {} 股,價格 {}'.format(latest_date, target_stock, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), amount, buy_price))
elif latest_price < white_line[-1] and white_line[-1] < yellow_line[-1] and yellow_line[-1] < purple_line[-1]:
    # 主力進出三線“死亡交叉”,盤口呈空頭排列,賣出股票
    sell_price = latest_price
    user.sell(target_stock, price=sell_price, amount=amount)
    print('{} {} 在 {} 賣出 {} 股,價格 {}'.format(latest_date, target_stock, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), amount, sell_price))
else:
    # 其他情況不執行任何操作
    pass
           
easytrader庫實作主力進出交易政策?(完整源碼示例)

需要注意的是,這個範例僅僅是一個簡單的示例,實際情況可能更加複雜,需要根據具體業務需求進行調整。同時,投資有風險,交易需謹慎,以上内容僅供參考。

easytrader庫實作主力進出交易政策?(完整源碼示例)

繼續閱讀