<commit_before>from jqdata import *
import numpy as np
import pandas as pd
import talib as ta
from math import isnan, floor
from math import atan
import tushare as ts

# 股票池来源
class Source(Enum):
    AUTO = 0  # 程序根据波动率及股价自动从沪深300中获取股票
    CLIENT = 1  # 使用用户提供的股票


g.stocks_source = Source.CLIENT  # 默认使用自动的方法获得股票

g.stock_id_list_from_client = ["002506.XSHE", "600703.XSHG", "300059.XSHE", "600206.XSHG",
                               "002281.XSHE", "600340.XSHG", "002092.XSHE", "002440.XSHE",
                               "600897.XSHG", "000063.XSHE"]
g.stock_position = {"002506.XSHE": 0,
                    "600703.XSHG": 0,
                    "300059.XSHE": 0,
                    "600206.XSHG": 0,
                    "002281.XSHE": 0,
                    "600340.XSHG": 0,
                    "002092.XSHE": 0,
                    "002440.XSHE": 0,
                    "600897.XSHG": 0,
                    "000063.XSHE": 0}
# 持仓股票池详细信息
g.basestock_pool = []

# 用于统计结果
g.repeat_signal_count = 0
g.reset_order_count = 0
g.success_count = 0

# MA平均的天数
g.ma_4day_count = 4
g.ma_13day_count = 13

# 每次调整的比例
g.adjust_scale = 0.25

# 期望收益率
g.expected_revenue = 0.003

# 角度阈值
g.angle_threshold = 30


class Angle(Enum):
    UP = 1  # 角度>30
    MIDDLE = 0  # 角度<=30 且 角度>=-30
    DOWN = -1  # 角度<-30


class Status(Enum):
    INIT = 0  # 在每天交易开始时，置为INIT
    WORKING = 1  # 处于买/卖中
    NONE = 2  # 今天不再做任何交易


class Break(Enum):
    UP = 0  # 上穿
    DOWN = 1  # 下穿
    NONE = 2


'''
    记录股票详细信息
'''


class BaseStock(object):
    def __init__(self, stock, close, min_vol, max_vol, lowest, highest, status, position, sell_order_id, buy_order_id):
        self.stock = stock
        self.close = close
        self.min_vol = min_vol
        self.max_vol = max_vol
        self.lowest = lowest
        self.highest = highest

        self.status = status
        self.position = position
        self.sell_order_id = sell_order_id
        self.sell_price = 0
        self.buy_order_id = buy_order_id
        self.buy_price = 0

        self.break_throught_type = Break.NONE  # 突破类型 up or down
        self.break_throught_time = None  # 突破时间点
        self.delay_amount = 0  # 反向挂单量
        self.delay_price = 0  # 反向挂单价格
        self.operator_value_4 = 0
        self.operator_value_13 = 0
        self.angle = 1000

    def print_stock(self):
        log.info(
            "stock: %s, close: %f, min_vol: %f, max_vol: %f, lowest: %f, hightest: %f, position: %f, sell_roder_id: %d, buy_order_id: %d, operator_value_4: %f, operator_value_13: %f"
            , self.stock, self.close, self.min_vol, self.max_vol, self.lowest, self.highest, self.position,
            self.sell_order_id, self.buy_order_id, self.operator_value_4, self.operator_value_13)


def get_stocks_by_client(context):
    '''
    直接从客户得到股票列表
    '''
    select_count = 0
    for stock_id in g.stock_id_list_from_client:
        stock_obj = BaseStock(stock_id, 0, 0, 0, 0, 0, Status.INIT, g.stock_position[stock_id], -1, -1)
        stock_obj.print_stock()

        g.basestock_pool.append(stock_obj)
        select_count += 1

    if select_count < g.position_count:
        g.position_count = select_count


def get_stock_angle(context, stock):
    '''ATAN(（五日收盘价均线值/昨日的五日收盘均线值-1）*100）*57.3'''

    df_close = get_price(stock, count=6, end_date=str(context.current_dt), frequency='daily', fields=['close'])
    close_list = [item for item in df_close['close']]

    yesterday_5MA = (reduce(lambda x, y: x + y, close_list) - close_list[5]) / 5
    today_5MA = (reduce(lambda x, y: x + y, close_list) - close_list[0]) / 5
    angle = math.atan((today_5MA / yesterday_5MA - 1) * 100) * 57.3
    log.info("股票：%s的角度为：%f", stock, angle)
    return angle


def initialize(context):
    log.info("---> 策略初始化 @ %s" % (str(context.current_dt)))
    g.repeat_signal_count = 0
    g.reset_order_count = 0
    g.success_count = 0
    # 第一天运行时，需要选股入池，并且当天不可进行股票交易
    g.firstrun = True

    # 默认股票池容量
    g.position_count = 30

    if g.stocks_source == Source.AUTO:
        log.info("程序根据波动率及股价自动从沪深300中获取股票")
        pass

    elif g.stocks_source == Source.CLIENT:<commit_msg>bugfix: 增加主动性买盘成交量<commit_after>from jqdata import *
import numpy as np
import pandas as pd
import talib as ta
from math import isnan, floor
from math import atan
import tushare as ts

# 股票池来源
class Source(Enum):
    AUTO = 0  # 程序根据波动率及股价自动从沪深300中获取股票
    CLIENT = 1  # 使用用户提供的股票


g.stocks_source = Source.CLIENT  # 默认使用自动的方法获得股票

g.stock_id_list_from_client = ["002506.XSHE", "600703.XSHG", "300059.XSHE", "600206.XSHG",
                               "002281.XSHE", "600340.XSHG", "002092.XSHE", "002440.XSHE",
                               "600897.XSHG", "000063.XSHE"]
g.stock_position = {"002506.XSHE": 0,
                    "600703.XSHG": 0,
                    "300059.XSHE": 0,
                    "600206.XSHG": 0,
                    "002281.XSHE": 0,
                    "600340.XSHG": 0,
                    "002092.XSHE": 0,
                    "002440.XSHE": 0,
                    "600897.XSHG": 0,
                    "000063.XSHE": 0}
# 持仓股票池详细信息
g.basestock_pool = []

# 用于统计结果
g.repeat_signal_count = 0
g.reset_order_count = 0
g.success_count = 0

# MA平均的天数
g.ma_4day_count = 4
g.ma_13day_count = 13

# 每次调整的比例
g.adjust_scale = 0.25

# 期望收益率
g.expected_revenue = 0.003

# 角度阈值
g.angle_threshold = 30


class Angle(Enum):
    UP = 1  # 角度>30
    MIDDLE = 0  # 角度<=30 且 角度>=-30
    DOWN = -1  # 角度<-30


class Status(Enum):
    INIT = 0  # 在每天交易开始时，置为INIT
    WORKING = 1  # 处于买/卖中
    NONE = 2  # 今天不再做任何交易


class Break(Enum):
    UP = 0  # 上穿
    DOWN = 1  # 下穿
    NONE = 2


'''
    记录股票详细信息
'''


class BaseStock(object):
    def __init__(self, stock, close, min_vol, max_vol, lowest, highest, status, position, sell_order_id, buy_order_id):
        self.stock = stock
        self.close = close
        self.min_vol = min_vol
        self.max_vol = max_vol
        self.lowest = lowest
        self.highest = highest

        self.status = status
        self.position = position
        self.sell_order_id = sell_order_id
        self.sell_price = 0
        self.buy_order_id = buy_order_id
        self.buy_price = 0

        self.break_throught_type = Break.NONE  # 突破类型 up or down
        self.break_throught_time = None  # 突破时间点
        self.delay_amount = 0  # 反向挂单量
        self.delay_price = 0  # 反向挂单价格
        self.operator_value_4 = 0
        self.operator_value_13 = 0
        self.angle = 1000

    def print_stock(self):
        log.info(
            "stock: %s, close: %f, min_vol: %f, max_vol: %f, lowest: %f, hightest: %f, position: %f, sell_roder_id: %d, buy_order_id: %d, operator_value_4: %f, operator_value_13: %f"
            , self.stock, self.close, self.min_vol, self.max_vol, self.lowest, self.highest, self.position,
            self.sell_order_id, self.buy_order_id, self.operator_value_4, self.operator_value_13)


def get_stocks_by_client(context):
    '''
    直接从客户得到股票列表
    '''
    select_count = 0
    for stock_id in g.stock_id_list_from_client:
        stock_obj = BaseStock(stock_id, 0, 0, 0, 0, 0, Status.INIT, g.stock_position[stock_id], -1, -1)
        stock_obj.print_stock()

        g.basestock_pool.append(stock_obj)
        select_count += 1

    if select_count < g.position_count:
        g.position_count = select_count


def get_stock_angle(context, stock):
    '''ATAN(（五日收盘价均线值/昨日的五日收盘均线值-1）*100）*57.3'''

    df_close = get_price(stock, count=6, end_date=str(context.current_dt), frequency='daily', fields=['close'])
    close_list = [item for item in df_close['close']]

    yesterday_5MA = (reduce(lambda x, y: x + y, close_list) - close_list[5]) / 5
    today_5MA = (reduce(lambda x, y: x + y, close_list) - close_list[0]) / 5
    angle = math.atan((today_5MA / yesterday_5MA - 1) * 100) * 57.3
    log.info("股票：%s的角度为：%f", stock, angle)
    return angle



def evaluate_activeVolBuy(np_close, vol):
    """
    主动性买盘成交量
    :param np_close:
    :param vol:
    :return:
    """
    diff_a1 = np.diff(np_close)
    comp_vol = vol[1:]
    activeVolBuy = []
    activeVolSell = []
    swingVol = []
    accumulateNetVol = 0
    netVol_buySell = []
    MFI_indicator = []  # 威廉姆斯的分形数学/混沌操作法的指标

    for i in range(len(diff_a1)):
        mfi = diff_a1[i] / comp_vol[i]
        MFI_indicator.append(mfi)
        if diff_a1[i] > 0:
            activeVolBuy.append(comp_vol[i])
            activeVolSell.append(0)
        elif diff_a1[i] < 0:
            activeVolSell.append(comp_vol[i])
            activeVolBuy.append(0)
        else:
            swingVol.append(comp_vol[i])
            activeVolBuy.append(0)
            activeVolSell.append(0)

    for k in range(len(activeVolBuy)):
        netVol = activeVolBuy[k] - activeVolSell[k]
        accumulateNetVol += netVol
        netVol_buySell.append(accumulateNetVol)

    netVol_buySell_sum = np.sum(np.array(activeVolBuy)) - np.sum(np.array(activeVolSell))
    print('netVol_buySell_sum= %d', netVol_buySell_sum)

def initialize(context):
    log.info("---> 策略初始化 @ %s" % (str(context.current_dt)))
    g.repeat_signal_count = 0
    g.reset_order_count = 0
    g.success_count = 0
    # 第一天运行时，需要选股入池，并且当天不可进行股票交易
    g.firstrun = True

    # 默认股票池容量
    g.position_count = 30

    if g.stocks_source == Source.AUTO:
        log.info("程序根据波动率及股价自动从沪深300中获取股票")
        pass

    elif g.stocks_source == Source.CLIENT:
{'fraction_non_alphanumeric': 0.11863684771033013, 'fraction_numerical': 0.05015974440894569, 'mean_word_length': 2.363538681948424, 'pattern_counts': {'":': 20, '<': 10, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4860147', 'n_tokens_mistral': 4257, 'n_tokens_neox': 4016, 'n_words': 709}