让我的def函数应用。()到我的股票

时间:2016-05-03 23:07:54

标签: python numpy pandas apply stock

我无法让代码工作。我在称为“Quantopian”的回测环境中编码python。无论如何,.apply(),系列,.pd或任何术语都超出了我的技能水平。 (假设我甚至在正确的轨道上大声笑)

我想要完成的任务: 拿几只股票并不断计算MACD。然后,当指标满足某个条件时,算法会购买或出售该特定股票。

MACD简单化了什么: 一个动量指标,用于查看历史数据,使用12,26和9天的指数移动平均线并将它们相互比较。 我设计了自己的功能,这不是我的问题......

帮助 我正试图将它应用到宇宙中的股票池中,以便每分钟不断计算MACD。

我特别困惑的地方: 我定义了一个MACD函数,但不知道如何计算我池中任何股票的每一分钟。

CODE:

import numpy as np
import math
import talib as ta
import pandas as pd

def initialize(context):
set_commission(commission.PerTrade(cost=10))
context.stocks = symbols('AAPL', 'GOOG_L')

def handle_data(context, data):
    for stock in context.stocks:
        prices_fast = data.history(context.stocks, "close", 390, "1m").resample("30min").dropna()
        prices_slow = data.history(context.stocks, "close", 390, "1m").resample("30min").dropna()
        prices_signal = data.history(context.stocks, "close", 390, "1m").resample("30min").dropna()
        curr_price = data.history(context.stocks, "price", 30, "1m").resample("30min")[-1:].dropna()

        series = pd.Series([stock]).dropna()
        macd = series.apply(MACD)

        macd_func = stock.apply(MACD)
        if macd_func[stock] > 0:
            order(stock, 1)

    print macd_func
    record(macd=macd_func[stock])

def MACD(prices_fast, prices_slow, prices_signal, curr_price):        
    # Setting MACD Conditions:
    slow = 26
    fast = 12
    signal = 9

    # Calcualting Averages:
    avg_fast = pd.rolling_sum(prices_fast[:fast], fast)[-1:] / fast
    avg_slow = pd.rolling_sum(prices_slow[:slow], slow)[-1:] / slow
    avg_signal = pd.rolling_sum(prices_signal[:signal], signal)[-1:] / signal

    # Calculating the Weighting Multipliers:
    A = 2 / (fast + 1)
    B = 2 / (slow + 1) 
    C = 2 / (signal + 1)

    # Calculating the Exponential Moving Averages:
    EMA_fast =  (curr_price * A) + [avg_fast * (1 - A)]
    EMA_slow =  (curr_price * B) + [avg_slow * (1 - B)]
    EMA_signal = (curr_price * C) + [avg_signal * (1 - C)]

    # Calculating MACD Histogram:
    macd = EMA_fast - EMA_slow - EMA_signal

如果有人能帮我办理,我会非常感激!

非常感谢你,

麦克

0 个答案:

没有答案