partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | QA_indicator_PBX | 瀑布线 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_PBX(DataFrame, N1=3, N2=5, N3=8, N4=13, N5=18, N6=24):
'瀑布线'
C = DataFrame['close']
PBX1 = (EMA(C, N1) + EMA(C, 2 * N1) + EMA(C, 4 * N1)) / 3
PBX2 = (EMA(C, N2) + EMA(C, 2 * N2) + EMA(C, 4 * N2)) / 3
PBX3 = (EMA(C, N3) + EMA(C, 2 * N3) + EMA(C, 4 * N3)) / 3
PBX4 = (EMA(C, N4) + EMA(C, 2 * N4) + EMA(C, 4 * N4)) / 3
PBX5 = (EMA(C, N5) + EMA(C, 2 * N5) + EMA(C, 4 * N5)) / 3
PBX6 = (EMA(C, N6) + EMA(C, 2 * N6) + EMA(C, 4 * N6)) / 3
DICT = {'PBX1': PBX1, 'PBX2': PBX2, 'PBX3': PBX3,
'PBX4': PBX4, 'PBX5': PBX5, 'PBX6': PBX6}
return pd.DataFrame(DICT) | def QA_indicator_PBX(DataFrame, N1=3, N2=5, N3=8, N4=13, N5=18, N6=24):
'瀑布线'
C = DataFrame['close']
PBX1 = (EMA(C, N1) + EMA(C, 2 * N1) + EMA(C, 4 * N1)) / 3
PBX2 = (EMA(C, N2) + EMA(C, 2 * N2) + EMA(C, 4 * N2)) / 3
PBX3 = (EMA(C, N3) + EMA(C, 2 * N3) + EMA(C, 4 * N3)) / 3
PBX4 = (EMA(C, N4) + EMA(C, 2 * N4) + EMA(C, 4 * N4)) / 3
PBX5 = (EMA(C, N5) + EMA(C, 2 * N5) + EMA(C, 4 * N5)) / 3
PBX6 = (EMA(C, N6) + EMA(C, 2 * N6) + EMA(C, 4 * N6)) / 3
DICT = {'PBX1': PBX1, 'PBX2': PBX2, 'PBX3': PBX3,
'PBX4': PBX4, 'PBX5': PBX5, 'PBX6': PBX6}
return pd.DataFrame(DICT) | [
"瀑布线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L121-L133 | [
"def",
"QA_indicator_PBX",
"(",
"DataFrame",
",",
"N1",
"=",
"3",
",",
"N2",
"=",
"5",
",",
"N3",
"=",
"8",
",",
"N4",
"=",
"13",
",",
"N5",
"=",
"18",
",",
"N6",
"=",
"24",
")",
":",
"C",
"=",
"DataFrame",
"[",
"'close'",
"]",
"PBX1",
"=",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_DMA | 平均线差 DMA | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_DMA(DataFrame, M1=10, M2=50, M3=10):
"""
平均线差 DMA
"""
CLOSE = DataFrame.close
DDD = MA(CLOSE, M1) - MA(CLOSE, M2)
AMA = MA(DDD, M3)
return pd.DataFrame({
'DDD': DDD, 'AMA': AMA
}) | def QA_indicator_DMA(DataFrame, M1=10, M2=50, M3=10):
"""
平均线差 DMA
"""
CLOSE = DataFrame.close
DDD = MA(CLOSE, M1) - MA(CLOSE, M2)
AMA = MA(DDD, M3)
return pd.DataFrame({
'DDD': DDD, 'AMA': AMA
}) | [
"平均线差",
"DMA"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L136-L145 | [
"def",
"QA_indicator_DMA",
"(",
"DataFrame",
",",
"M1",
"=",
"10",
",",
"M2",
"=",
"50",
",",
"M3",
"=",
"10",
")",
":",
"CLOSE",
"=",
"DataFrame",
".",
"close",
"DDD",
"=",
"MA",
"(",
"CLOSE",
",",
"M1",
")",
"-",
"MA",
"(",
"CLOSE",
",",
"M2"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_MTM | 动量线 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_MTM(DataFrame, N=12, M=6):
'动量线'
C = DataFrame.close
mtm = C - REF(C, N)
MTMMA = MA(mtm, M)
DICT = {'MTM': mtm, 'MTMMA': MTMMA}
return pd.DataFrame(DICT) | def QA_indicator_MTM(DataFrame, N=12, M=6):
'动量线'
C = DataFrame.close
mtm = C - REF(C, N)
MTMMA = MA(mtm, M)
DICT = {'MTM': mtm, 'MTMMA': MTMMA}
return pd.DataFrame(DICT) | [
"动量线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L148-L155 | [
"def",
"QA_indicator_MTM",
"(",
"DataFrame",
",",
"N",
"=",
"12",
",",
"M",
"=",
"6",
")",
":",
"C",
"=",
"DataFrame",
".",
"close",
"mtm",
"=",
"C",
"-",
"REF",
"(",
"C",
",",
"N",
")",
"MTMMA",
"=",
"MA",
"(",
"mtm",
",",
"M",
")",
"DICT",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_EXPMA | 指数平均线 EXPMA | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_EXPMA(DataFrame, P1=5, P2=10, P3=20, P4=60):
""" 指数平均线 EXPMA"""
CLOSE = DataFrame.close
MA1 = EMA(CLOSE, P1)
MA2 = EMA(CLOSE, P2)
MA3 = EMA(CLOSE, P3)
MA4 = EMA(CLOSE, P4)
return pd.DataFrame({
'MA1': MA1, 'MA2': MA2, 'MA3': MA3, 'MA4': MA4
}) | def QA_indicator_EXPMA(DataFrame, P1=5, P2=10, P3=20, P4=60):
""" 指数平均线 EXPMA"""
CLOSE = DataFrame.close
MA1 = EMA(CLOSE, P1)
MA2 = EMA(CLOSE, P2)
MA3 = EMA(CLOSE, P3)
MA4 = EMA(CLOSE, P4)
return pd.DataFrame({
'MA1': MA1, 'MA2': MA2, 'MA3': MA3, 'MA4': MA4
}) | [
"指数平均线",
"EXPMA"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L158-L167 | [
"def",
"QA_indicator_EXPMA",
"(",
"DataFrame",
",",
"P1",
"=",
"5",
",",
"P2",
"=",
"10",
",",
"P3",
"=",
"20",
",",
"P4",
"=",
"60",
")",
":",
"CLOSE",
"=",
"DataFrame",
".",
"close",
"MA1",
"=",
"EMA",
"(",
"CLOSE",
",",
"P1",
")",
"MA2",
"="... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_CHO | 佳庆指标 CHO | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_CHO(DataFrame, N1=10, N2=20, M=6):
"""
佳庆指标 CHO
"""
HIGH = DataFrame.high
LOW = DataFrame.low
CLOSE = DataFrame.close
VOL = DataFrame.volume
MID = SUM(VOL*(2*CLOSE-HIGH-LOW)/(HIGH+LOW), 0)
CHO = MA(MID, N1)-MA(MID, N2)
MACHO = MA(CHO, M)
return pd.DataFrame({
'CHO': CHO, 'MACHO': MACHO
}) | def QA_indicator_CHO(DataFrame, N1=10, N2=20, M=6):
"""
佳庆指标 CHO
"""
HIGH = DataFrame.high
LOW = DataFrame.low
CLOSE = DataFrame.close
VOL = DataFrame.volume
MID = SUM(VOL*(2*CLOSE-HIGH-LOW)/(HIGH+LOW), 0)
CHO = MA(MID, N1)-MA(MID, N2)
MACHO = MA(CHO, M)
return pd.DataFrame({
'CHO': CHO, 'MACHO': MACHO
}) | [
"佳庆指标",
"CHO"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L170-L183 | [
"def",
"QA_indicator_CHO",
"(",
"DataFrame",
",",
"N1",
"=",
"10",
",",
"N2",
"=",
"20",
",",
"M",
"=",
"6",
")",
":",
"HIGH",
"=",
"DataFrame",
".",
"high",
"LOW",
"=",
"DataFrame",
".",
"low",
"CLOSE",
"=",
"DataFrame",
".",
"close",
"VOL",
"=",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_BIAS | 乖离率 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_BIAS(DataFrame, N1, N2, N3):
'乖离率'
CLOSE = DataFrame['close']
BIAS1 = (CLOSE - MA(CLOSE, N1)) / MA(CLOSE, N1) * 100
BIAS2 = (CLOSE - MA(CLOSE, N2)) / MA(CLOSE, N2) * 100
BIAS3 = (CLOSE - MA(CLOSE, N3)) / MA(CLOSE, N3) * 100
DICT = {'BIAS1': BIAS1, 'BIAS2': BIAS2, 'BIAS3': BIAS3}
return pd.DataFrame(DICT) | def QA_indicator_BIAS(DataFrame, N1, N2, N3):
'乖离率'
CLOSE = DataFrame['close']
BIAS1 = (CLOSE - MA(CLOSE, N1)) / MA(CLOSE, N1) * 100
BIAS2 = (CLOSE - MA(CLOSE, N2)) / MA(CLOSE, N2) * 100
BIAS3 = (CLOSE - MA(CLOSE, N3)) / MA(CLOSE, N3) * 100
DICT = {'BIAS1': BIAS1, 'BIAS2': BIAS2, 'BIAS3': BIAS3}
return pd.DataFrame(DICT) | [
"乖离率"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L216-L224 | [
"def",
"QA_indicator_BIAS",
"(",
"DataFrame",
",",
"N1",
",",
"N2",
",",
"N3",
")",
":",
"CLOSE",
"=",
"DataFrame",
"[",
"'close'",
"]",
"BIAS1",
"=",
"(",
"CLOSE",
"-",
"MA",
"(",
"CLOSE",
",",
"N1",
")",
")",
"/",
"MA",
"(",
"CLOSE",
",",
"N1",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_ROC | 变动率指标 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_ROC(DataFrame, N=12, M=6):
'变动率指标'
C = DataFrame['close']
roc = 100 * (C - REF(C, N)) / REF(C, N)
ROCMA = MA(roc, M)
DICT = {'ROC': roc, 'ROCMA': ROCMA}
return pd.DataFrame(DICT) | def QA_indicator_ROC(DataFrame, N=12, M=6):
'变动率指标'
C = DataFrame['close']
roc = 100 * (C - REF(C, N)) / REF(C, N)
ROCMA = MA(roc, M)
DICT = {'ROC': roc, 'ROCMA': ROCMA}
return pd.DataFrame(DICT) | [
"变动率指标"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L227-L234 | [
"def",
"QA_indicator_ROC",
"(",
"DataFrame",
",",
"N",
"=",
"12",
",",
"M",
"=",
"6",
")",
":",
"C",
"=",
"DataFrame",
"[",
"'close'",
"]",
"roc",
"=",
"100",
"*",
"(",
"C",
"-",
"REF",
"(",
"C",
",",
"N",
")",
")",
"/",
"REF",
"(",
"C",
",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_CCI | TYP:=(HIGH+LOW+CLOSE)/3;
CCI:(TYP-MA(TYP,N))/(0.015*AVEDEV(TYP,N)); | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_CCI(DataFrame, N=14):
"""
TYP:=(HIGH+LOW+CLOSE)/3;
CCI:(TYP-MA(TYP,N))/(0.015*AVEDEV(TYP,N));
"""
typ = (DataFrame['high'] + DataFrame['low'] + DataFrame['close']) / 3
cci = ((typ - MA(typ, N)) / (0.015 * AVEDEV(typ, N)))
a = 100
b = -100
return pd.DataFrame({
'CCI': cci, 'a': a, 'b': b
}) | def QA_indicator_CCI(DataFrame, N=14):
"""
TYP:=(HIGH+LOW+CLOSE)/3;
CCI:(TYP-MA(TYP,N))/(0.015*AVEDEV(TYP,N));
"""
typ = (DataFrame['high'] + DataFrame['low'] + DataFrame['close']) / 3
cci = ((typ - MA(typ, N)) / (0.015 * AVEDEV(typ, N)))
a = 100
b = -100
return pd.DataFrame({
'CCI': cci, 'a': a, 'b': b
}) | [
"TYP",
":",
"=",
"(",
"HIGH",
"+",
"LOW",
"+",
"CLOSE",
")",
"/",
"3",
";",
"CCI",
":",
"(",
"TYP",
"-",
"MA",
"(",
"TYP",
"N",
"))",
"/",
"(",
"0",
".",
"015",
"*",
"AVEDEV",
"(",
"TYP",
"N",
"))",
";"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L237-L249 | [
"def",
"QA_indicator_CCI",
"(",
"DataFrame",
",",
"N",
"=",
"14",
")",
":",
"typ",
"=",
"(",
"DataFrame",
"[",
"'high'",
"]",
"+",
"DataFrame",
"[",
"'low'",
"]",
"+",
"DataFrame",
"[",
"'close'",
"]",
")",
"/",
"3",
"cci",
"=",
"(",
"(",
"typ",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_WR | 威廉指标 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_WR(DataFrame, N, N1):
'威廉指标'
HIGH = DataFrame['high']
LOW = DataFrame['low']
CLOSE = DataFrame['close']
WR1 = 100 * (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N))
WR2 = 100 * (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1))
DICT = {'WR1': WR1, 'WR2': WR2}
return pd.DataFrame(DICT) | def QA_indicator_WR(DataFrame, N, N1):
'威廉指标'
HIGH = DataFrame['high']
LOW = DataFrame['low']
CLOSE = DataFrame['close']
WR1 = 100 * (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N))
WR2 = 100 * (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1))
DICT = {'WR1': WR1, 'WR2': WR2}
return pd.DataFrame(DICT) | [
"威廉指标"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L252-L261 | [
"def",
"QA_indicator_WR",
"(",
"DataFrame",
",",
"N",
",",
"N1",
")",
":",
"HIGH",
"=",
"DataFrame",
"[",
"'high'",
"]",
"LOW",
"=",
"DataFrame",
"[",
"'low'",
"]",
"CLOSE",
"=",
"DataFrame",
"[",
"'close'",
"]",
"WR1",
"=",
"100",
"*",
"(",
"HHV",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_OSC | 变动速率线
震荡量指标OSC,也叫变动速率线。属于超买超卖类指标,是从移动平均线原理派生出来的一种分析指标。
它反应当日收盘价与一段时间内平均收盘价的差离值,从而测出股价的震荡幅度。
按照移动平均线原理,根据OSC的值可推断价格的趋势,如果远离平均线,就很可能向平均线回归。 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_OSC(DataFrame, N=20, M=6):
"""变动速率线
震荡量指标OSC,也叫变动速率线。属于超买超卖类指标,是从移动平均线原理派生出来的一种分析指标。
它反应当日收盘价与一段时间内平均收盘价的差离值,从而测出股价的震荡幅度。
按照移动平均线原理,根据OSC的值可推断价格的趋势,如果远离平均线,就很可能向平均线回归。
"""
C = DataFrame['close']
OS = (C - MA(C, N)) * 100
MAOSC = EMA(OS, M)
DICT = {'OSC': OS, 'MAOSC': MAOSC}
return pd.DataFrame(DICT) | def QA_indicator_OSC(DataFrame, N=20, M=6):
"""变动速率线
震荡量指标OSC,也叫变动速率线。属于超买超卖类指标,是从移动平均线原理派生出来的一种分析指标。
它反应当日收盘价与一段时间内平均收盘价的差离值,从而测出股价的震荡幅度。
按照移动平均线原理,根据OSC的值可推断价格的趋势,如果远离平均线,就很可能向平均线回归。
"""
C = DataFrame['close']
OS = (C - MA(C, N)) * 100
MAOSC = EMA(OS, M)
DICT = {'OSC': OS, 'MAOSC': MAOSC}
return pd.DataFrame(DICT) | [
"变动速率线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L264-L278 | [
"def",
"QA_indicator_OSC",
"(",
"DataFrame",
",",
"N",
"=",
"20",
",",
"M",
"=",
"6",
")",
":",
"C",
"=",
"DataFrame",
"[",
"'close'",
"]",
"OS",
"=",
"(",
"C",
"-",
"MA",
"(",
"C",
",",
"N",
")",
")",
"*",
"100",
"MAOSC",
"=",
"EMA",
"(",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_RSI | 相对强弱指标RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100; | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_RSI(DataFrame, N1=12, N2=26, N3=9):
'相对强弱指标RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;'
CLOSE = DataFrame['close']
LC = REF(CLOSE, 1)
RSI1 = SMA(MAX(CLOSE - LC, 0), N1) / SMA(ABS(CLOSE - LC), N1) * 100
RSI2 = SMA(MAX(CLOSE - LC, 0), N2) / SMA(ABS(CLOSE - LC), N2) * 100
RSI3 = SMA(MAX(CLOSE - LC, 0), N3) / SMA(ABS(CLOSE - LC), N3) * 100
DICT = {'RSI1': RSI1, 'RSI2': RSI2, 'RSI3': RSI3}
return pd.DataFrame(DICT) | def QA_indicator_RSI(DataFrame, N1=12, N2=26, N3=9):
'相对强弱指标RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;'
CLOSE = DataFrame['close']
LC = REF(CLOSE, 1)
RSI1 = SMA(MAX(CLOSE - LC, 0), N1) / SMA(ABS(CLOSE - LC), N1) * 100
RSI2 = SMA(MAX(CLOSE - LC, 0), N2) / SMA(ABS(CLOSE - LC), N2) * 100
RSI3 = SMA(MAX(CLOSE - LC, 0), N3) / SMA(ABS(CLOSE - LC), N3) * 100
DICT = {'RSI1': RSI1, 'RSI2': RSI2, 'RSI3': RSI3}
return pd.DataFrame(DICT) | [
"相对强弱指标RSI1",
":",
"SMA",
"(",
"MAX",
"(",
"CLOSE",
"-",
"LC",
"0",
")",
"N1",
"1",
")",
"/",
"SMA",
"(",
"ABS",
"(",
"CLOSE",
"-",
"LC",
")",
"N1",
"1",
")",
"*",
"100",
";"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L281-L290 | [
"def",
"QA_indicator_RSI",
"(",
"DataFrame",
",",
"N1",
"=",
"12",
",",
"N2",
"=",
"26",
",",
"N3",
"=",
"9",
")",
":",
"CLOSE",
"=",
"DataFrame",
"[",
"'close'",
"]",
"LC",
"=",
"REF",
"(",
"CLOSE",
",",
"1",
")",
"RSI1",
"=",
"SMA",
"(",
"MAX... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_ADTM | 动态买卖气指标 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_ADTM(DataFrame, N=23, M=8):
'动态买卖气指标'
HIGH = DataFrame.high
LOW = DataFrame.low
OPEN = DataFrame.open
DTM = IF(OPEN > REF(OPEN, 1), MAX((HIGH - OPEN), (OPEN - REF(OPEN, 1))), 0)
DBM = IF(OPEN < REF(OPEN, 1), MAX((OPEN - LOW), (OPEN - REF(OPEN, 1))), 0)
STM = SUM(DTM, N)
SBM = SUM(DBM, N)
ADTM1 = IF(STM > SBM, (STM - SBM) / STM,
IF(STM != SBM, (STM - SBM) / SBM, 0))
MAADTM = MA(ADTM1, M)
DICT = {'ADTM': ADTM1, 'MAADTM': MAADTM}
return pd.DataFrame(DICT) | def QA_indicator_ADTM(DataFrame, N=23, M=8):
'动态买卖气指标'
HIGH = DataFrame.high
LOW = DataFrame.low
OPEN = DataFrame.open
DTM = IF(OPEN > REF(OPEN, 1), MAX((HIGH - OPEN), (OPEN - REF(OPEN, 1))), 0)
DBM = IF(OPEN < REF(OPEN, 1), MAX((OPEN - LOW), (OPEN - REF(OPEN, 1))), 0)
STM = SUM(DTM, N)
SBM = SUM(DBM, N)
ADTM1 = IF(STM > SBM, (STM - SBM) / STM,
IF(STM != SBM, (STM - SBM) / SBM, 0))
MAADTM = MA(ADTM1, M)
DICT = {'ADTM': ADTM1, 'MAADTM': MAADTM}
return pd.DataFrame(DICT) | [
"动态买卖气指标"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L293-L307 | [
"def",
"QA_indicator_ADTM",
"(",
"DataFrame",
",",
"N",
"=",
"23",
",",
"M",
"=",
"8",
")",
":",
"HIGH",
"=",
"DataFrame",
".",
"high",
"LOW",
"=",
"DataFrame",
".",
"low",
"OPEN",
"=",
"DataFrame",
".",
"open",
"DTM",
"=",
"IF",
"(",
"OPEN",
">",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_ASI | LC=REF(CLOSE,1);
AA=ABS(HIGH-LC);
BB=ABS(LOW-LC);
CC=ABS(HIGH-REF(LOW,1));
DD=ABS(LC-REF(OPEN,1));
R=IF(AA>BB AND AA>CC,AA+BB/2+DD/4,IF(BB>CC AND BB>AA,BB+AA/2+DD/4,CC+DD/4));
X=(CLOSE-LC+(CLOSE-OPEN)/2+LC-REF(OPEN,1));
SI=16*X/R*MAX(AA,BB);
ASI:SUM(SI,M1);
ASIT:MA(ASI,M2); | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_ASI(DataFrame, M1=26, M2=10):
"""
LC=REF(CLOSE,1);
AA=ABS(HIGH-LC);
BB=ABS(LOW-LC);
CC=ABS(HIGH-REF(LOW,1));
DD=ABS(LC-REF(OPEN,1));
R=IF(AA>BB AND AA>CC,AA+BB/2+DD/4,IF(BB>CC AND BB>AA,BB+AA/2+DD/4,CC+DD/4));
X=(CLOSE-LC+(CLOSE-OPEN)/2+LC-REF(OPEN,1));
SI=16*X/R*MAX(AA,BB);
ASI:SUM(SI,M1);
ASIT:MA(ASI,M2);
"""
CLOSE = DataFrame['close']
HIGH = DataFrame['high']
LOW = DataFrame['low']
OPEN = DataFrame['open']
LC = REF(CLOSE, 1)
AA = ABS(HIGH - LC)
BB = ABS(LOW-LC)
CC = ABS(HIGH - REF(LOW, 1))
DD = ABS(LC - REF(OPEN, 1))
R = IFAND(AA > BB, AA > CC, AA+BB/2+DD/4,
IFAND(BB > CC, BB > AA, BB+AA/2+DD/4, CC+DD/4))
X = (CLOSE - LC + (CLOSE - OPEN) / 2 + LC - REF(OPEN, 1))
SI = 16*X/R*MAX(AA, BB)
ASI = SUM(SI, M1)
ASIT = MA(ASI, M2)
return pd.DataFrame({
'ASI': ASI, 'ASIT': ASIT
}) | def QA_indicator_ASI(DataFrame, M1=26, M2=10):
"""
LC=REF(CLOSE,1);
AA=ABS(HIGH-LC);
BB=ABS(LOW-LC);
CC=ABS(HIGH-REF(LOW,1));
DD=ABS(LC-REF(OPEN,1));
R=IF(AA>BB AND AA>CC,AA+BB/2+DD/4,IF(BB>CC AND BB>AA,BB+AA/2+DD/4,CC+DD/4));
X=(CLOSE-LC+(CLOSE-OPEN)/2+LC-REF(OPEN,1));
SI=16*X/R*MAX(AA,BB);
ASI:SUM(SI,M1);
ASIT:MA(ASI,M2);
"""
CLOSE = DataFrame['close']
HIGH = DataFrame['high']
LOW = DataFrame['low']
OPEN = DataFrame['open']
LC = REF(CLOSE, 1)
AA = ABS(HIGH - LC)
BB = ABS(LOW-LC)
CC = ABS(HIGH - REF(LOW, 1))
DD = ABS(LC - REF(OPEN, 1))
R = IFAND(AA > BB, AA > CC, AA+BB/2+DD/4,
IFAND(BB > CC, BB > AA, BB+AA/2+DD/4, CC+DD/4))
X = (CLOSE - LC + (CLOSE - OPEN) / 2 + LC - REF(OPEN, 1))
SI = 16*X/R*MAX(AA, BB)
ASI = SUM(SI, M1)
ASIT = MA(ASI, M2)
return pd.DataFrame({
'ASI': ASI, 'ASIT': ASIT
}) | [
"LC",
"=",
"REF",
"(",
"CLOSE",
"1",
")",
";",
"AA",
"=",
"ABS",
"(",
"HIGH",
"-",
"LC",
")",
";",
"BB",
"=",
"ABS",
"(",
"LOW",
"-",
"LC",
")",
";",
"CC",
"=",
"ABS",
"(",
"HIGH",
"-",
"REF",
"(",
"LOW",
"1",
"))",
";",
"DD",
"=",
"ABS... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L388-L419 | [
"def",
"QA_indicator_ASI",
"(",
"DataFrame",
",",
"M1",
"=",
"26",
",",
"M2",
"=",
"10",
")",
":",
"CLOSE",
"=",
"DataFrame",
"[",
"'close'",
"]",
"HIGH",
"=",
"DataFrame",
"[",
"'high'",
"]",
"LOW",
"=",
"DataFrame",
"[",
"'low'",
"]",
"OPEN",
"=",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_OBV | 能量潮 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_OBV(DataFrame):
"""能量潮"""
VOL = DataFrame.volume
CLOSE = DataFrame.close
return pd.DataFrame({
'OBV': np.cumsum(IF(CLOSE > REF(CLOSE, 1), VOL, IF(CLOSE < REF(CLOSE, 1), -VOL, 0)))/10000
}) | def QA_indicator_OBV(DataFrame):
"""能量潮"""
VOL = DataFrame.volume
CLOSE = DataFrame.close
return pd.DataFrame({
'OBV': np.cumsum(IF(CLOSE > REF(CLOSE, 1), VOL, IF(CLOSE < REF(CLOSE, 1), -VOL, 0)))/10000
}) | [
"能量潮"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L429-L435 | [
"def",
"QA_indicator_OBV",
"(",
"DataFrame",
")",
":",
"VOL",
"=",
"DataFrame",
".",
"volume",
"CLOSE",
"=",
"DataFrame",
".",
"close",
"return",
"pd",
".",
"DataFrame",
"(",
"{",
"'OBV'",
":",
"np",
".",
"cumsum",
"(",
"IF",
"(",
"CLOSE",
">",
"REF",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_BOLL | 布林线 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_BOLL(DataFrame, N=20, P=2):
'布林线'
C = DataFrame['close']
boll = MA(C, N)
UB = boll + P * STD(C, N)
LB = boll - P * STD(C, N)
DICT = {'BOLL': boll, 'UB': UB, 'LB': LB}
return pd.DataFrame(DICT) | def QA_indicator_BOLL(DataFrame, N=20, P=2):
'布林线'
C = DataFrame['close']
boll = MA(C, N)
UB = boll + P * STD(C, N)
LB = boll - P * STD(C, N)
DICT = {'BOLL': boll, 'UB': UB, 'LB': LB}
return pd.DataFrame(DICT) | [
"布林线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L456-L464 | [
"def",
"QA_indicator_BOLL",
"(",
"DataFrame",
",",
"N",
"=",
"20",
",",
"P",
"=",
"2",
")",
":",
"C",
"=",
"DataFrame",
"[",
"'close'",
"]",
"boll",
"=",
"MA",
"(",
"C",
",",
"N",
")",
"UB",
"=",
"boll",
"+",
"P",
"*",
"STD",
"(",
"C",
",",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_MIKE | MIKE指标
指标说明
MIKE是另外一种形式的路径指标。
买卖原则
1 WEAK-S,MEDIUM-S,STRONG-S三条线代表初级、中级、强力支撑。
2 WEAK-R,MEDIUM-R,STRONG-R三条线代表初级、中级、强力压力。 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_MIKE(DataFrame, N=12):
"""
MIKE指标
指标说明
MIKE是另外一种形式的路径指标。
买卖原则
1 WEAK-S,MEDIUM-S,STRONG-S三条线代表初级、中级、强力支撑。
2 WEAK-R,MEDIUM-R,STRONG-R三条线代表初级、中级、强力压力。
"""
HIGH = DataFrame.high
LOW = DataFrame.low
CLOSE = DataFrame.close
TYP = (HIGH+LOW+CLOSE)/3
LL = LLV(LOW, N)
HH = HHV(HIGH, N)
WR = TYP+(TYP-LL)
MR = TYP+(HH-LL)
SR = 2*HH-LL
WS = TYP-(HH-TYP)
MS = TYP-(HH-LL)
SS = 2*LL-HH
return pd.DataFrame({
'WR': WR, 'MR': MR, 'SR': SR,
'WS': WS, 'MS': MS, 'SS': SS
}) | def QA_indicator_MIKE(DataFrame, N=12):
"""
MIKE指标
指标说明
MIKE是另外一种形式的路径指标。
买卖原则
1 WEAK-S,MEDIUM-S,STRONG-S三条线代表初级、中级、强力支撑。
2 WEAK-R,MEDIUM-R,STRONG-R三条线代表初级、中级、强力压力。
"""
HIGH = DataFrame.high
LOW = DataFrame.low
CLOSE = DataFrame.close
TYP = (HIGH+LOW+CLOSE)/3
LL = LLV(LOW, N)
HH = HHV(HIGH, N)
WR = TYP+(TYP-LL)
MR = TYP+(HH-LL)
SR = 2*HH-LL
WS = TYP-(HH-TYP)
MS = TYP-(HH-LL)
SS = 2*LL-HH
return pd.DataFrame({
'WR': WR, 'MR': MR, 'SR': SR,
'WS': WS, 'MS': MS, 'SS': SS
}) | [
"MIKE指标",
"指标说明",
"MIKE是另外一种形式的路径指标。",
"买卖原则",
"1",
"WEAK",
"-",
"S,MEDIUM",
"-",
"S,STRONG",
"-",
"S三条线代表初级、中级、强力支撑。",
"2",
"WEAK",
"-",
"R,MEDIUM",
"-",
"R,STRONG",
"-",
"R三条线代表初级、中级、强力压力。"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L467-L493 | [
"def",
"QA_indicator_MIKE",
"(",
"DataFrame",
",",
"N",
"=",
"12",
")",
":",
"HIGH",
"=",
"DataFrame",
".",
"high",
"LOW",
"=",
"DataFrame",
".",
"low",
"CLOSE",
"=",
"DataFrame",
".",
"close",
"TYP",
"=",
"(",
"HIGH",
"+",
"LOW",
"+",
"CLOSE",
")",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_BBI | 多空指标 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_BBI(DataFrame, N1=3, N2=6, N3=12, N4=24):
'多空指标'
C = DataFrame['close']
bbi = (MA(C, N1) + MA(C, N2) + MA(C, N3) + MA(C, N4)) / 4
DICT = {'BBI': bbi}
return pd.DataFrame(DICT) | def QA_indicator_BBI(DataFrame, N1=3, N2=6, N3=12, N4=24):
'多空指标'
C = DataFrame['close']
bbi = (MA(C, N1) + MA(C, N2) + MA(C, N3) + MA(C, N4)) / 4
DICT = {'BBI': bbi}
return pd.DataFrame(DICT) | [
"多空指标"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L496-L502 | [
"def",
"QA_indicator_BBI",
"(",
"DataFrame",
",",
"N1",
"=",
"3",
",",
"N2",
"=",
"6",
",",
"N3",
"=",
"12",
",",
"N4",
"=",
"24",
")",
":",
"C",
"=",
"DataFrame",
"[",
"'close'",
"]",
"bbi",
"=",
"(",
"MA",
"(",
"C",
",",
"N1",
")",
"+",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_MFI | 资金指标
TYP := (HIGH + LOW + CLOSE)/3;
V1:=SUM(IF(TYP>REF(TYP,1),TYP*VOL,0),N)/SUM(IF(TYP<REF(TYP,1),TYP*VOL,0),N);
MFI:100-(100/(1+V1));
赋值: (最高价 + 最低价 + 收盘价)/3
V1赋值:如果TYP>1日前的TYP,返回TYP*成交量(手),否则返回0的N日累和/如果TYP<1日前的TYP,返回TYP*成交量(手),否则返回0的N日累和
输出资金流量指标:100-(100/(1+V1)) | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_MFI(DataFrame, N=14):
"""
资金指标
TYP := (HIGH + LOW + CLOSE)/3;
V1:=SUM(IF(TYP>REF(TYP,1),TYP*VOL,0),N)/SUM(IF(TYP<REF(TYP,1),TYP*VOL,0),N);
MFI:100-(100/(1+V1));
赋值: (最高价 + 最低价 + 收盘价)/3
V1赋值:如果TYP>1日前的TYP,返回TYP*成交量(手),否则返回0的N日累和/如果TYP<1日前的TYP,返回TYP*成交量(手),否则返回0的N日累和
输出资金流量指标:100-(100/(1+V1))
"""
C = DataFrame['close']
H = DataFrame['high']
L = DataFrame['low']
VOL = DataFrame['volume']
TYP = (C + H + L) / 3
V1 = SUM(IF(TYP > REF(TYP, 1), TYP * VOL, 0), N) / \
SUM(IF(TYP < REF(TYP, 1), TYP * VOL, 0), N)
mfi = 100 - (100 / (1 + V1))
DICT = {'MFI': mfi}
return pd.DataFrame(DICT) | def QA_indicator_MFI(DataFrame, N=14):
"""
资金指标
TYP := (HIGH + LOW + CLOSE)/3;
V1:=SUM(IF(TYP>REF(TYP,1),TYP*VOL,0),N)/SUM(IF(TYP<REF(TYP,1),TYP*VOL,0),N);
MFI:100-(100/(1+V1));
赋值: (最高价 + 最低价 + 收盘价)/3
V1赋值:如果TYP>1日前的TYP,返回TYP*成交量(手),否则返回0的N日累和/如果TYP<1日前的TYP,返回TYP*成交量(手),否则返回0的N日累和
输出资金流量指标:100-(100/(1+V1))
"""
C = DataFrame['close']
H = DataFrame['high']
L = DataFrame['low']
VOL = DataFrame['volume']
TYP = (C + H + L) / 3
V1 = SUM(IF(TYP > REF(TYP, 1), TYP * VOL, 0), N) / \
SUM(IF(TYP < REF(TYP, 1), TYP * VOL, 0), N)
mfi = 100 - (100 / (1 + V1))
DICT = {'MFI': mfi}
return pd.DataFrame(DICT) | [
"资金指标",
"TYP",
":",
"=",
"(",
"HIGH",
"+",
"LOW",
"+",
"CLOSE",
")",
"/",
"3",
";",
"V1",
":",
"=",
"SUM",
"(",
"IF",
"(",
"TYP",
">",
"REF",
"(",
"TYP",
"1",
")",
"TYP",
"*",
"VOL",
"0",
")",
"N",
")",
"/",
"SUM",
"(",
"IF",
"(",
"TYP<... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L505-L525 | [
"def",
"QA_indicator_MFI",
"(",
"DataFrame",
",",
"N",
"=",
"14",
")",
":",
"C",
"=",
"DataFrame",
"[",
"'close'",
"]",
"H",
"=",
"DataFrame",
"[",
"'high'",
"]",
"L",
"=",
"DataFrame",
"[",
"'low'",
"]",
"VOL",
"=",
"DataFrame",
"[",
"'volume'",
"]"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_ATR | 输出TR:(最高价-最低价)和昨收-最高价的绝对值的较大值和昨收-最低价的绝对值的较大值
输出真实波幅:TR的N日简单移动平均
算法:今日振幅、今日最高与昨收差价、今日最低与昨收差价中的最大值,为真实波幅,求真实波幅的N日移动平均
参数:N 天数,一般取14 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_ATR(DataFrame, N=14):
"""
输出TR:(最高价-最低价)和昨收-最高价的绝对值的较大值和昨收-最低价的绝对值的较大值
输出真实波幅:TR的N日简单移动平均
算法:今日振幅、今日最高与昨收差价、今日最低与昨收差价中的最大值,为真实波幅,求真实波幅的N日移动平均
参数:N 天数,一般取14
"""
C = DataFrame['close']
H = DataFrame['high']
L = DataFrame['low']
TR = MAX(MAX((H - L), ABS(REF(C, 1) - H)), ABS(REF(C, 1) - L))
atr = MA(TR, N)
return pd.DataFrame({'TR': TR, 'ATR': atr}) | def QA_indicator_ATR(DataFrame, N=14):
"""
输出TR:(最高价-最低价)和昨收-最高价的绝对值的较大值和昨收-最低价的绝对值的较大值
输出真实波幅:TR的N日简单移动平均
算法:今日振幅、今日最高与昨收差价、今日最低与昨收差价中的最大值,为真实波幅,求真实波幅的N日移动平均
参数:N 天数,一般取14
"""
C = DataFrame['close']
H = DataFrame['high']
L = DataFrame['low']
TR = MAX(MAX((H - L), ABS(REF(C, 1) - H)), ABS(REF(C, 1) - L))
atr = MA(TR, N)
return pd.DataFrame({'TR': TR, 'ATR': atr}) | [
"输出TR",
":",
"(",
"最高价",
"-",
"最低价",
")",
"和昨收",
"-",
"最高价的绝对值的较大值和昨收",
"-",
"最低价的绝对值的较大值",
"输出真实波幅",
":",
"TR的N日简单移动平均",
"算法:今日振幅、今日最高与昨收差价、今日最低与昨收差价中的最大值,为真实波幅,求真实波幅的N日移动平均"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L528-L542 | [
"def",
"QA_indicator_ATR",
"(",
"DataFrame",
",",
"N",
"=",
"14",
")",
":",
"C",
"=",
"DataFrame",
"[",
"'close'",
"]",
"H",
"=",
"DataFrame",
"[",
"'high'",
"]",
"L",
"=",
"DataFrame",
"[",
"'low'",
"]",
"TR",
"=",
"MAX",
"(",
"MAX",
"(",
"(",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_SKDJ | 1.指标>80 时,回档机率大;指标<20 时,反弹机率大;
2.K在20左右向上交叉D时,视为买进信号参考;
3.K在80左右向下交叉D时,视为卖出信号参考;
4.SKDJ波动于50左右的任何讯号,其作用不大。 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_SKDJ(DataFrame, N=9, M=3):
"""
1.指标>80 时,回档机率大;指标<20 时,反弹机率大;
2.K在20左右向上交叉D时,视为买进信号参考;
3.K在80左右向下交叉D时,视为卖出信号参考;
4.SKDJ波动于50左右的任何讯号,其作用不大。
"""
CLOSE = DataFrame['close']
LOWV = LLV(DataFrame['low'], N)
HIGHV = HHV(DataFrame['high'], N)
RSV = EMA((CLOSE - LOWV) / (HIGHV - LOWV) * 100, M)
K = EMA(RSV, M)
D = MA(K, M)
DICT = {'RSV': RSV, 'SKDJ_K': K, 'SKDJ_D': D}
return pd.DataFrame(DICT) | def QA_indicator_SKDJ(DataFrame, N=9, M=3):
"""
1.指标>80 时,回档机率大;指标<20 时,反弹机率大;
2.K在20左右向上交叉D时,视为买进信号参考;
3.K在80左右向下交叉D时,视为卖出信号参考;
4.SKDJ波动于50左右的任何讯号,其作用不大。
"""
CLOSE = DataFrame['close']
LOWV = LLV(DataFrame['low'], N)
HIGHV = HHV(DataFrame['high'], N)
RSV = EMA((CLOSE - LOWV) / (HIGHV - LOWV) * 100, M)
K = EMA(RSV, M)
D = MA(K, M)
DICT = {'RSV': RSV, 'SKDJ_K': K, 'SKDJ_D': D}
return pd.DataFrame(DICT) | [
"1",
".",
"指标",
">",
"80",
"时,回档机率大;指标<20",
"时,反弹机率大;",
"2",
".",
"K在20左右向上交叉D时,视为买进信号参考;",
"3",
".",
"K在80左右向下交叉D时,视为卖出信号参考;",
"4",
".",
"SKDJ波动于50左右的任何讯号,其作用不大。"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L545-L561 | [
"def",
"QA_indicator_SKDJ",
"(",
"DataFrame",
",",
"N",
"=",
"9",
",",
"M",
"=",
"3",
")",
":",
"CLOSE",
"=",
"DataFrame",
"[",
"'close'",
"]",
"LOWV",
"=",
"LLV",
"(",
"DataFrame",
"[",
"'low'",
"]",
",",
"N",
")",
"HIGHV",
"=",
"HHV",
"(",
"Dat... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_DDI | '方向标准离差指数'
分析DDI柱状线,由红变绿(正变负),卖出信号参考;由绿变红,买入信号参考。 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_DDI(DataFrame, N=13, N1=26, M=1, M1=5):
"""
'方向标准离差指数'
分析DDI柱状线,由红变绿(正变负),卖出信号参考;由绿变红,买入信号参考。
"""
H = DataFrame['high']
L = DataFrame['low']
DMZ = IF((H + L) > (REF(H, 1) + REF(L, 1)),
MAX(ABS(H - REF(H, 1)), ABS(L - REF(L, 1))), 0)
DMF = IF((H + L) < (REF(H, 1) + REF(L, 1)),
MAX(ABS(H - REF(H, 1)), ABS(L - REF(L, 1))), 0)
DIZ = SUM(DMZ, N) / (SUM(DMZ, N) + SUM(DMF, N))
DIF = SUM(DMF, N) / (SUM(DMF, N) + SUM(DMZ, N))
ddi = DIZ - DIF
ADDI = SMA(ddi, N1, M)
AD = MA(ADDI, M1)
DICT = {'DDI': ddi, 'ADDI': ADDI, 'AD': AD}
return pd.DataFrame(DICT) | def QA_indicator_DDI(DataFrame, N=13, N1=26, M=1, M1=5):
"""
'方向标准离差指数'
分析DDI柱状线,由红变绿(正变负),卖出信号参考;由绿变红,买入信号参考。
"""
H = DataFrame['high']
L = DataFrame['low']
DMZ = IF((H + L) > (REF(H, 1) + REF(L, 1)),
MAX(ABS(H - REF(H, 1)), ABS(L - REF(L, 1))), 0)
DMF = IF((H + L) < (REF(H, 1) + REF(L, 1)),
MAX(ABS(H - REF(H, 1)), ABS(L - REF(L, 1))), 0)
DIZ = SUM(DMZ, N) / (SUM(DMZ, N) + SUM(DMF, N))
DIF = SUM(DMF, N) / (SUM(DMF, N) + SUM(DMZ, N))
ddi = DIZ - DIF
ADDI = SMA(ddi, N1, M)
AD = MA(ADDI, M1)
DICT = {'DDI': ddi, 'ADDI': ADDI, 'AD': AD}
return pd.DataFrame(DICT) | [
"方向标准离差指数",
"分析DDI柱状线,由红变绿",
"(",
"正变负",
")",
",卖出信号参考;由绿变红,买入信号参考。"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L564-L583 | [
"def",
"QA_indicator_DDI",
"(",
"DataFrame",
",",
"N",
"=",
"13",
",",
"N1",
"=",
"26",
",",
"M",
"=",
"1",
",",
"M1",
"=",
"5",
")",
":",
"H",
"=",
"DataFrame",
"[",
"'high'",
"]",
"L",
"=",
"DataFrame",
"[",
"'low'",
"]",
"DMZ",
"=",
"IF",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_indicator_shadow | 上下影线指标 | QUANTAXIS/QAIndicator/indicators.py | def QA_indicator_shadow(DataFrame):
"""
上下影线指标
"""
return {
'LOW': lower_shadow(DataFrame), 'UP': upper_shadow(DataFrame),
'BODY': body(DataFrame), 'BODY_ABS': body_abs(DataFrame), 'PRICE_PCG': price_pcg(DataFrame)
} | def QA_indicator_shadow(DataFrame):
"""
上下影线指标
"""
return {
'LOW': lower_shadow(DataFrame), 'UP': upper_shadow(DataFrame),
'BODY': body(DataFrame), 'BODY_ABS': body_abs(DataFrame), 'PRICE_PCG': price_pcg(DataFrame)
} | [
"上下影线指标"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L586-L593 | [
"def",
"QA_indicator_shadow",
"(",
"DataFrame",
")",
":",
"return",
"{",
"'LOW'",
":",
"lower_shadow",
"(",
"DataFrame",
")",
",",
"'UP'",
":",
"upper_shadow",
"(",
"DataFrame",
")",
",",
"'BODY'",
":",
"body",
"(",
"DataFrame",
")",
",",
"'BODY_ABS'",
":"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | RSanalysis.run | :type series: List
:type exponent: int
:rtype: float | QUANTAXIS/QAIndicator/hurst.py | def run(self, series, exponent=None):
'''
:type series: List
:type exponent: int
:rtype: float
'''
try:
return self.calculateHurst(series, exponent)
except Exception as e:
print(" Error: %s" % e) | def run(self, series, exponent=None):
'''
:type series: List
:type exponent: int
:rtype: float
'''
try:
return self.calculateHurst(series, exponent)
except Exception as e:
print(" Error: %s" % e) | [
":",
"type",
"series",
":",
"List",
":",
"type",
"exponent",
":",
"int",
":",
"rtype",
":",
"float"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/hurst.py#L15-L24 | [
"def",
"run",
"(",
"self",
",",
"series",
",",
"exponent",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"calculateHurst",
"(",
"series",
",",
"exponent",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\" Error: %s\"",
"%",
"e... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | RSanalysis.bestExponent | :type seriesLenght: int
:rtype: int | QUANTAXIS/QAIndicator/hurst.py | def bestExponent(self, seriesLenght):
'''
:type seriesLenght: int
:rtype: int
'''
i = 0
cont = True
while(cont):
if(int(seriesLenght/int(math.pow(2, i))) <= 1):
cont = False
else:
i += 1
return int(i-1) | def bestExponent(self, seriesLenght):
'''
:type seriesLenght: int
:rtype: int
'''
i = 0
cont = True
while(cont):
if(int(seriesLenght/int(math.pow(2, i))) <= 1):
cont = False
else:
i += 1
return int(i-1) | [
":",
"type",
"seriesLenght",
":",
"int",
":",
"rtype",
":",
"int"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/hurst.py#L26-L38 | [
"def",
"bestExponent",
"(",
"self",
",",
"seriesLenght",
")",
":",
"i",
"=",
"0",
"cont",
"=",
"True",
"while",
"(",
"cont",
")",
":",
"if",
"(",
"int",
"(",
"seriesLenght",
"/",
"int",
"(",
"math",
".",
"pow",
"(",
"2",
",",
"i",
")",
")",
")"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | RSanalysis.mean | :type start: int
:type limit: int
:rtype: float | QUANTAXIS/QAIndicator/hurst.py | def mean(self, series, start, limit):
'''
:type start: int
:type limit: int
:rtype: float
'''
return float(np.mean(series[start:limit])) | def mean(self, series, start, limit):
'''
:type start: int
:type limit: int
:rtype: float
'''
return float(np.mean(series[start:limit])) | [
":",
"type",
"start",
":",
"int",
":",
"type",
"limit",
":",
"int",
":",
"rtype",
":",
"float"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/hurst.py#L40-L46 | [
"def",
"mean",
"(",
"self",
",",
"series",
",",
"start",
",",
"limit",
")",
":",
"return",
"float",
"(",
"np",
".",
"mean",
"(",
"series",
"[",
"start",
":",
"limit",
"]",
")",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | RSanalysis.deviation | :type start: int
:type limit: int
:type mean: int
:rtype: list() | QUANTAXIS/QAIndicator/hurst.py | def deviation(self, series, start, limit, mean):
'''
:type start: int
:type limit: int
:type mean: int
:rtype: list()
'''
d = []
for x in range(start, limit):
d.append(float(series[x] - mean))
return d | def deviation(self, series, start, limit, mean):
'''
:type start: int
:type limit: int
:type mean: int
:rtype: list()
'''
d = []
for x in range(start, limit):
d.append(float(series[x] - mean))
return d | [
":",
"type",
"start",
":",
"int",
":",
"type",
"limit",
":",
"int",
":",
"type",
"mean",
":",
"int",
":",
"rtype",
":",
"list",
"()"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/hurst.py#L55-L65 | [
"def",
"deviation",
"(",
"self",
",",
"series",
",",
"start",
",",
"limit",
",",
"mean",
")",
":",
"d",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"start",
",",
"limit",
")",
":",
"d",
".",
"append",
"(",
"float",
"(",
"series",
"[",
"x",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | RSanalysis.standartDeviation | :type start: int
:type limit: int
:rtype: float | QUANTAXIS/QAIndicator/hurst.py | def standartDeviation(self, series, start, limit):
'''
:type start: int
:type limit: int
:rtype: float
'''
return float(np.std(series[start:limit])) | def standartDeviation(self, series, start, limit):
'''
:type start: int
:type limit: int
:rtype: float
'''
return float(np.std(series[start:limit])) | [
":",
"type",
"start",
":",
"int",
":",
"type",
"limit",
":",
"int",
":",
"rtype",
":",
"float"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/hurst.py#L67-L73 | [
"def",
"standartDeviation",
"(",
"self",
",",
"series",
",",
"start",
",",
"limit",
")",
":",
"return",
"float",
"(",
"np",
".",
"std",
"(",
"series",
"[",
"start",
":",
"limit",
"]",
")",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | RSanalysis.calculateHurst | :type series: List
:type exponent: int
:rtype: float | QUANTAXIS/QAIndicator/hurst.py | def calculateHurst(self, series, exponent=None):
'''
:type series: List
:type exponent: int
:rtype: float
'''
rescaledRange = list()
sizeRange = list()
rescaledRangeMean = list()
if(exponent is None):
exponent = self.bestExponent(len(series))
for i in range(0, exponent):
partsNumber = int(math.pow(2, i))
size = int(len(series)/partsNumber)
sizeRange.append(size)
rescaledRange.append(0)
rescaledRangeMean.append(0)
for x in range(0, partsNumber):
start = int(size*(x))
limit = int(size*(x+1))
deviationAcumulative = self.sumDeviation(self.deviation(
series, start, limit, self.mean(series, start, limit)))
deviationsDifference = float(
max(deviationAcumulative) - min(deviationAcumulative))
standartDeviation = self.standartDeviation(
series, start, limit)
if(deviationsDifference != 0 and standartDeviation != 0):
rescaledRange[i] += (deviationsDifference /
standartDeviation)
y = 0
for x in rescaledRange:
rescaledRangeMean[y] = x/int(math.pow(2, y))
y = y+1
# log calculation
rescaledRangeLog = list()
sizeRangeLog = list()
for i in range(0, exponent):
rescaledRangeLog.append(math.log(rescaledRangeMean[i], 10))
sizeRangeLog.append(math.log(sizeRange[i], 10))
slope, intercept = np.polyfit(sizeRangeLog, rescaledRangeLog, 1)
ablineValues = [slope * i + intercept for i in sizeRangeLog]
plt.plot(sizeRangeLog, rescaledRangeLog, '--')
plt.plot(sizeRangeLog, ablineValues, 'b')
plt.title(slope)
# graphic dimension settings
limitUp = 0
if(max(sizeRangeLog) > max(rescaledRangeLog)):
limitUp = max(sizeRangeLog)
else:
limitUp = max(rescaledRangeLog)
limitDown = 0
if(min(sizeRangeLog) > min(rescaledRangeLog)):
limitDown = min(rescaledRangeLog)
else:
limitDown = min(sizeRangeLog)
plt.gca().set_xlim(limitDown, limitUp)
plt.gca().set_ylim(limitDown, limitUp)
print("Hurst exponent: " + str(slope))
plt.show()
return slope | def calculateHurst(self, series, exponent=None):
'''
:type series: List
:type exponent: int
:rtype: float
'''
rescaledRange = list()
sizeRange = list()
rescaledRangeMean = list()
if(exponent is None):
exponent = self.bestExponent(len(series))
for i in range(0, exponent):
partsNumber = int(math.pow(2, i))
size = int(len(series)/partsNumber)
sizeRange.append(size)
rescaledRange.append(0)
rescaledRangeMean.append(0)
for x in range(0, partsNumber):
start = int(size*(x))
limit = int(size*(x+1))
deviationAcumulative = self.sumDeviation(self.deviation(
series, start, limit, self.mean(series, start, limit)))
deviationsDifference = float(
max(deviationAcumulative) - min(deviationAcumulative))
standartDeviation = self.standartDeviation(
series, start, limit)
if(deviationsDifference != 0 and standartDeviation != 0):
rescaledRange[i] += (deviationsDifference /
standartDeviation)
y = 0
for x in rescaledRange:
rescaledRangeMean[y] = x/int(math.pow(2, y))
y = y+1
# log calculation
rescaledRangeLog = list()
sizeRangeLog = list()
for i in range(0, exponent):
rescaledRangeLog.append(math.log(rescaledRangeMean[i], 10))
sizeRangeLog.append(math.log(sizeRange[i], 10))
slope, intercept = np.polyfit(sizeRangeLog, rescaledRangeLog, 1)
ablineValues = [slope * i + intercept for i in sizeRangeLog]
plt.plot(sizeRangeLog, rescaledRangeLog, '--')
plt.plot(sizeRangeLog, ablineValues, 'b')
plt.title(slope)
# graphic dimension settings
limitUp = 0
if(max(sizeRangeLog) > max(rescaledRangeLog)):
limitUp = max(sizeRangeLog)
else:
limitUp = max(rescaledRangeLog)
limitDown = 0
if(min(sizeRangeLog) > min(rescaledRangeLog)):
limitDown = min(rescaledRangeLog)
else:
limitDown = min(sizeRangeLog)
plt.gca().set_xlim(limitDown, limitUp)
plt.gca().set_ylim(limitDown, limitUp)
print("Hurst exponent: " + str(slope))
plt.show()
return slope | [
":",
"type",
"series",
":",
"List",
":",
"type",
"exponent",
":",
"int",
":",
"rtype",
":",
"float"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/hurst.py#L75-L146 | [
"def",
"calculateHurst",
"(",
"self",
",",
"series",
",",
"exponent",
"=",
"None",
")",
":",
"rescaledRange",
"=",
"list",
"(",
")",
"sizeRange",
"=",
"list",
"(",
")",
"rescaledRangeMean",
"=",
"list",
"(",
")",
"if",
"(",
"exponent",
"is",
"None",
")... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_send_mail | 邮件发送
Arguments:
msg {[type]} -- [description]
title {[type]} -- [description]
from_user {[type]} -- [description]
from_password {[type]} -- [description]
to_addr {[type]} -- [description]
smtp {[type]} -- [description] | QUANTAXIS/QAUtil/QAMail.py | def QA_util_send_mail(msg, title, from_user, from_password, to_addr, smtp):
"""邮件发送
Arguments:
msg {[type]} -- [description]
title {[type]} -- [description]
from_user {[type]} -- [description]
from_password {[type]} -- [description]
to_addr {[type]} -- [description]
smtp {[type]} -- [description]
"""
msg = MIMEText(msg, 'plain', 'utf-8')
msg['Subject'] = Header(title, 'utf-8').encode()
server = smtplib.SMTP(smtp, 25) # SMTP协议默认端口是25
server.set_debuglevel(1)
server.login(from_user, from_password)
server.sendmail(from_user, [to_addr], msg.as_string()) | def QA_util_send_mail(msg, title, from_user, from_password, to_addr, smtp):
"""邮件发送
Arguments:
msg {[type]} -- [description]
title {[type]} -- [description]
from_user {[type]} -- [description]
from_password {[type]} -- [description]
to_addr {[type]} -- [description]
smtp {[type]} -- [description]
"""
msg = MIMEText(msg, 'plain', 'utf-8')
msg['Subject'] = Header(title, 'utf-8').encode()
server = smtplib.SMTP(smtp, 25) # SMTP协议默认端口是25
server.set_debuglevel(1)
server.login(from_user, from_password)
server.sendmail(from_user, [to_addr], msg.as_string()) | [
"邮件发送",
"Arguments",
":",
"msg",
"{",
"[",
"type",
"]",
"}",
"--",
"[",
"description",
"]",
"title",
"{",
"[",
"type",
"]",
"}",
"--",
"[",
"description",
"]",
"from_user",
"{",
"[",
"type",
"]",
"}",
"--",
"[",
"description",
"]",
"from_password",
... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QAMail.py#L32-L50 | [
"def",
"QA_util_send_mail",
"(",
"msg",
",",
"title",
",",
"from_user",
",",
"from_password",
",",
"to_addr",
",",
"smtp",
")",
":",
"msg",
"=",
"MIMEText",
"(",
"msg",
",",
"'plain'",
",",
"'utf-8'",
")",
"msg",
"[",
"'Subject'",
"]",
"=",
"Header",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_stock_analysis | 'zyfw', 主营范围 'jyps'#经营评述 'zygcfx' 主营构成分析
date 主营构成 主营收入(元) 收入比例cbbl 主营成本(元) 成本比例 主营利润(元) 利润比例 毛利率(%)
行业 /产品/ 区域 hq cp qy | QUANTAXIS/QAFetch/QAEastMoney.py | def QA_fetch_get_stock_analysis(code):
"""
'zyfw', 主营范围 'jyps'#经营评述 'zygcfx' 主营构成分析
date 主营构成 主营收入(元) 收入比例cbbl 主营成本(元) 成本比例 主营利润(元) 利润比例 毛利率(%)
行业 /产品/ 区域 hq cp qy
"""
market = 'sh' if _select_market_code(code) == 1 else 'sz'
null = 'none'
data = eval(requests.get(BusinessAnalysis_url.format(
market, code), headers=headers_em).text)
zyfw = pd.DataFrame(data.get('zyfw', None))
jyps = pd.DataFrame(data.get('jyps', None))
zygcfx = data.get('zygcfx', [])
temp = []
for item in zygcfx:
try:
data_ = pd.concat([pd.DataFrame(item['hy']).assign(date=item['rq']).assign(classify='hy'),
pd.DataFrame(item['cp']).assign(
date=item['rq']).assign(classify='cp'),
pd.DataFrame(item['qy']).assign(date=item['rq']).assign(classify='qy')])
temp.append(data_)
except:
pass
try:
res_zyfcfx = pd.concat(temp).set_index(
['date', 'classify'], drop=False)
except:
res_zyfcfx = None
return zyfw, jyps, res_zyfcfx | def QA_fetch_get_stock_analysis(code):
"""
'zyfw', 主营范围 'jyps'#经营评述 'zygcfx' 主营构成分析
date 主营构成 主营收入(元) 收入比例cbbl 主营成本(元) 成本比例 主营利润(元) 利润比例 毛利率(%)
行业 /产品/ 区域 hq cp qy
"""
market = 'sh' if _select_market_code(code) == 1 else 'sz'
null = 'none'
data = eval(requests.get(BusinessAnalysis_url.format(
market, code), headers=headers_em).text)
zyfw = pd.DataFrame(data.get('zyfw', None))
jyps = pd.DataFrame(data.get('jyps', None))
zygcfx = data.get('zygcfx', [])
temp = []
for item in zygcfx:
try:
data_ = pd.concat([pd.DataFrame(item['hy']).assign(date=item['rq']).assign(classify='hy'),
pd.DataFrame(item['cp']).assign(
date=item['rq']).assign(classify='cp'),
pd.DataFrame(item['qy']).assign(date=item['rq']).assign(classify='qy')])
temp.append(data_)
except:
pass
try:
res_zyfcfx = pd.concat(temp).set_index(
['date', 'classify'], drop=False)
except:
res_zyfcfx = None
return zyfw, jyps, res_zyfcfx | [
"zyfw",
"主营范围",
"jyps",
"#经营评述",
"zygcfx",
"主营构成分析"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAEastMoney.py#L35-L66 | [
"def",
"QA_fetch_get_stock_analysis",
"(",
"code",
")",
":",
"market",
"=",
"'sh'",
"if",
"_select_market_code",
"(",
"code",
")",
"==",
"1",
"else",
"'sz'",
"null",
"=",
"'none'",
"data",
"=",
"eval",
"(",
"requests",
".",
"get",
"(",
"BusinessAnalysis_url"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_TTSBroker.send_order | 下单
Arguments:
code {[type]} -- [description]
price {[type]} -- [description]
amount {[type]} -- [description]
towards {[type]} -- [description]
order_model {[type]} -- [description]
market:市场,SZ 深交所,SH 上交所
Returns:
[type] -- [description] | QUANTAXIS/QAMarket/QATTSBroker.py | def send_order(self, code, price, amount, towards, order_model, market=None):
"""下单
Arguments:
code {[type]} -- [description]
price {[type]} -- [description]
amount {[type]} -- [description]
towards {[type]} -- [description]
order_model {[type]} -- [description]
market:市场,SZ 深交所,SH 上交所
Returns:
[type] -- [description]
"""
towards = 0 if towards == ORDER_DIRECTION.BUY else 1
if order_model == ORDER_MODEL.MARKET:
order_model = 4
elif order_model == ORDER_MODEL.LIMIT:
order_model = 0
if market is None:
market = QAFetch.base.get_stock_market(code)
if not isinstance(market, str):
raise Exception('%s不正确,请检查code和market参数' % market)
market = market.lower()
if market not in ['sh', 'sz']:
raise Exception('%s不支持,请检查code和market参数' % market)
return self.data_to_df(self.call("send_order", {
'client_id': self.client_id,
'category': towards,
'price_type': order_model,
'gddm': self.gddm_sh if market == 'sh' else self.gddm_sz,
'zqdm': code,
'price': price,
'quantity': amount
})) | def send_order(self, code, price, amount, towards, order_model, market=None):
"""下单
Arguments:
code {[type]} -- [description]
price {[type]} -- [description]
amount {[type]} -- [description]
towards {[type]} -- [description]
order_model {[type]} -- [description]
market:市场,SZ 深交所,SH 上交所
Returns:
[type] -- [description]
"""
towards = 0 if towards == ORDER_DIRECTION.BUY else 1
if order_model == ORDER_MODEL.MARKET:
order_model = 4
elif order_model == ORDER_MODEL.LIMIT:
order_model = 0
if market is None:
market = QAFetch.base.get_stock_market(code)
if not isinstance(market, str):
raise Exception('%s不正确,请检查code和market参数' % market)
market = market.lower()
if market not in ['sh', 'sz']:
raise Exception('%s不支持,请检查code和market参数' % market)
return self.data_to_df(self.call("send_order", {
'client_id': self.client_id,
'category': towards,
'price_type': order_model,
'gddm': self.gddm_sh if market == 'sh' else self.gddm_sz,
'zqdm': code,
'price': price,
'quantity': amount
})) | [
"下单"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QATTSBroker.py#L255-L292 | [
"def",
"send_order",
"(",
"self",
",",
"code",
",",
"price",
",",
"amount",
",",
"towards",
",",
"order_model",
",",
"market",
"=",
"None",
")",
":",
"towards",
"=",
"0",
"if",
"towards",
"==",
"ORDER_DIRECTION",
".",
"BUY",
"else",
"1",
"if",
"order_m... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_getBetweenMonth | #返回所有月份,以及每月的起始日期、结束日期,字典格式 | QUANTAXIS/QAUtil/QADateTools.py | def QA_util_getBetweenMonth(from_date, to_date):
"""
#返回所有月份,以及每月的起始日期、结束日期,字典格式
"""
date_list = {}
begin_date = datetime.datetime.strptime(from_date, "%Y-%m-%d")
end_date = datetime.datetime.strptime(to_date, "%Y-%m-%d")
while begin_date <= end_date:
date_str = begin_date.strftime("%Y-%m")
date_list[date_str] = ['%d-%d-01' % (begin_date.year, begin_date.month),
'%d-%d-%d' % (begin_date.year, begin_date.month,
calendar.monthrange(begin_date.year, begin_date.month)[1])]
begin_date = QA_util_get_1st_of_next_month(begin_date)
return(date_list) | def QA_util_getBetweenMonth(from_date, to_date):
"""
#返回所有月份,以及每月的起始日期、结束日期,字典格式
"""
date_list = {}
begin_date = datetime.datetime.strptime(from_date, "%Y-%m-%d")
end_date = datetime.datetime.strptime(to_date, "%Y-%m-%d")
while begin_date <= end_date:
date_str = begin_date.strftime("%Y-%m")
date_list[date_str] = ['%d-%d-01' % (begin_date.year, begin_date.month),
'%d-%d-%d' % (begin_date.year, begin_date.month,
calendar.monthrange(begin_date.year, begin_date.month)[1])]
begin_date = QA_util_get_1st_of_next_month(begin_date)
return(date_list) | [
"#返回所有月份,以及每月的起始日期、结束日期,字典格式"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADateTools.py#L6-L19 | [
"def",
"QA_util_getBetweenMonth",
"(",
"from_date",
",",
"to_date",
")",
":",
"date_list",
"=",
"{",
"}",
"begin_date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"from_date",
",",
"\"%Y-%m-%d\"",
")",
"end_date",
"=",
"datetime",
".",
"datetime",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_add_months | #返回dt隔months个月后的日期,months相当于步长 | QUANTAXIS/QAUtil/QADateTools.py | def QA_util_add_months(dt, months):
"""
#返回dt隔months个月后的日期,months相当于步长
"""
dt = datetime.datetime.strptime(
dt, "%Y-%m-%d") + relativedelta(months=months)
return(dt) | def QA_util_add_months(dt, months):
"""
#返回dt隔months个月后的日期,months相当于步长
"""
dt = datetime.datetime.strptime(
dt, "%Y-%m-%d") + relativedelta(months=months)
return(dt) | [
"#返回dt隔months个月后的日期,months相当于步长"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADateTools.py#L22-L28 | [
"def",
"QA_util_add_months",
"(",
"dt",
",",
"months",
")",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"dt",
",",
"\"%Y-%m-%d\"",
")",
"+",
"relativedelta",
"(",
"months",
"=",
"months",
")",
"return",
"(",
"dt",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_get_1st_of_next_month | 获取下个月第一天的日期
:return: 返回日期 | QUANTAXIS/QAUtil/QADateTools.py | def QA_util_get_1st_of_next_month(dt):
"""
获取下个月第一天的日期
:return: 返回日期
"""
year = dt.year
month = dt.month
if month == 12:
month = 1
year += 1
else:
month += 1
res = datetime.datetime(year, month, 1)
return res | def QA_util_get_1st_of_next_month(dt):
"""
获取下个月第一天的日期
:return: 返回日期
"""
year = dt.year
month = dt.month
if month == 12:
month = 1
year += 1
else:
month += 1
res = datetime.datetime(year, month, 1)
return res | [
"获取下个月第一天的日期",
":",
"return",
":",
"返回日期"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADateTools.py#L31-L44 | [
"def",
"QA_util_get_1st_of_next_month",
"(",
"dt",
")",
":",
"year",
"=",
"dt",
".",
"year",
"month",
"=",
"dt",
".",
"month",
"if",
"month",
"==",
"12",
":",
"month",
"=",
"1",
"year",
"+=",
"1",
"else",
":",
"month",
"+=",
"1",
"res",
"=",
"datet... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_getBetweenQuarter | #加上每季度的起始日期、结束日期 | QUANTAXIS/QAUtil/QADateTools.py | def QA_util_getBetweenQuarter(begin_date, end_date):
"""
#加上每季度的起始日期、结束日期
"""
quarter_list = {}
month_list = QA_util_getBetweenMonth(begin_date, end_date)
for value in month_list:
tempvalue = value.split("-")
year = tempvalue[0]
if tempvalue[1] in ['01', '02', '03']:
quarter_list[year + "Q1"] = ['%s-01-01' % year, '%s-03-31' % year]
elif tempvalue[1] in ['04', '05', '06']:
quarter_list[year + "Q2"] = ['%s-04-01' % year, '%s-06-30' % year]
elif tempvalue[1] in ['07', '08', '09']:
quarter_list[year + "Q3"] = ['%s-07-31' % year, '%s-09-30' % year]
elif tempvalue[1] in ['10', '11', '12']:
quarter_list[year + "Q4"] = ['%s-10-01' % year, '%s-12-31' % year]
return(quarter_list) | def QA_util_getBetweenQuarter(begin_date, end_date):
"""
#加上每季度的起始日期、结束日期
"""
quarter_list = {}
month_list = QA_util_getBetweenMonth(begin_date, end_date)
for value in month_list:
tempvalue = value.split("-")
year = tempvalue[0]
if tempvalue[1] in ['01', '02', '03']:
quarter_list[year + "Q1"] = ['%s-01-01' % year, '%s-03-31' % year]
elif tempvalue[1] in ['04', '05', '06']:
quarter_list[year + "Q2"] = ['%s-04-01' % year, '%s-06-30' % year]
elif tempvalue[1] in ['07', '08', '09']:
quarter_list[year + "Q3"] = ['%s-07-31' % year, '%s-09-30' % year]
elif tempvalue[1] in ['10', '11', '12']:
quarter_list[year + "Q4"] = ['%s-10-01' % year, '%s-12-31' % year]
return(quarter_list) | [
"#加上每季度的起始日期、结束日期"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADateTools.py#L47-L64 | [
"def",
"QA_util_getBetweenQuarter",
"(",
"begin_date",
",",
"end_date",
")",
":",
"quarter_list",
"=",
"{",
"}",
"month_list",
"=",
"QA_util_getBetweenMonth",
"(",
"begin_date",
",",
"end_date",
")",
"for",
"value",
"in",
"month_list",
":",
"tempvalue",
"=",
"va... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | save_account | save account
Arguments:
message {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/save_account.py | def save_account(message, collection=DATABASE.account):
"""save account
Arguments:
message {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE})
"""
try:
collection.create_index(
[("account_cookie", ASCENDING), ("user_cookie", ASCENDING), ("portfolio_cookie", ASCENDING)], unique=True)
except:
pass
collection.update(
{'account_cookie': message['account_cookie'], 'portfolio_cookie':
message['portfolio_cookie'], 'user_cookie': message['user_cookie']},
{'$set': message},
upsert=True
) | def save_account(message, collection=DATABASE.account):
"""save account
Arguments:
message {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE})
"""
try:
collection.create_index(
[("account_cookie", ASCENDING), ("user_cookie", ASCENDING), ("portfolio_cookie", ASCENDING)], unique=True)
except:
pass
collection.update(
{'account_cookie': message['account_cookie'], 'portfolio_cookie':
message['portfolio_cookie'], 'user_cookie': message['user_cookie']},
{'$set': message},
upsert=True
) | [
"save",
"account"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_account.py#L32-L51 | [
"def",
"save_account",
"(",
"message",
",",
"collection",
"=",
"DATABASE",
".",
"account",
")",
":",
"try",
":",
"collection",
".",
"create_index",
"(",
"[",
"(",
"\"account_cookie\"",
",",
"ASCENDING",
")",
",",
"(",
"\"user_cookie\"",
",",
"ASCENDING",
")"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_financial_files | 本地存储financialdata | QUANTAXIS/QASU/save_financialfiles.py | def QA_SU_save_financial_files():
"""本地存储financialdata
"""
download_financialzip()
coll = DATABASE.financial
coll.create_index(
[("code", ASCENDING), ("report_date", ASCENDING)], unique=True)
for item in os.listdir(download_path):
if item[0:4] != 'gpcw':
print(
"file ", item, " is not start with gpcw , seems not a financial file , ignore!")
continue
date = int(item.split('.')[0][-8:])
print('QUANTAXIS NOW SAVING {}'.format(date))
if coll.find({'report_date': date}).count() < 3600:
print(coll.find({'report_date': date}).count())
data = QA_util_to_json_from_pandas(parse_filelist([item]).reset_index(
).drop_duplicates(subset=['code', 'report_date']).sort_index())
# data["crawl_date"] = str(datetime.date.today())
try:
coll.insert_many(data, ordered=False)
except Exception as e:
if isinstance(e, MemoryError):
coll.insert_many(data, ordered=True)
elif isinstance(e, pymongo.bulk.BulkWriteError):
pass
else:
print('ALL READY IN DATABASE')
print('SUCCESSFULLY SAVE/UPDATE FINANCIAL DATA') | def QA_SU_save_financial_files():
"""本地存储financialdata
"""
download_financialzip()
coll = DATABASE.financial
coll.create_index(
[("code", ASCENDING), ("report_date", ASCENDING)], unique=True)
for item in os.listdir(download_path):
if item[0:4] != 'gpcw':
print(
"file ", item, " is not start with gpcw , seems not a financial file , ignore!")
continue
date = int(item.split('.')[0][-8:])
print('QUANTAXIS NOW SAVING {}'.format(date))
if coll.find({'report_date': date}).count() < 3600:
print(coll.find({'report_date': date}).count())
data = QA_util_to_json_from_pandas(parse_filelist([item]).reset_index(
).drop_duplicates(subset=['code', 'report_date']).sort_index())
# data["crawl_date"] = str(datetime.date.today())
try:
coll.insert_many(data, ordered=False)
except Exception as e:
if isinstance(e, MemoryError):
coll.insert_many(data, ordered=True)
elif isinstance(e, pymongo.bulk.BulkWriteError):
pass
else:
print('ALL READY IN DATABASE')
print('SUCCESSFULLY SAVE/UPDATE FINANCIAL DATA') | [
"本地存储financialdata"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_financialfiles.py#L39-L71 | [
"def",
"QA_SU_save_financial_files",
"(",
")",
":",
"download_financialzip",
"(",
")",
"coll",
"=",
"DATABASE",
".",
"financial",
"coll",
".",
"create_index",
"(",
"[",
"(",
"\"code\"",
",",
"ASCENDING",
")",
",",
"(",
"\"report_date\"",
",",
"ASCENDING",
")",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_log_info | QUANTAXIS Log Module
@yutiansut
QA_util_log_x is under [QAStandard#0.0.2@602-x] Protocol | QUANTAXIS/QAUtil/QALogs.py | def QA_util_log_info(
logs,
ui_log=None,
ui_progress=None,
ui_progress_int_value=None,
):
"""
QUANTAXIS Log Module
@yutiansut
QA_util_log_x is under [QAStandard#0.0.2@602-x] Protocol
"""
logging.warning(logs)
# 给GUI使用,更新当前任务到日志和进度
if ui_log is not None:
if isinstance(logs, str):
ui_log.emit(logs)
if isinstance(logs, list):
for iStr in logs:
ui_log.emit(iStr)
if ui_progress is not None and ui_progress_int_value is not None:
ui_progress.emit(ui_progress_int_value) | def QA_util_log_info(
logs,
ui_log=None,
ui_progress=None,
ui_progress_int_value=None,
):
"""
QUANTAXIS Log Module
@yutiansut
QA_util_log_x is under [QAStandard#0.0.2@602-x] Protocol
"""
logging.warning(logs)
# 给GUI使用,更新当前任务到日志和进度
if ui_log is not None:
if isinstance(logs, str):
ui_log.emit(logs)
if isinstance(logs, list):
for iStr in logs:
ui_log.emit(iStr)
if ui_progress is not None and ui_progress_int_value is not None:
ui_progress.emit(ui_progress_int_value) | [
"QUANTAXIS",
"Log",
"Module",
"@yutiansut"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QALogs.py#L86-L109 | [
"def",
"QA_util_log_info",
"(",
"logs",
",",
"ui_log",
"=",
"None",
",",
"ui_progress",
"=",
"None",
",",
"ui_progress_int_value",
"=",
"None",
",",
")",
":",
"logging",
".",
"warning",
"(",
"logs",
")",
"# 给GUI使用,更新当前任务到日志和进度",
"if",
"ui_log",
"is",
"not",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_save_tdx_to_mongo | save file
Arguments:
file_dir {str:direction} -- 文件的地址
Keyword Arguments:
client {Mongodb:Connection} -- Mongo Connection (default: {DATABASE}) | QUANTAXIS/QASU/save_tdx_file.py | def QA_save_tdx_to_mongo(file_dir, client=DATABASE):
"""save file
Arguments:
file_dir {str:direction} -- 文件的地址
Keyword Arguments:
client {Mongodb:Connection} -- Mongo Connection (default: {DATABASE})
"""
reader = TdxMinBarReader()
__coll = client.stock_min_five
for a, v, files in os.walk(file_dir):
for file in files:
if (str(file)[0:2] == 'sh' and int(str(file)[2]) == 6) or \
(str(file)[0:2] == 'sz' and int(str(file)[2]) == 0) or \
(str(file)[0:2] == 'sz' and int(str(file)[2]) == 3):
QA_util_log_info('Now_saving ' + str(file)
[2:8] + '\'s 5 min tick')
fname = file_dir + os.sep + file
df = reader.get_df(fname)
df['code'] = str(file)[2:8]
df['market'] = str(file)[0:2]
df['datetime'] = [str(x) for x in list(df.index)]
df['date'] = [str(x)[0:10] for x in list(df.index)]
df['time_stamp'] = df['datetime'].apply(
lambda x: QA_util_time_stamp(x))
df['date_stamp'] = df['date'].apply(
lambda x: QA_util_date_stamp(x))
data_json = json.loads(df.to_json(orient='records'))
__coll.insert_many(data_json) | def QA_save_tdx_to_mongo(file_dir, client=DATABASE):
"""save file
Arguments:
file_dir {str:direction} -- 文件的地址
Keyword Arguments:
client {Mongodb:Connection} -- Mongo Connection (default: {DATABASE})
"""
reader = TdxMinBarReader()
__coll = client.stock_min_five
for a, v, files in os.walk(file_dir):
for file in files:
if (str(file)[0:2] == 'sh' and int(str(file)[2]) == 6) or \
(str(file)[0:2] == 'sz' and int(str(file)[2]) == 0) or \
(str(file)[0:2] == 'sz' and int(str(file)[2]) == 3):
QA_util_log_info('Now_saving ' + str(file)
[2:8] + '\'s 5 min tick')
fname = file_dir + os.sep + file
df = reader.get_df(fname)
df['code'] = str(file)[2:8]
df['market'] = str(file)[0:2]
df['datetime'] = [str(x) for x in list(df.index)]
df['date'] = [str(x)[0:10] for x in list(df.index)]
df['time_stamp'] = df['datetime'].apply(
lambda x: QA_util_time_stamp(x))
df['date_stamp'] = df['date'].apply(
lambda x: QA_util_date_stamp(x))
data_json = json.loads(df.to_json(orient='records'))
__coll.insert_many(data_json) | [
"save",
"file",
"Arguments",
":",
"file_dir",
"{",
"str",
":",
"direction",
"}",
"--",
"文件的地址",
"Keyword",
"Arguments",
":",
"client",
"{",
"Mongodb",
":",
"Connection",
"}",
"--",
"Mongo",
"Connection",
"(",
"default",
":",
"{",
"DATABASE",
"}",
")"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_tdx_file.py#L35-L68 | [
"def",
"QA_save_tdx_to_mongo",
"(",
"file_dir",
",",
"client",
"=",
"DATABASE",
")",
":",
"reader",
"=",
"TdxMinBarReader",
"(",
")",
"__coll",
"=",
"client",
".",
"stock_min_five",
"for",
"a",
",",
"v",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"file_... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | exclude_from_stock_ip_list | 从stock_ip_list删除列表exclude_ip_list中的ip
从stock_ip_list删除列表future_ip_list中的ip
:param exclude_ip_list: 需要删除的ip_list
:return: None | QUANTAXIS/QAUtil/QASetting.py | def exclude_from_stock_ip_list(exclude_ip_list):
""" 从stock_ip_list删除列表exclude_ip_list中的ip
从stock_ip_list删除列表future_ip_list中的ip
:param exclude_ip_list: 需要删除的ip_list
:return: None
"""
for exc in exclude_ip_list:
if exc in stock_ip_list:
stock_ip_list.remove(exc)
# 扩展市场
for exc in exclude_ip_list:
if exc in future_ip_list:
future_ip_list.remove(exc) | def exclude_from_stock_ip_list(exclude_ip_list):
""" 从stock_ip_list删除列表exclude_ip_list中的ip
从stock_ip_list删除列表future_ip_list中的ip
:param exclude_ip_list: 需要删除的ip_list
:return: None
"""
for exc in exclude_ip_list:
if exc in stock_ip_list:
stock_ip_list.remove(exc)
# 扩展市场
for exc in exclude_ip_list:
if exc in future_ip_list:
future_ip_list.remove(exc) | [
"从stock_ip_list删除列表exclude_ip_list中的ip",
"从stock_ip_list删除列表future_ip_list中的ip"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QASetting.py#L209-L223 | [
"def",
"exclude_from_stock_ip_list",
"(",
"exclude_ip_list",
")",
":",
"for",
"exc",
"in",
"exclude_ip_list",
":",
"if",
"exc",
"in",
"stock_ip_list",
":",
"stock_ip_list",
".",
"remove",
"(",
"exc",
")",
"# 扩展市场",
"for",
"exc",
"in",
"exclude_ip_list",
":",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_Setting.get_config | [summary]
Keyword Arguments:
section {str} -- [description] (default: {'MONGODB'})
option {str} -- [description] (default: {'uri'})
default_value {[type]} -- [description] (default: {DEFAULT_DB_URI})
Returns:
[type] -- [description] | QUANTAXIS/QAUtil/QASetting.py | def get_config(
self,
section='MONGODB',
option='uri',
default_value=DEFAULT_DB_URI
):
"""[summary]
Keyword Arguments:
section {str} -- [description] (default: {'MONGODB'})
option {str} -- [description] (default: {'uri'})
default_value {[type]} -- [description] (default: {DEFAULT_DB_URI})
Returns:
[type] -- [description]
"""
res = self.client.quantaxis.usersetting.find_one({'section': section})
if res:
return res.get(option, default_value)
else:
self.set_config(section, option, default_value)
return default_value | def get_config(
self,
section='MONGODB',
option='uri',
default_value=DEFAULT_DB_URI
):
"""[summary]
Keyword Arguments:
section {str} -- [description] (default: {'MONGODB'})
option {str} -- [description] (default: {'uri'})
default_value {[type]} -- [description] (default: {DEFAULT_DB_URI})
Returns:
[type] -- [description]
"""
res = self.client.quantaxis.usersetting.find_one({'section': section})
if res:
return res.get(option, default_value)
else:
self.set_config(section, option, default_value)
return default_value | [
"[",
"summary",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QASetting.py#L78-L101 | [
"def",
"get_config",
"(",
"self",
",",
"section",
"=",
"'MONGODB'",
",",
"option",
"=",
"'uri'",
",",
"default_value",
"=",
"DEFAULT_DB_URI",
")",
":",
"res",
"=",
"self",
".",
"client",
".",
"quantaxis",
".",
"usersetting",
".",
"find_one",
"(",
"{",
"'... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_Setting.set_config | [summary]
Keyword Arguments:
section {str} -- [description] (default: {'MONGODB'})
option {str} -- [description] (default: {'uri'})
default_value {[type]} -- [description] (default: {DEFAULT_DB_URI})
Returns:
[type] -- [description] | QUANTAXIS/QAUtil/QASetting.py | def set_config(
self,
section='MONGODB',
option='uri',
default_value=DEFAULT_DB_URI
):
"""[summary]
Keyword Arguments:
section {str} -- [description] (default: {'MONGODB'})
option {str} -- [description] (default: {'uri'})
default_value {[type]} -- [description] (default: {DEFAULT_DB_URI})
Returns:
[type] -- [description]
"""
t = {'section': section, option: default_value}
self.client.quantaxis.usersetting.update(
{'section': section}, {'$set':t}, upsert=True) | def set_config(
self,
section='MONGODB',
option='uri',
default_value=DEFAULT_DB_URI
):
"""[summary]
Keyword Arguments:
section {str} -- [description] (default: {'MONGODB'})
option {str} -- [description] (default: {'uri'})
default_value {[type]} -- [description] (default: {DEFAULT_DB_URI})
Returns:
[type] -- [description]
"""
t = {'section': section, option: default_value}
self.client.quantaxis.usersetting.update(
{'section': section}, {'$set':t}, upsert=True) | [
"[",
"summary",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QASetting.py#L103-L121 | [
"def",
"set_config",
"(",
"self",
",",
"section",
"=",
"'MONGODB'",
",",
"option",
"=",
"'uri'",
",",
"default_value",
"=",
"DEFAULT_DB_URI",
")",
":",
"t",
"=",
"{",
"'section'",
":",
"section",
",",
"option",
":",
"default_value",
"}",
"self",
".",
"cl... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_Setting.get_or_set_section | [summary]
Arguments:
config {[type]} -- [description]
section {[type]} -- [description]
option {[type]} -- [description]
DEFAULT_VALUE {[type]} -- [description]
Keyword Arguments:
method {str} -- [description] (default: {'get'})
Returns:
[type] -- [description] | QUANTAXIS/QAUtil/QASetting.py | def get_or_set_section(
self,
config,
section,
option,
DEFAULT_VALUE,
method='get'
):
"""[summary]
Arguments:
config {[type]} -- [description]
section {[type]} -- [description]
option {[type]} -- [description]
DEFAULT_VALUE {[type]} -- [description]
Keyword Arguments:
method {str} -- [description] (default: {'get'})
Returns:
[type] -- [description]
"""
try:
if isinstance(DEFAULT_VALUE, str):
val = DEFAULT_VALUE
else:
val = json.dumps(DEFAULT_VALUE)
if method == 'get':
return self.get_config(section, option)
else:
self.set_config(section, option, val)
return val
except:
self.set_config(section, option, val)
return val | def get_or_set_section(
self,
config,
section,
option,
DEFAULT_VALUE,
method='get'
):
"""[summary]
Arguments:
config {[type]} -- [description]
section {[type]} -- [description]
option {[type]} -- [description]
DEFAULT_VALUE {[type]} -- [description]
Keyword Arguments:
method {str} -- [description] (default: {'get'})
Returns:
[type] -- [description]
"""
try:
if isinstance(DEFAULT_VALUE, str):
val = DEFAULT_VALUE
else:
val = json.dumps(DEFAULT_VALUE)
if method == 'get':
return self.get_config(section, option)
else:
self.set_config(section, option, val)
return val
except:
self.set_config(section, option, val)
return val | [
"[",
"summary",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QASetting.py#L147-L183 | [
"def",
"get_or_set_section",
"(",
"self",
",",
"config",
",",
"section",
",",
"option",
",",
"DEFAULT_VALUE",
",",
"method",
"=",
"'get'",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"DEFAULT_VALUE",
",",
"str",
")",
":",
"val",
"=",
"DEFAULT_VALUE",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_date_str2int | 日期字符串 '2011-09-11' 变换成 整数 20110911
日期字符串 '2018-12-01' 变换成 整数 20181201
:param date: str日期字符串
:return: 类型int | QUANTAXIS/QAUtil/QADate.py | def QA_util_date_str2int(date):
"""
日期字符串 '2011-09-11' 变换成 整数 20110911
日期字符串 '2018-12-01' 变换成 整数 20181201
:param date: str日期字符串
:return: 类型int
"""
# return int(str(date)[0:4] + str(date)[5:7] + str(date)[8:10])
if isinstance(date, str):
return int(str().join(date.split('-')))
elif isinstance(date, int):
return date | def QA_util_date_str2int(date):
"""
日期字符串 '2011-09-11' 变换成 整数 20110911
日期字符串 '2018-12-01' 变换成 整数 20181201
:param date: str日期字符串
:return: 类型int
"""
# return int(str(date)[0:4] + str(date)[5:7] + str(date)[8:10])
if isinstance(date, str):
return int(str().join(date.split('-')))
elif isinstance(date, int):
return date | [
"日期字符串",
"2011",
"-",
"09",
"-",
"11",
"变换成",
"整数",
"20110911",
"日期字符串",
"2018",
"-",
"12",
"-",
"01",
"变换成",
"整数",
"20181201",
":",
"param",
"date",
":",
"str日期字符串",
":",
"return",
":",
"类型int"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L60-L71 | [
"def",
"QA_util_date_str2int",
"(",
"date",
")",
":",
"# return int(str(date)[0:4] + str(date)[5:7] + str(date)[8:10])",
"if",
"isinstance",
"(",
"date",
",",
"str",
")",
":",
"return",
"int",
"(",
"str",
"(",
")",
".",
"join",
"(",
"date",
".",
"split",
"(",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_date_int2str | 类型datetime.datatime
:param date: int 8位整数
:return: 类型str | QUANTAXIS/QAUtil/QADate.py | def QA_util_date_int2str(int_date):
"""
类型datetime.datatime
:param date: int 8位整数
:return: 类型str
"""
date = str(int_date)
if len(date) == 8:
return str(date[0:4] + '-' + date[4:6] + '-' + date[6:8])
elif len(date) == 10:
return date | def QA_util_date_int2str(int_date):
"""
类型datetime.datatime
:param date: int 8位整数
:return: 类型str
"""
date = str(int_date)
if len(date) == 8:
return str(date[0:4] + '-' + date[4:6] + '-' + date[6:8])
elif len(date) == 10:
return date | [
"类型datetime",
".",
"datatime",
":",
"param",
"date",
":",
"int",
"8位整数",
":",
"return",
":",
"类型str"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L74-L84 | [
"def",
"QA_util_date_int2str",
"(",
"int_date",
")",
":",
"date",
"=",
"str",
"(",
"int_date",
")",
"if",
"len",
"(",
"date",
")",
"==",
"8",
":",
"return",
"str",
"(",
"date",
"[",
"0",
":",
"4",
"]",
"+",
"'-'",
"+",
"date",
"[",
"4",
":",
"6... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_to_datetime | 字符串 '2018-01-01' 转变成 datatime 类型
:param time: 字符串str -- 格式必须是 2018-01-01 ,长度10
:return: 类型datetime.datatime | QUANTAXIS/QAUtil/QADate.py | def QA_util_to_datetime(time):
"""
字符串 '2018-01-01' 转变成 datatime 类型
:param time: 字符串str -- 格式必须是 2018-01-01 ,长度10
:return: 类型datetime.datatime
"""
if len(str(time)) == 10:
_time = '{} 00:00:00'.format(time)
elif len(str(time)) == 19:
_time = str(time)
else:
QA_util_log_info('WRONG DATETIME FORMAT {}'.format(time))
return datetime.datetime.strptime(_time, '%Y-%m-%d %H:%M:%S') | def QA_util_to_datetime(time):
"""
字符串 '2018-01-01' 转变成 datatime 类型
:param time: 字符串str -- 格式必须是 2018-01-01 ,长度10
:return: 类型datetime.datatime
"""
if len(str(time)) == 10:
_time = '{} 00:00:00'.format(time)
elif len(str(time)) == 19:
_time = str(time)
else:
QA_util_log_info('WRONG DATETIME FORMAT {}'.format(time))
return datetime.datetime.strptime(_time, '%Y-%m-%d %H:%M:%S') | [
"字符串",
"2018",
"-",
"01",
"-",
"01",
"转变成",
"datatime",
"类型",
":",
"param",
"time",
":",
"字符串str",
"--",
"格式必须是",
"2018",
"-",
"01",
"-",
"01",
",长度10",
":",
"return",
":",
"类型datetime",
".",
"datatime"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L87-L99 | [
"def",
"QA_util_to_datetime",
"(",
"time",
")",
":",
"if",
"len",
"(",
"str",
"(",
"time",
")",
")",
"==",
"10",
":",
"_time",
"=",
"'{} 00:00:00'",
".",
"format",
"(",
"time",
")",
"elif",
"len",
"(",
"str",
"(",
"time",
")",
")",
"==",
"19",
":... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_datetime_to_strdate | :param dt: pythone datetime.datetime
:return: 1999-02-01 string type | QUANTAXIS/QAUtil/QADate.py | def QA_util_datetime_to_strdate(dt):
"""
:param dt: pythone datetime.datetime
:return: 1999-02-01 string type
"""
strdate = "%04d-%02d-%02d" % (dt.year, dt.month, dt.day)
return strdate | def QA_util_datetime_to_strdate(dt):
"""
:param dt: pythone datetime.datetime
:return: 1999-02-01 string type
"""
strdate = "%04d-%02d-%02d" % (dt.year, dt.month, dt.day)
return strdate | [
":",
"param",
"dt",
":",
"pythone",
"datetime",
".",
"datetime",
":",
"return",
":",
"1999",
"-",
"02",
"-",
"01",
"string",
"type"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L102-L108 | [
"def",
"QA_util_datetime_to_strdate",
"(",
"dt",
")",
":",
"strdate",
"=",
"\"%04d-%02d-%02d\"",
"%",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
")",
"return",
"strdate"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_datetime_to_strdatetime | :param dt: pythone datetime.datetime
:return: 1999-02-01 09:30:91 string type | QUANTAXIS/QAUtil/QADate.py | def QA_util_datetime_to_strdatetime(dt):
"""
:param dt: pythone datetime.datetime
:return: 1999-02-01 09:30:91 string type
"""
strdatetime = "%04d-%02d-%02d %02d:%02d:%02d" % (
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second
)
return strdatetime | def QA_util_datetime_to_strdatetime(dt):
"""
:param dt: pythone datetime.datetime
:return: 1999-02-01 09:30:91 string type
"""
strdatetime = "%04d-%02d-%02d %02d:%02d:%02d" % (
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second
)
return strdatetime | [
":",
"param",
"dt",
":",
"pythone",
"datetime",
".",
"datetime",
":",
"return",
":",
"1999",
"-",
"02",
"-",
"01",
"09",
":",
"30",
":",
"91",
"string",
"type"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L111-L124 | [
"def",
"QA_util_datetime_to_strdatetime",
"(",
"dt",
")",
":",
"strdatetime",
"=",
"\"%04d-%02d-%02d %02d:%02d:%02d\"",
"%",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
",",
"dt",
".",
"hour",
",",
"dt",
".",
"minute",
",",
"d... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_date_stamp | 字符串 '2018-01-01' 转变成 float 类型时间 类似 time.time() 返回的类型
:param date: 字符串str -- 格式必须是 2018-01-01 ,长度10
:return: 类型float | QUANTAXIS/QAUtil/QADate.py | def QA_util_date_stamp(date):
"""
字符串 '2018-01-01' 转变成 float 类型时间 类似 time.time() 返回的类型
:param date: 字符串str -- 格式必须是 2018-01-01 ,长度10
:return: 类型float
"""
datestr = str(date)[0:10]
date = time.mktime(time.strptime(datestr, '%Y-%m-%d'))
return date | def QA_util_date_stamp(date):
"""
字符串 '2018-01-01' 转变成 float 类型时间 类似 time.time() 返回的类型
:param date: 字符串str -- 格式必须是 2018-01-01 ,长度10
:return: 类型float
"""
datestr = str(date)[0:10]
date = time.mktime(time.strptime(datestr, '%Y-%m-%d'))
return date | [
"字符串",
"2018",
"-",
"01",
"-",
"01",
"转变成",
"float",
"类型时间",
"类似",
"time",
".",
"time",
"()",
"返回的类型",
":",
"param",
"date",
":",
"字符串str",
"--",
"格式必须是",
"2018",
"-",
"01",
"-",
"01",
",长度10",
":",
"return",
":",
"类型float"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L127-L135 | [
"def",
"QA_util_date_stamp",
"(",
"date",
")",
":",
"datestr",
"=",
"str",
"(",
"date",
")",
"[",
"0",
":",
"10",
"]",
"date",
"=",
"time",
".",
"mktime",
"(",
"time",
".",
"strptime",
"(",
"datestr",
",",
"'%Y-%m-%d'",
")",
")",
"return",
"date"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_time_stamp | 字符串 '2018-01-01 00:00:00' 转变成 float 类型时间 类似 time.time() 返回的类型
:param time_: 字符串str -- 数据格式 最好是%Y-%m-%d %H:%M:%S 中间要有空格
:return: 类型float | QUANTAXIS/QAUtil/QADate.py | def QA_util_time_stamp(time_):
"""
字符串 '2018-01-01 00:00:00' 转变成 float 类型时间 类似 time.time() 返回的类型
:param time_: 字符串str -- 数据格式 最好是%Y-%m-%d %H:%M:%S 中间要有空格
:return: 类型float
"""
if len(str(time_)) == 10:
# yyyy-mm-dd格式
return time.mktime(time.strptime(time_, '%Y-%m-%d'))
elif len(str(time_)) == 16:
# yyyy-mm-dd hh:mm格式
return time.mktime(time.strptime(time_, '%Y-%m-%d %H:%M'))
else:
timestr = str(time_)[0:19]
return time.mktime(time.strptime(timestr, '%Y-%m-%d %H:%M:%S')) | def QA_util_time_stamp(time_):
"""
字符串 '2018-01-01 00:00:00' 转变成 float 类型时间 类似 time.time() 返回的类型
:param time_: 字符串str -- 数据格式 最好是%Y-%m-%d %H:%M:%S 中间要有空格
:return: 类型float
"""
if len(str(time_)) == 10:
# yyyy-mm-dd格式
return time.mktime(time.strptime(time_, '%Y-%m-%d'))
elif len(str(time_)) == 16:
# yyyy-mm-dd hh:mm格式
return time.mktime(time.strptime(time_, '%Y-%m-%d %H:%M'))
else:
timestr = str(time_)[0:19]
return time.mktime(time.strptime(timestr, '%Y-%m-%d %H:%M:%S')) | [
"字符串",
"2018",
"-",
"01",
"-",
"01",
"00",
":",
"00",
":",
"00",
"转变成",
"float",
"类型时间",
"类似",
"time",
".",
"time",
"()",
"返回的类型",
":",
"param",
"time_",
":",
"字符串str",
"--",
"数据格式",
"最好是%Y",
"-",
"%m",
"-",
"%d",
"%H",
":",
"%M",
":",
"%S",
... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L138-L152 | [
"def",
"QA_util_time_stamp",
"(",
"time_",
")",
":",
"if",
"len",
"(",
"str",
"(",
"time_",
")",
")",
"==",
"10",
":",
"# yyyy-mm-dd格式",
"return",
"time",
".",
"mktime",
"(",
"time",
".",
"strptime",
"(",
"time_",
",",
"'%Y-%m-%d'",
")",
")",
"elif",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_stamp2datetime | datestamp转datetime
pandas转出来的timestamp是13位整数 要/1000
It’s common for this to be restricted to years from 1970 through 2038.
从1970年开始的纳秒到当前的计数 转变成 float 类型时间 类似 time.time() 返回的类型
:param timestamp: long类型
:return: 类型float | QUANTAXIS/QAUtil/QADate.py | def QA_util_stamp2datetime(timestamp):
"""
datestamp转datetime
pandas转出来的timestamp是13位整数 要/1000
It’s common for this to be restricted to years from 1970 through 2038.
从1970年开始的纳秒到当前的计数 转变成 float 类型时间 类似 time.time() 返回的类型
:param timestamp: long类型
:return: 类型float
"""
try:
return datetime.datetime.fromtimestamp(timestamp)
except Exception as e:
# it won't work ??
try:
return datetime.datetime.fromtimestamp(timestamp / 1000)
except:
try:
return datetime.datetime.fromtimestamp(timestamp / 1000000)
except:
return datetime.datetime.fromtimestamp(timestamp / 1000000000) | def QA_util_stamp2datetime(timestamp):
"""
datestamp转datetime
pandas转出来的timestamp是13位整数 要/1000
It’s common for this to be restricted to years from 1970 through 2038.
从1970年开始的纳秒到当前的计数 转变成 float 类型时间 类似 time.time() 返回的类型
:param timestamp: long类型
:return: 类型float
"""
try:
return datetime.datetime.fromtimestamp(timestamp)
except Exception as e:
# it won't work ??
try:
return datetime.datetime.fromtimestamp(timestamp / 1000)
except:
try:
return datetime.datetime.fromtimestamp(timestamp / 1000000)
except:
return datetime.datetime.fromtimestamp(timestamp / 1000000000) | [
"datestamp转datetime",
"pandas转出来的timestamp是13位整数",
"要",
"/",
"1000",
"It’s",
"common",
"for",
"this",
"to",
"be",
"restricted",
"to",
"years",
"from",
"1970",
"through",
"2038",
".",
"从1970年开始的纳秒到当前的计数",
"转变成",
"float",
"类型时间",
"类似",
"time",
".",
"time",
"()",
... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L173-L192 | [
"def",
"QA_util_stamp2datetime",
"(",
"timestamp",
")",
":",
"try",
":",
"return",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"timestamp",
")",
"except",
"Exception",
"as",
"e",
":",
"# it won't work ??",
"try",
":",
"return",
"datetime",
".",
"da... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_realtime | 查询数据库中的数据
:param strtime: strtime str字符串 -- 1999-12-11 这种格式
:param client: client pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Dictionary -- {'time_real': 时间,'id': id} | QUANTAXIS/QAUtil/QADate.py | def QA_util_realtime(strtime, client):
"""
查询数据库中的数据
:param strtime: strtime str字符串 -- 1999-12-11 这种格式
:param client: client pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Dictionary -- {'time_real': 时间,'id': id}
"""
time_stamp = QA_util_date_stamp(strtime)
coll = client.quantaxis.trade_date
temp_str = coll.find_one({'date_stamp': {"$gte": time_stamp}})
time_real = temp_str['date']
time_id = temp_str['num']
return {'time_real': time_real, 'id': time_id} | def QA_util_realtime(strtime, client):
"""
查询数据库中的数据
:param strtime: strtime str字符串 -- 1999-12-11 这种格式
:param client: client pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Dictionary -- {'time_real': 时间,'id': id}
"""
time_stamp = QA_util_date_stamp(strtime)
coll = client.quantaxis.trade_date
temp_str = coll.find_one({'date_stamp': {"$gte": time_stamp}})
time_real = temp_str['date']
time_id = temp_str['num']
return {'time_real': time_real, 'id': time_id} | [
"查询数据库中的数据",
":",
"param",
"strtime",
":",
"strtime",
"str字符串",
"--",
"1999",
"-",
"12",
"-",
"11",
"这种格式",
":",
"param",
"client",
":",
"client",
"pymongo",
".",
"MongoClient类型",
"--",
"mongodb",
"数据库",
"从",
"QA_util_sql_mongo_setting",
"中",
"QA_util_sql_mong... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L219-L231 | [
"def",
"QA_util_realtime",
"(",
"strtime",
",",
"client",
")",
":",
"time_stamp",
"=",
"QA_util_date_stamp",
"(",
"strtime",
")",
"coll",
"=",
"client",
".",
"quantaxis",
".",
"trade_date",
"temp_str",
"=",
"coll",
".",
"find_one",
"(",
"{",
"'date_stamp'",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_id2date | 从数据库中查询 通达信时间
:param idx: 字符串 -- 数据库index
:param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Str -- 通达信数据库时间 | QUANTAXIS/QAUtil/QADate.py | def QA_util_id2date(idx, client):
"""
从数据库中查询 通达信时间
:param idx: 字符串 -- 数据库index
:param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Str -- 通达信数据库时间
"""
coll = client.quantaxis.trade_date
temp_str = coll.find_one({'num': idx})
return temp_str['date'] | def QA_util_id2date(idx, client):
"""
从数据库中查询 通达信时间
:param idx: 字符串 -- 数据库index
:param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Str -- 通达信数据库时间
"""
coll = client.quantaxis.trade_date
temp_str = coll.find_one({'num': idx})
return temp_str['date'] | [
"从数据库中查询",
"通达信时间",
":",
"param",
"idx",
":",
"字符串",
"--",
"数据库index",
":",
"param",
"client",
":",
"pymongo",
".",
"MongoClient类型",
"--",
"mongodb",
"数据库",
"从",
"QA_util_sql_mongo_setting",
"中",
"QA_util_sql_mongo_setting",
"获取",
":",
"return",
":",
"Str",
"-... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L234-L243 | [
"def",
"QA_util_id2date",
"(",
"idx",
",",
"client",
")",
":",
"coll",
"=",
"client",
".",
"quantaxis",
".",
"trade_date",
"temp_str",
"=",
"coll",
".",
"find_one",
"(",
"{",
"'num'",
":",
"idx",
"}",
")",
"return",
"temp_str",
"[",
"'date'",
"]"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_is_trade | 判断是否是交易日
从数据库中查询
:param date: str类型 -- 1999-12-11 这种格式 10位字符串
:param code: str类型 -- 股票代码 例如 603658 , 6位字符串
:param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Boolean -- 是否是交易时间 | QUANTAXIS/QAUtil/QADate.py | def QA_util_is_trade(date, code, client):
"""
判断是否是交易日
从数据库中查询
:param date: str类型 -- 1999-12-11 这种格式 10位字符串
:param code: str类型 -- 股票代码 例如 603658 , 6位字符串
:param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Boolean -- 是否是交易时间
"""
coll = client.quantaxis.stock_day
date = str(date)[0:10]
is_trade = coll.find_one({'code': code, 'date': date})
try:
len(is_trade)
return True
except:
return False | def QA_util_is_trade(date, code, client):
"""
判断是否是交易日
从数据库中查询
:param date: str类型 -- 1999-12-11 这种格式 10位字符串
:param code: str类型 -- 股票代码 例如 603658 , 6位字符串
:param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Boolean -- 是否是交易时间
"""
coll = client.quantaxis.stock_day
date = str(date)[0:10]
is_trade = coll.find_one({'code': code, 'date': date})
try:
len(is_trade)
return True
except:
return False | [
"判断是否是交易日",
"从数据库中查询",
":",
"param",
"date",
":",
"str类型",
"--",
"1999",
"-",
"12",
"-",
"11",
"这种格式",
"10位字符串",
":",
"param",
"code",
":",
"str类型",
"--",
"股票代码",
"例如",
"603658",
",",
"6位字符串",
":",
"param",
"client",
":",
"pymongo",
".",
"MongoClient类型... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L246-L262 | [
"def",
"QA_util_is_trade",
"(",
"date",
",",
"code",
",",
"client",
")",
":",
"coll",
"=",
"client",
".",
"quantaxis",
".",
"stock_day",
"date",
"=",
"str",
"(",
"date",
")",
"[",
"0",
":",
"10",
"]",
"is_trade",
"=",
"coll",
".",
"find_one",
"(",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_select_hours | quantaxis的时间选择函数,约定时间的范围,比如早上9点到11点 | QUANTAXIS/QAUtil/QADate.py | def QA_util_select_hours(time=None, gt=None, lt=None, gte=None, lte=None):
'quantaxis的时间选择函数,约定时间的范围,比如早上9点到11点'
if time is None:
__realtime = datetime.datetime.now()
else:
__realtime = time
fun_list = []
if gt != None:
fun_list.append('>')
if lt != None:
fun_list.append('<')
if gte != None:
fun_list.append('>=')
if lte != None:
fun_list.append('<=')
assert len(fun_list) > 0
true_list = []
try:
for item in fun_list:
if item == '>':
if __realtime.strftime('%H') > gt:
true_list.append(0)
else:
true_list.append(1)
elif item == '<':
if __realtime.strftime('%H') < lt:
true_list.append(0)
else:
true_list.append(1)
elif item == '>=':
if __realtime.strftime('%H') >= gte:
true_list.append(0)
else:
true_list.append(1)
elif item == '<=':
if __realtime.strftime('%H') <= lte:
true_list.append(0)
else:
true_list.append(1)
except:
return Exception
if sum(true_list) > 0:
return False
else:
return True | def QA_util_select_hours(time=None, gt=None, lt=None, gte=None, lte=None):
'quantaxis的时间选择函数,约定时间的范围,比如早上9点到11点'
if time is None:
__realtime = datetime.datetime.now()
else:
__realtime = time
fun_list = []
if gt != None:
fun_list.append('>')
if lt != None:
fun_list.append('<')
if gte != None:
fun_list.append('>=')
if lte != None:
fun_list.append('<=')
assert len(fun_list) > 0
true_list = []
try:
for item in fun_list:
if item == '>':
if __realtime.strftime('%H') > gt:
true_list.append(0)
else:
true_list.append(1)
elif item == '<':
if __realtime.strftime('%H') < lt:
true_list.append(0)
else:
true_list.append(1)
elif item == '>=':
if __realtime.strftime('%H') >= gte:
true_list.append(0)
else:
true_list.append(1)
elif item == '<=':
if __realtime.strftime('%H') <= lte:
true_list.append(0)
else:
true_list.append(1)
except:
return Exception
if sum(true_list) > 0:
return False
else:
return True | [
"quantaxis的时间选择函数",
"约定时间的范围",
"比如早上9点到11点"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L284-L331 | [
"def",
"QA_util_select_hours",
"(",
"time",
"=",
"None",
",",
"gt",
"=",
"None",
",",
"lt",
"=",
"None",
",",
"gte",
"=",
"None",
",",
"lte",
"=",
"None",
")",
":",
"if",
"time",
"is",
"None",
":",
"__realtime",
"=",
"datetime",
".",
"datetime",
".... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_calc_time | '耗时长度的装饰器'
:param func:
:param args:
:param kwargs:
:return: | QUANTAXIS/QAUtil/QADate.py | def QA_util_calc_time(func, *args, **kwargs):
"""
'耗时长度的装饰器'
:param func:
:param args:
:param kwargs:
:return:
"""
_time = datetime.datetime.now()
func(*args, **kwargs)
print(datetime.datetime.now() - _time) | def QA_util_calc_time(func, *args, **kwargs):
"""
'耗时长度的装饰器'
:param func:
:param args:
:param kwargs:
:return:
"""
_time = datetime.datetime.now()
func(*args, **kwargs)
print(datetime.datetime.now() - _time) | [
"耗时长度的装饰器",
":",
"param",
"func",
":",
":",
"param",
"args",
":",
":",
"param",
"kwargs",
":",
":",
"return",
":"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QADate.py#L407-L417 | [
"def",
"QA_util_calc_time",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"print",
"(",
"datetime",
".",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_DataStruct_Stock_day.high_limit | 涨停价 | QUANTAXIS/QAData/QADataStruct.py | def high_limit(self):
'涨停价'
return self.groupby(level=1).close.apply(lambda x: round((x.shift(1) + 0.0002)*1.1, 2)).sort_index() | def high_limit(self):
'涨停价'
return self.groupby(level=1).close.apply(lambda x: round((x.shift(1) + 0.0002)*1.1, 2)).sort_index() | [
"涨停价"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/QADataStruct.py#L121-L123 | [
"def",
"high_limit",
"(",
"self",
")",
":",
"return",
"self",
".",
"groupby",
"(",
"level",
"=",
"1",
")",
".",
"close",
".",
"apply",
"(",
"lambda",
"x",
":",
"round",
"(",
"(",
"x",
".",
"shift",
"(",
"1",
")",
"+",
"0.0002",
")",
"*",
"1.1",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_DataStruct_Stock_day.next_day_low_limit | 明日跌停价 | QUANTAXIS/QAData/QADataStruct.py | def next_day_low_limit(self):
"明日跌停价"
return self.groupby(level=1).close.apply(lambda x: round((x + 0.0002)*0.9, 2)).sort_index() | def next_day_low_limit(self):
"明日跌停价"
return self.groupby(level=1).close.apply(lambda x: round((x + 0.0002)*0.9, 2)).sort_index() | [
"明日跌停价"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/QADataStruct.py#L133-L135 | [
"def",
"next_day_low_limit",
"(",
"self",
")",
":",
"return",
"self",
".",
"groupby",
"(",
"level",
"=",
"1",
")",
".",
"close",
".",
"apply",
"(",
"lambda",
"x",
":",
"round",
"(",
"(",
"x",
"+",
"0.0002",
")",
"*",
"0.9",
",",
"2",
")",
")",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_DataStruct_Stock_transaction.get_medium_order | return medium
Keyword Arguments:
lower {[type]} -- [description] (default: {200000})
higher {[type]} -- [description] (default: {1000000})
Returns:
[type] -- [description] | QUANTAXIS/QAData/QADataStruct.py | def get_medium_order(self, lower=200000, higher=1000000):
"""return medium
Keyword Arguments:
lower {[type]} -- [description] (default: {200000})
higher {[type]} -- [description] (default: {1000000})
Returns:
[type] -- [description]
"""
return self.data.query('amount>={}'.format(lower)).query('amount<={}'.format(higher)) | def get_medium_order(self, lower=200000, higher=1000000):
"""return medium
Keyword Arguments:
lower {[type]} -- [description] (default: {200000})
higher {[type]} -- [description] (default: {1000000})
Returns:
[type] -- [description]
"""
return self.data.query('amount>={}'.format(lower)).query('amount<={}'.format(higher)) | [
"return",
"medium"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/QADataStruct.py#L767-L778 | [
"def",
"get_medium_order",
"(",
"self",
",",
"lower",
"=",
"200000",
",",
"higher",
"=",
"1000000",
")",
":",
"return",
"self",
".",
"data",
".",
"query",
"(",
"'amount>={}'",
".",
"format",
"(",
"lower",
")",
")",
".",
"query",
"(",
"'amount<={}'",
".... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | shadow_calc | 计算上下影线
Arguments:
data {DataStruct.slice} -- 输入的是一个行情切片
Returns:
up_shadow {float} -- 上影线
down_shdow {float} -- 下影线
entity {float} -- 实体部分
date {str} -- 时间
code {str} -- 代码 | QUANTAXIS/QAAnalysis/QAAnalysis_dataframe.py | def shadow_calc(data):
"""计算上下影线
Arguments:
data {DataStruct.slice} -- 输入的是一个行情切片
Returns:
up_shadow {float} -- 上影线
down_shdow {float} -- 下影线
entity {float} -- 实体部分
date {str} -- 时间
code {str} -- 代码
"""
up_shadow = abs(data.high - (max(data.open, data.close)))
down_shadow = abs(data.low - (min(data.open, data.close)))
entity = abs(data.open - data.close)
towards = True if data.open < data.close else False
print('=' * 15)
print('up_shadow : {}'.format(up_shadow))
print('down_shadow : {}'.format(down_shadow))
print('entity: {}'.format(entity))
print('towards : {}'.format(towards))
return up_shadow, down_shadow, entity, data.date, data.code | def shadow_calc(data):
"""计算上下影线
Arguments:
data {DataStruct.slice} -- 输入的是一个行情切片
Returns:
up_shadow {float} -- 上影线
down_shdow {float} -- 下影线
entity {float} -- 实体部分
date {str} -- 时间
code {str} -- 代码
"""
up_shadow = abs(data.high - (max(data.open, data.close)))
down_shadow = abs(data.low - (min(data.open, data.close)))
entity = abs(data.open - data.close)
towards = True if data.open < data.close else False
print('=' * 15)
print('up_shadow : {}'.format(up_shadow))
print('down_shadow : {}'.format(down_shadow))
print('entity: {}'.format(entity))
print('towards : {}'.format(towards))
return up_shadow, down_shadow, entity, data.date, data.code | [
"计算上下影线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAAnalysis/QAAnalysis_dataframe.py#L202-L225 | [
"def",
"shadow_calc",
"(",
"data",
")",
":",
"up_shadow",
"=",
"abs",
"(",
"data",
".",
"high",
"-",
"(",
"max",
"(",
"data",
".",
"open",
",",
"data",
".",
"close",
")",
")",
")",
"down_shadow",
"=",
"abs",
"(",
"data",
".",
"low",
"-",
"(",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SimulatedBroker.query_data | 标准格式是numpy | QUANTAXIS/QAMarket/QASimulatedBroker.py | def query_data(self, code, start, end, frequence, market_type=None):
"""
标准格式是numpy
"""
try:
return self.fetcher[(market_type, frequence)](
code, start, end, frequence=frequence)
except:
pass | def query_data(self, code, start, end, frequence, market_type=None):
"""
标准格式是numpy
"""
try:
return self.fetcher[(market_type, frequence)](
code, start, end, frequence=frequence)
except:
pass | [
"标准格式是numpy"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QASimulatedBroker.py#L76-L84 | [
"def",
"query_data",
"(",
"self",
",",
"code",
",",
"start",
",",
"end",
",",
"frequence",
",",
"market_type",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"fetcher",
"[",
"(",
"market_type",
",",
"frequence",
")",
"]",
"(",
"code",
",",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_stock_min | 掘金实现方式
save current day's stock_min data | QUANTAXIS/QASU/save_gm.py | def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None):
"""
掘金实现方式
save current day's stock_min data
"""
# 导入掘金模块且进行登录
try:
from gm.api import set_token
from gm.api import history
# 请自行将掘金量化的 TOKEN 替换掉 GMTOKEN
set_token("9c5601171e97994686b47b5cbfe7b2fc8bb25b09")
except:
raise ModuleNotFoundError
# 股票代码格式化
code_list = list(
map(
lambda x: "SHSE." + x if x[0] == "6" else "SZSE." + x,
QA_fetch_get_stock_list().code.unique().tolist(),
))
coll = client.stock_min
coll.create_index([
("code", pymongo.ASCENDING),
("time_stamp", pymongo.ASCENDING),
("date_stamp", pymongo.ASCENDING),
])
err = []
def __transform_gm_to_qa(df, type_):
"""
将掘金数据转换为 qa 格式
"""
if df is None or len(df) == 0:
raise ValueError("没有掘金数据")
df = df.rename(columns={
"eob": "datetime",
"volume": "vol",
"symbol": "code"
}).drop(["bob", "frequency", "position", "pre_close"], axis=1)
df["code"] = df["code"].map(str).str.slice(5, )
df["datetime"] = pd.to_datetime(df["datetime"].map(str).str.slice(
0, 19))
df["date"] = df.datetime.map(str).str.slice(0, 10)
df = df.set_index("datetime", drop=False)
df["date_stamp"] = df["date"].apply(lambda x: QA_util_date_stamp(x))
df["time_stamp"] = (
df["datetime"].map(str).apply(lambda x: QA_util_time_stamp(x)))
df["type"] = type_
return df[[
"open",
"close",
"high",
"low",
"vol",
"amount",
"datetime",
"code",
"date",
"date_stamp",
"time_stamp",
"type",
]]
def __saving_work(code, coll):
QA_util_log_info(
"##JOB03 Now Saving STOCK_MIN ==== {}".format(code), ui_log=ui_log)
try:
for type_ in ["1min", "5min", "15min", "30min", "60min"]:
col_filter = {"code": str(code)[5:], "type": type_}
ref_ = coll.find(col_filter)
end_time = str(now_time())[0:19]
if coll.count_documents(col_filter) > 0:
start_time = ref_[coll.count_documents(
col_filter) - 1]["datetime"]
print(start_time)
QA_util_log_info(
"##JOB03.{} Now Saving {} from {} to {} == {}".format(
["1min",
"5min",
"15min",
"30min",
"60min"
].index(type_),
str(code)[5:],
start_time,
end_time,
type_,
),
ui_log=ui_log,
)
if start_time != end_time:
df = history(
symbol=code,
start_time=start_time,
end_time=end_time,
frequency=MIN_SEC[type_],
df=True
)
__data = __transform_gm_to_qa(df, type_)
if len(__data) > 1:
# print(QA_util_to_json_from_pandas(__data)[1::])
# print(__data)
coll.insert_many(
QA_util_to_json_from_pandas(__data)[1::])
else:
start_time = "2015-01-01 09:30:00"
QA_util_log_info(
"##JOB03.{} Now Saving {} from {} to {} == {}".format(
["1min",
"5min",
"15min",
"30min",
"60min"
].index(type_),
str(code)[5:],
start_time,
end_time,
type_,
),
ui_log=ui_log,
)
if start_time != end_time:
df = history(
symbol=code,
start_time=start_time,
end_time=end_time,
frequency=MIN_SEC[type_],
df=True
)
__data = __transform_gm_to_qa(df, type_)
if len(__data) > 1:
# print(__data)
coll.insert_many(
QA_util_to_json_from_pandas(__data)[1::])
# print(QA_util_to_json_from_pandas(__data)[1::])
except Exception as e:
QA_util_log_info(e, ui_log=ui_log)
err.append(code)
QA_util_log_info(err, ui_log=ui_log)
executor = ThreadPoolExecutor(max_workers=2)
res = {
executor.submit(__saving_work, code_list[i_], coll)
for i_ in range(len(code_list))
}
count = 0
for i_ in concurrent.futures.as_completed(res):
QA_util_log_info(
'The {} of Total {}'.format(count,
len(code_list)),
ui_log=ui_log
)
strProgress = "DOWNLOAD PROGRESS {} ".format(
str(float(count / len(code_list) * 100))[0:4] + "%")
intProgress = int(count / len(code_list) * 10000.0)
QA_util_log_info(
strProgress,
ui_log,
ui_progress=ui_progress,
ui_progress_int_value=intProgress
)
count = count + 1
if len(err) < 1:
QA_util_log_info("SUCCESS", ui_log=ui_log)
else:
QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
QA_util_log_info(err, ui_log=ui_log) | def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None):
"""
掘金实现方式
save current day's stock_min data
"""
# 导入掘金模块且进行登录
try:
from gm.api import set_token
from gm.api import history
# 请自行将掘金量化的 TOKEN 替换掉 GMTOKEN
set_token("9c5601171e97994686b47b5cbfe7b2fc8bb25b09")
except:
raise ModuleNotFoundError
# 股票代码格式化
code_list = list(
map(
lambda x: "SHSE." + x if x[0] == "6" else "SZSE." + x,
QA_fetch_get_stock_list().code.unique().tolist(),
))
coll = client.stock_min
coll.create_index([
("code", pymongo.ASCENDING),
("time_stamp", pymongo.ASCENDING),
("date_stamp", pymongo.ASCENDING),
])
err = []
def __transform_gm_to_qa(df, type_):
"""
将掘金数据转换为 qa 格式
"""
if df is None or len(df) == 0:
raise ValueError("没有掘金数据")
df = df.rename(columns={
"eob": "datetime",
"volume": "vol",
"symbol": "code"
}).drop(["bob", "frequency", "position", "pre_close"], axis=1)
df["code"] = df["code"].map(str).str.slice(5, )
df["datetime"] = pd.to_datetime(df["datetime"].map(str).str.slice(
0, 19))
df["date"] = df.datetime.map(str).str.slice(0, 10)
df = df.set_index("datetime", drop=False)
df["date_stamp"] = df["date"].apply(lambda x: QA_util_date_stamp(x))
df["time_stamp"] = (
df["datetime"].map(str).apply(lambda x: QA_util_time_stamp(x)))
df["type"] = type_
return df[[
"open",
"close",
"high",
"low",
"vol",
"amount",
"datetime",
"code",
"date",
"date_stamp",
"time_stamp",
"type",
]]
def __saving_work(code, coll):
QA_util_log_info(
"##JOB03 Now Saving STOCK_MIN ==== {}".format(code), ui_log=ui_log)
try:
for type_ in ["1min", "5min", "15min", "30min", "60min"]:
col_filter = {"code": str(code)[5:], "type": type_}
ref_ = coll.find(col_filter)
end_time = str(now_time())[0:19]
if coll.count_documents(col_filter) > 0:
start_time = ref_[coll.count_documents(
col_filter) - 1]["datetime"]
print(start_time)
QA_util_log_info(
"##JOB03.{} Now Saving {} from {} to {} == {}".format(
["1min",
"5min",
"15min",
"30min",
"60min"
].index(type_),
str(code)[5:],
start_time,
end_time,
type_,
),
ui_log=ui_log,
)
if start_time != end_time:
df = history(
symbol=code,
start_time=start_time,
end_time=end_time,
frequency=MIN_SEC[type_],
df=True
)
__data = __transform_gm_to_qa(df, type_)
if len(__data) > 1:
# print(QA_util_to_json_from_pandas(__data)[1::])
# print(__data)
coll.insert_many(
QA_util_to_json_from_pandas(__data)[1::])
else:
start_time = "2015-01-01 09:30:00"
QA_util_log_info(
"##JOB03.{} Now Saving {} from {} to {} == {}".format(
["1min",
"5min",
"15min",
"30min",
"60min"
].index(type_),
str(code)[5:],
start_time,
end_time,
type_,
),
ui_log=ui_log,
)
if start_time != end_time:
df = history(
symbol=code,
start_time=start_time,
end_time=end_time,
frequency=MIN_SEC[type_],
df=True
)
__data = __transform_gm_to_qa(df, type_)
if len(__data) > 1:
# print(__data)
coll.insert_many(
QA_util_to_json_from_pandas(__data)[1::])
# print(QA_util_to_json_from_pandas(__data)[1::])
except Exception as e:
QA_util_log_info(e, ui_log=ui_log)
err.append(code)
QA_util_log_info(err, ui_log=ui_log)
executor = ThreadPoolExecutor(max_workers=2)
res = {
executor.submit(__saving_work, code_list[i_], coll)
for i_ in range(len(code_list))
}
count = 0
for i_ in concurrent.futures.as_completed(res):
QA_util_log_info(
'The {} of Total {}'.format(count,
len(code_list)),
ui_log=ui_log
)
strProgress = "DOWNLOAD PROGRESS {} ".format(
str(float(count / len(code_list) * 100))[0:4] + "%")
intProgress = int(count / len(code_list) * 10000.0)
QA_util_log_info(
strProgress,
ui_log,
ui_progress=ui_progress,
ui_progress_int_value=intProgress
)
count = count + 1
if len(err) < 1:
QA_util_log_info("SUCCESS", ui_log=ui_log)
else:
QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
QA_util_log_info(err, ui_log=ui_log) | [
"掘金实现方式",
"save",
"current",
"day",
"s",
"stock_min",
"data"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_gm.py#L36-L206 | [
"def",
"QA_SU_save_stock_min",
"(",
"client",
"=",
"DATABASE",
",",
"ui_log",
"=",
"None",
",",
"ui_progress",
"=",
"None",
")",
":",
"# 导入掘金模块且进行登录",
"try",
":",
"from",
"gm",
".",
"api",
"import",
"set_token",
"from",
"gm",
".",
"api",
"import",
"history... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.datetime | 分钟线结构返回datetime 日线结构返回date | QUANTAXIS/QAData/base_datastruct.py | def datetime(self):
'分钟线结构返回datetime 日线结构返回date'
index = self.data.index.remove_unused_levels()
return pd.to_datetime(index.levels[0]) | def datetime(self):
'分钟线结构返回datetime 日线结构返回date'
index = self.data.index.remove_unused_levels()
return pd.to_datetime(index.levels[0]) | [
"分钟线结构返回datetime",
"日线结构返回date"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L391-L394 | [
"def",
"datetime",
"(",
"self",
")",
":",
"index",
"=",
"self",
".",
"data",
".",
"index",
".",
"remove_unused_levels",
"(",
")",
"return",
"pd",
".",
"to_datetime",
"(",
"index",
".",
"levels",
"[",
"0",
"]",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.price_diff | 返回DataStruct.price的一阶差分 | QUANTAXIS/QAData/base_datastruct.py | def price_diff(self):
'返回DataStruct.price的一阶差分'
res = self.price.groupby(level=1).apply(lambda x: x.diff(1))
res.name = 'price_diff'
return res | def price_diff(self):
'返回DataStruct.price的一阶差分'
res = self.price.groupby(level=1).apply(lambda x: x.diff(1))
res.name = 'price_diff'
return res | [
"返回DataStruct",
".",
"price的一阶差分"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L447-L451 | [
"def",
"price_diff",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"price",
".",
"groupby",
"(",
"level",
"=",
"1",
")",
".",
"apply",
"(",
"lambda",
"x",
":",
"x",
".",
"diff",
"(",
"1",
")",
")",
"res",
".",
"name",
"=",
"'price_diff'",
"re... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.pvariance | 返回DataStruct.price的方差 variance | QUANTAXIS/QAData/base_datastruct.py | def pvariance(self):
'返回DataStruct.price的方差 variance'
res = self.price.groupby(level=1
).apply(lambda x: statistics.pvariance(x))
res.name = 'pvariance'
return res | def pvariance(self):
'返回DataStruct.price的方差 variance'
res = self.price.groupby(level=1
).apply(lambda x: statistics.pvariance(x))
res.name = 'pvariance'
return res | [
"返回DataStruct",
".",
"price的方差",
"variance"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L457-L462 | [
"def",
"pvariance",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"price",
".",
"groupby",
"(",
"level",
"=",
"1",
")",
".",
"apply",
"(",
"lambda",
"x",
":",
"statistics",
".",
"pvariance",
"(",
"x",
")",
")",
"res",
".",
"name",
"=",
"'pvaria... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.bar_pct_change | 返回bar的涨跌幅 | QUANTAXIS/QAData/base_datastruct.py | def bar_pct_change(self):
'返回bar的涨跌幅'
res = (self.close - self.open) / self.open
res.name = 'bar_pct_change'
return res | def bar_pct_change(self):
'返回bar的涨跌幅'
res = (self.close - self.open) / self.open
res.name = 'bar_pct_change'
return res | [
"返回bar的涨跌幅"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L478-L482 | [
"def",
"bar_pct_change",
"(",
"self",
")",
":",
"res",
"=",
"(",
"self",
".",
"close",
"-",
"self",
".",
"open",
")",
"/",
"self",
".",
"open",
"res",
".",
"name",
"=",
"'bar_pct_change'",
"return",
"res"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.bar_amplitude | 返回bar振幅 | QUANTAXIS/QAData/base_datastruct.py | def bar_amplitude(self):
"返回bar振幅"
res = (self.high - self.low) / self.low
res.name = 'bar_amplitude'
return res | def bar_amplitude(self):
"返回bar振幅"
res = (self.high - self.low) / self.low
res.name = 'bar_amplitude'
return res | [
"返回bar振幅"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L486-L490 | [
"def",
"bar_amplitude",
"(",
"self",
")",
":",
"res",
"=",
"(",
"self",
".",
"high",
"-",
"self",
".",
"low",
")",
"/",
"self",
".",
"low",
"res",
".",
"name",
"=",
"'bar_amplitude'",
"return",
"res"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.mean_harmonic | 返回DataStruct.price的调和平均数 | QUANTAXIS/QAData/base_datastruct.py | def mean_harmonic(self):
'返回DataStruct.price的调和平均数'
res = self.price.groupby(level=1
).apply(lambda x: statistics.harmonic_mean(x))
res.name = 'mean_harmonic'
return res | def mean_harmonic(self):
'返回DataStruct.price的调和平均数'
res = self.price.groupby(level=1
).apply(lambda x: statistics.harmonic_mean(x))
res.name = 'mean_harmonic'
return res | [
"返回DataStruct",
".",
"price的调和平均数"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L513-L518 | [
"def",
"mean_harmonic",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"price",
".",
"groupby",
"(",
"level",
"=",
"1",
")",
".",
"apply",
"(",
"lambda",
"x",
":",
"statistics",
".",
"harmonic_mean",
"(",
"x",
")",
")",
"res",
".",
"name",
"=",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.amplitude | 返回DataStruct.price的百分比变化 | QUANTAXIS/QAData/base_datastruct.py | def amplitude(self):
'返回DataStruct.price的百分比变化'
res = self.price.groupby(
level=1
).apply(lambda x: (x.max() - x.min()) / x.min())
res.name = 'amplitude'
return res | def amplitude(self):
'返回DataStruct.price的百分比变化'
res = self.price.groupby(
level=1
).apply(lambda x: (x.max() - x.min()) / x.min())
res.name = 'amplitude'
return res | [
"返回DataStruct",
".",
"price的百分比变化"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L536-L542 | [
"def",
"amplitude",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"price",
".",
"groupby",
"(",
"level",
"=",
"1",
")",
".",
"apply",
"(",
"lambda",
"x",
":",
"(",
"x",
".",
"max",
"(",
")",
"-",
"x",
".",
"min",
"(",
")",
")",
"/",
"x",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.close_pct_change | 返回DataStruct.close的百分比变化 | QUANTAXIS/QAData/base_datastruct.py | def close_pct_change(self):
'返回DataStruct.close的百分比变化'
res = self.close.groupby(level=1).apply(lambda x: x.pct_change())
res.name = 'close_pct_change'
return res | def close_pct_change(self):
'返回DataStruct.close的百分比变化'
res = self.close.groupby(level=1).apply(lambda x: x.pct_change())
res.name = 'close_pct_change'
return res | [
"返回DataStruct",
".",
"close的百分比变化"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L575-L579 | [
"def",
"close_pct_change",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"close",
".",
"groupby",
"(",
"level",
"=",
"1",
")",
".",
"apply",
"(",
"lambda",
"x",
":",
"x",
".",
"pct_change",
"(",
")",
")",
"res",
".",
"name",
"=",
"'close_pct_chan... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.normalized | 归一化 | QUANTAXIS/QAData/base_datastruct.py | def normalized(self):
'归一化'
res = self.groupby('code').apply(lambda x: x / x.iloc[0])
return res | def normalized(self):
'归一化'
res = self.groupby('code').apply(lambda x: x / x.iloc[0])
return res | [
"归一化"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L593-L596 | [
"def",
"normalized",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"groupby",
"(",
"'code'",
")",
".",
"apply",
"(",
"lambda",
"x",
":",
"x",
"/",
"x",
".",
"iloc",
"[",
"0",
"]",
")",
"return",
"res"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.security_gen | 返回一个基于代码的迭代器 | QUANTAXIS/QAData/base_datastruct.py | def security_gen(self):
'返回一个基于代码的迭代器'
for item in self.index.levels[1]:
yield self.new(
self.data.xs(item,
level=1,
drop_level=False),
dtype=self.type,
if_fq=self.if_fq
) | def security_gen(self):
'返回一个基于代码的迭代器'
for item in self.index.levels[1]:
yield self.new(
self.data.xs(item,
level=1,
drop_level=False),
dtype=self.type,
if_fq=self.if_fq
) | [
"返回一个基于代码的迭代器"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L618-L627 | [
"def",
"security_gen",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"index",
".",
"levels",
"[",
"1",
"]",
":",
"yield",
"self",
".",
"new",
"(",
"self",
".",
"data",
".",
"xs",
"(",
"item",
",",
"level",
"=",
"1",
",",
"drop_level",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.get_dict | 'give the time,code tuple and turn the dict'
:param time:
:param code:
:return: 字典dict 类型 | QUANTAXIS/QAData/base_datastruct.py | def get_dict(self, time, code):
'''
'give the time,code tuple and turn the dict'
:param time:
:param code:
:return: 字典dict 类型
'''
try:
return self.dicts[(QA_util_to_datetime(time), str(code))]
except Exception as e:
raise e | def get_dict(self, time, code):
'''
'give the time,code tuple and turn the dict'
:param time:
:param code:
:return: 字典dict 类型
'''
try:
return self.dicts[(QA_util_to_datetime(time), str(code))]
except Exception as e:
raise e | [
"give",
"the",
"time",
"code",
"tuple",
"and",
"turn",
"the",
"dict",
":",
"param",
"time",
":",
":",
"param",
"code",
":",
":",
"return",
":",
"字典dict",
"类型"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L662-L672 | [
"def",
"get_dict",
"(",
"self",
",",
"time",
",",
"code",
")",
":",
"try",
":",
"return",
"self",
".",
"dicts",
"[",
"(",
"QA_util_to_datetime",
"(",
"time",
")",
",",
"str",
"(",
"code",
")",
")",
"]",
"except",
"Exception",
"as",
"e",
":",
"raise... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.kline_echarts | plot the market_data | QUANTAXIS/QAData/base_datastruct.py | def kline_echarts(self, code=None):
def kline_formater(param):
return param.name + ':' + vars(param)
"""plot the market_data"""
if code is None:
path_name = '.' + os.sep + 'QA_' + self.type + \
'_codepackage_' + self.if_fq + '.html'
kline = Kline(
'CodePackage_' + self.if_fq + '_' + self.type,
width=1360,
height=700,
page_title='QUANTAXIS'
)
bar = Bar()
data_splits = self.splits()
for ds in data_splits:
data = []
axis = []
if ds.type[-3:] == 'day':
datetime = np.array(ds.date.map(str))
else:
datetime = np.array(ds.datetime.map(str))
ohlc = np.array(
ds.data.loc[:,
['open',
'close',
'low',
'high']]
)
kline.add(
ds.code[0],
datetime,
ohlc,
mark_point=["max",
"min"],
is_datazoom_show=True,
datazoom_orient='horizontal'
)
return kline
else:
data = []
axis = []
ds = self.select_code(code)
data = []
#axis = []
if self.type[-3:] == 'day':
datetime = np.array(ds.date.map(str))
else:
datetime = np.array(ds.datetime.map(str))
ohlc = np.array(ds.data.loc[:, ['open', 'close', 'low', 'high']])
vol = np.array(ds.volume)
kline = Kline(
'{}__{}__{}'.format(code,
self.if_fq,
self.type),
width=1360,
height=700,
page_title='QUANTAXIS'
)
bar = Bar()
kline.add(self.code, datetime, ohlc,
mark_point=["max", "min"],
# is_label_show=True,
is_datazoom_show=True,
is_xaxis_show=False,
# is_toolbox_show=True,
tooltip_formatter='{b}:{c}', # kline_formater,
# is_more_utils=True,
datazoom_orient='horizontal')
bar.add(
self.code,
datetime,
vol,
is_datazoom_show=True,
datazoom_xaxis_index=[0,
1]
)
grid = Grid(width=1360, height=700, page_title='QUANTAXIS')
grid.add(bar, grid_top="80%")
grid.add(kline, grid_bottom="30%")
return grid | def kline_echarts(self, code=None):
def kline_formater(param):
return param.name + ':' + vars(param)
"""plot the market_data"""
if code is None:
path_name = '.' + os.sep + 'QA_' + self.type + \
'_codepackage_' + self.if_fq + '.html'
kline = Kline(
'CodePackage_' + self.if_fq + '_' + self.type,
width=1360,
height=700,
page_title='QUANTAXIS'
)
bar = Bar()
data_splits = self.splits()
for ds in data_splits:
data = []
axis = []
if ds.type[-3:] == 'day':
datetime = np.array(ds.date.map(str))
else:
datetime = np.array(ds.datetime.map(str))
ohlc = np.array(
ds.data.loc[:,
['open',
'close',
'low',
'high']]
)
kline.add(
ds.code[0],
datetime,
ohlc,
mark_point=["max",
"min"],
is_datazoom_show=True,
datazoom_orient='horizontal'
)
return kline
else:
data = []
axis = []
ds = self.select_code(code)
data = []
#axis = []
if self.type[-3:] == 'day':
datetime = np.array(ds.date.map(str))
else:
datetime = np.array(ds.datetime.map(str))
ohlc = np.array(ds.data.loc[:, ['open', 'close', 'low', 'high']])
vol = np.array(ds.volume)
kline = Kline(
'{}__{}__{}'.format(code,
self.if_fq,
self.type),
width=1360,
height=700,
page_title='QUANTAXIS'
)
bar = Bar()
kline.add(self.code, datetime, ohlc,
mark_point=["max", "min"],
# is_label_show=True,
is_datazoom_show=True,
is_xaxis_show=False,
# is_toolbox_show=True,
tooltip_formatter='{b}:{c}', # kline_formater,
# is_more_utils=True,
datazoom_orient='horizontal')
bar.add(
self.code,
datetime,
vol,
is_datazoom_show=True,
datazoom_xaxis_index=[0,
1]
)
grid = Grid(width=1360, height=700, page_title='QUANTAXIS')
grid.add(bar, grid_top="80%")
grid.add(kline, grid_bottom="30%")
return grid | [
"plot",
"the",
"market_data"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L680-L769 | [
"def",
"kline_echarts",
"(",
"self",
",",
"code",
"=",
"None",
")",
":",
"def",
"kline_formater",
"(",
"param",
")",
":",
"return",
"param",
".",
"name",
"+",
"':'",
"+",
"vars",
"(",
"param",
")",
"if",
"code",
"is",
"None",
":",
"path_name",
"=",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.query | 查询data | QUANTAXIS/QAData/base_datastruct.py | def query(self, context):
"""
查询data
"""
try:
return self.data.query(context)
except pd.core.computation.ops.UndefinedVariableError:
print('QA CANNOT QUERY THIS {}'.format(context))
pass | def query(self, context):
"""
查询data
"""
try:
return self.data.query(context)
except pd.core.computation.ops.UndefinedVariableError:
print('QA CANNOT QUERY THIS {}'.format(context))
pass | [
"查询data"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L791-L800 | [
"def",
"query",
"(",
"self",
",",
"context",
")",
":",
"try",
":",
"return",
"self",
".",
"data",
".",
"query",
"(",
"context",
")",
"except",
"pd",
".",
"core",
".",
"computation",
".",
"ops",
".",
"UndefinedVariableError",
":",
"print",
"(",
"'QA CAN... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.groupby | 仿dataframe的groupby写法,但控制了by的code和datetime
Keyword Arguments:
by {[type]} -- [description] (default: {None})
axis {int} -- [description] (default: {0})
level {[type]} -- [description] (default: {None})
as_index {bool} -- [description] (default: {True})
sort {bool} -- [description] (default: {True})
group_keys {bool} -- [description] (default: {True})
squeeze {bool} -- [description] (default: {False})
observed {bool} -- [description] (default: {False})
Returns:
[type] -- [description] | QUANTAXIS/QAData/base_datastruct.py | def groupby(
self,
by=None,
axis=0,
level=None,
as_index=True,
sort=False,
group_keys=False,
squeeze=False,
**kwargs
):
"""仿dataframe的groupby写法,但控制了by的code和datetime
Keyword Arguments:
by {[type]} -- [description] (default: {None})
axis {int} -- [description] (default: {0})
level {[type]} -- [description] (default: {None})
as_index {bool} -- [description] (default: {True})
sort {bool} -- [description] (default: {True})
group_keys {bool} -- [description] (default: {True})
squeeze {bool} -- [description] (default: {False})
observed {bool} -- [description] (default: {False})
Returns:
[type] -- [description]
"""
if by == self.index.names[1]:
by = None
level = 1
elif by == self.index.names[0]:
by = None
level = 0
return self.data.groupby(
by=by,
axis=axis,
level=level,
as_index=as_index,
sort=sort,
group_keys=group_keys,
squeeze=squeeze
) | def groupby(
self,
by=None,
axis=0,
level=None,
as_index=True,
sort=False,
group_keys=False,
squeeze=False,
**kwargs
):
"""仿dataframe的groupby写法,但控制了by的code和datetime
Keyword Arguments:
by {[type]} -- [description] (default: {None})
axis {int} -- [description] (default: {0})
level {[type]} -- [description] (default: {None})
as_index {bool} -- [description] (default: {True})
sort {bool} -- [description] (default: {True})
group_keys {bool} -- [description] (default: {True})
squeeze {bool} -- [description] (default: {False})
observed {bool} -- [description] (default: {False})
Returns:
[type] -- [description]
"""
if by == self.index.names[1]:
by = None
level = 1
elif by == self.index.names[0]:
by = None
level = 0
return self.data.groupby(
by=by,
axis=axis,
level=level,
as_index=as_index,
sort=sort,
group_keys=group_keys,
squeeze=squeeze
) | [
"仿dataframe的groupby写法",
"但控制了by的code和datetime"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L802-L843 | [
"def",
"groupby",
"(",
"self",
",",
"by",
"=",
"None",
",",
"axis",
"=",
"0",
",",
"level",
"=",
"None",
",",
"as_index",
"=",
"True",
",",
"sort",
"=",
"False",
",",
"group_keys",
"=",
"False",
",",
"squeeze",
"=",
"False",
",",
"*",
"*",
"kwarg... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.new | 创建一个新的DataStruct
data 默认是self.data
🛠todo 没有这个?? inplace 是否是对于原类的修改 ?? | QUANTAXIS/QAData/base_datastruct.py | def new(self, data=None, dtype=None, if_fq=None):
"""
创建一个新的DataStruct
data 默认是self.data
🛠todo 没有这个?? inplace 是否是对于原类的修改 ??
"""
data = self.data if data is None else data
dtype = self.type if dtype is None else dtype
if_fq = self.if_fq if if_fq is None else if_fq
temp = copy(self)
temp.__init__(data, dtype, if_fq)
return temp | def new(self, data=None, dtype=None, if_fq=None):
"""
创建一个新的DataStruct
data 默认是self.data
🛠todo 没有这个?? inplace 是否是对于原类的修改 ??
"""
data = self.data if data is None else data
dtype = self.type if dtype is None else dtype
if_fq = self.if_fq if if_fq is None else if_fq
temp = copy(self)
temp.__init__(data, dtype, if_fq)
return temp | [
"创建一个新的DataStruct",
"data",
"默认是self",
".",
"data",
"🛠todo",
"没有这个??",
"inplace",
"是否是对于原类的修改",
"??"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L845-L858 | [
"def",
"new",
"(",
"self",
",",
"data",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"if_fq",
"=",
"None",
")",
":",
"data",
"=",
"self",
".",
"data",
"if",
"data",
"is",
"None",
"else",
"data",
"dtype",
"=",
"self",
".",
"type",
"if",
"dtype",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.reindex | reindex
Arguments:
ind {[type]} -- [description]
Raises:
RuntimeError -- [description]
RuntimeError -- [description]
Returns:
[type] -- [description] | QUANTAXIS/QAData/base_datastruct.py | def reindex(self, ind):
"""reindex
Arguments:
ind {[type]} -- [description]
Raises:
RuntimeError -- [description]
RuntimeError -- [description]
Returns:
[type] -- [description]
"""
if isinstance(ind, pd.MultiIndex):
try:
return self.new(self.data.reindex(ind))
except:
raise RuntimeError('QADATASTRUCT ERROR: CANNOT REINDEX')
else:
raise RuntimeError(
'QADATASTRUCT ERROR: ONLY ACCEPT MULTI-INDEX FORMAT'
) | def reindex(self, ind):
"""reindex
Arguments:
ind {[type]} -- [description]
Raises:
RuntimeError -- [description]
RuntimeError -- [description]
Returns:
[type] -- [description]
"""
if isinstance(ind, pd.MultiIndex):
try:
return self.new(self.data.reindex(ind))
except:
raise RuntimeError('QADATASTRUCT ERROR: CANNOT REINDEX')
else:
raise RuntimeError(
'QADATASTRUCT ERROR: ONLY ACCEPT MULTI-INDEX FORMAT'
) | [
"reindex"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L863-L885 | [
"def",
"reindex",
"(",
"self",
",",
"ind",
")",
":",
"if",
"isinstance",
"(",
"ind",
",",
"pd",
".",
"MultiIndex",
")",
":",
"try",
":",
"return",
"self",
".",
"new",
"(",
"self",
".",
"data",
".",
"reindex",
"(",
"ind",
")",
")",
"except",
":",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.to_json | 转换DataStruct为json | QUANTAXIS/QAData/base_datastruct.py | def to_json(self):
"""
转换DataStruct为json
"""
data = self.data
if self.type[-3:] != 'min':
data = self.data.assign(datetime= self.datetime)
return QA_util_to_json_from_pandas(data.reset_index()) | def to_json(self):
"""
转换DataStruct为json
"""
data = self.data
if self.type[-3:] != 'min':
data = self.data.assign(datetime= self.datetime)
return QA_util_to_json_from_pandas(data.reset_index()) | [
"转换DataStruct为json"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L965-L973 | [
"def",
"to_json",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"data",
"if",
"self",
".",
"type",
"[",
"-",
"3",
":",
"]",
"!=",
"'min'",
":",
"data",
"=",
"self",
".",
"data",
".",
"assign",
"(",
"datetime",
"=",
"self",
".",
"datetime",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.to_hdf | IO --> hdf5 | QUANTAXIS/QAData/base_datastruct.py | def to_hdf(self, place, name):
'IO --> hdf5'
self.data.to_hdf(place, name)
return place, name | def to_hdf(self, place, name):
'IO --> hdf5'
self.data.to_hdf(place, name)
return place, name | [
"IO",
"--",
">",
"hdf5"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L993-L996 | [
"def",
"to_hdf",
"(",
"self",
",",
"place",
",",
"name",
")",
":",
"self",
".",
"data",
".",
"to_hdf",
"(",
"place",
",",
"name",
")",
"return",
"place",
",",
"name"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.is_same | 判断是否相同 | QUANTAXIS/QAData/base_datastruct.py | def is_same(self, DataStruct):
"""
判断是否相同
"""
if self.type == DataStruct.type and self.if_fq == DataStruct.if_fq:
return True
else:
return False | def is_same(self, DataStruct):
"""
判断是否相同
"""
if self.type == DataStruct.type and self.if_fq == DataStruct.if_fq:
return True
else:
return False | [
"判断是否相同"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L998-L1005 | [
"def",
"is_same",
"(",
"self",
",",
"DataStruct",
")",
":",
"if",
"self",
".",
"type",
"==",
"DataStruct",
".",
"type",
"and",
"self",
".",
"if_fq",
"==",
"DataStruct",
".",
"if_fq",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.splits | 将一个DataStruct按code分解为N个DataStruct | QUANTAXIS/QAData/base_datastruct.py | def splits(self):
"""
将一个DataStruct按code分解为N个DataStruct
"""
return list(map(lambda x: self.select_code(x), self.code)) | def splits(self):
"""
将一个DataStruct按code分解为N个DataStruct
"""
return list(map(lambda x: self.select_code(x), self.code)) | [
"将一个DataStruct按code分解为N个DataStruct"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L1007-L1011 | [
"def",
"splits",
"(",
"self",
")",
":",
"return",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"self",
".",
"select_code",
"(",
"x",
")",
",",
"self",
".",
"code",
")",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.add_func | QADATASTRUCT的指标/函数apply入口
Arguments:
func {[type]} -- [description]
Returns:
[type] -- [description] | QUANTAXIS/QAData/base_datastruct.py | def add_func(self, func, *arg, **kwargs):
"""QADATASTRUCT的指标/函数apply入口
Arguments:
func {[type]} -- [description]
Returns:
[type] -- [description]
"""
return self.groupby(level=1, sort=False).apply(func, *arg, **kwargs) | def add_func(self, func, *arg, **kwargs):
"""QADATASTRUCT的指标/函数apply入口
Arguments:
func {[type]} -- [description]
Returns:
[type] -- [description]
"""
return self.groupby(level=1, sort=False).apply(func, *arg, **kwargs) | [
"QADATASTRUCT的指标",
"/",
"函数apply入口"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L1029-L1039 | [
"def",
"add_func",
"(",
"self",
",",
"func",
",",
"*",
"arg",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"groupby",
"(",
"level",
"=",
"1",
",",
"sort",
"=",
"False",
")",
".",
"apply",
"(",
"func",
",",
"*",
"arg",
",",
"*",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.get_data | 获取不同格式的数据
Arguments:
columns {[type]} -- [description]
Keyword Arguments:
type {str} -- [description] (default: {'ndarray'})
with_index {bool} -- [description] (default: {False})
Returns:
[type] -- [description] | QUANTAXIS/QAData/base_datastruct.py | def get_data(self, columns, type='ndarray', with_index=False):
"""获取不同格式的数据
Arguments:
columns {[type]} -- [description]
Keyword Arguments:
type {str} -- [description] (default: {'ndarray'})
with_index {bool} -- [description] (default: {False})
Returns:
[type] -- [description]
"""
res = self.select_columns(columns)
if type == 'ndarray':
if with_index:
return res.reset_index().values
else:
return res.values
elif type == 'list':
if with_index:
return res.reset_index().values.tolist()
else:
return res.values.tolist()
elif type == 'dataframe':
if with_index:
return res.reset_index()
else:
return res | def get_data(self, columns, type='ndarray', with_index=False):
"""获取不同格式的数据
Arguments:
columns {[type]} -- [description]
Keyword Arguments:
type {str} -- [description] (default: {'ndarray'})
with_index {bool} -- [description] (default: {False})
Returns:
[type] -- [description]
"""
res = self.select_columns(columns)
if type == 'ndarray':
if with_index:
return res.reset_index().values
else:
return res.values
elif type == 'list':
if with_index:
return res.reset_index().values.tolist()
else:
return res.values.tolist()
elif type == 'dataframe':
if with_index:
return res.reset_index()
else:
return res | [
"获取不同格式的数据"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L1052-L1081 | [
"def",
"get_data",
"(",
"self",
",",
"columns",
",",
"type",
"=",
"'ndarray'",
",",
"with_index",
"=",
"False",
")",
":",
"res",
"=",
"self",
".",
"select_columns",
"(",
"columns",
")",
"if",
"type",
"==",
"'ndarray'",
":",
"if",
"with_index",
":",
"re... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.pivot | 增加对于多列的支持 | QUANTAXIS/QAData/base_datastruct.py | def pivot(self, column_):
"""增加对于多列的支持"""
if isinstance(column_, str):
try:
return self.data.reset_index().pivot(
index='datetime',
columns='code',
values=column_
)
except:
return self.data.reset_index().pivot(
index='date',
columns='code',
values=column_
)
elif isinstance(column_, list):
try:
return self.data.reset_index().pivot_table(
index='datetime',
columns='code',
values=column_
)
except:
return self.data.reset_index().pivot_table(
index='date',
columns='code',
values=column_
) | def pivot(self, column_):
"""增加对于多列的支持"""
if isinstance(column_, str):
try:
return self.data.reset_index().pivot(
index='datetime',
columns='code',
values=column_
)
except:
return self.data.reset_index().pivot(
index='date',
columns='code',
values=column_
)
elif isinstance(column_, list):
try:
return self.data.reset_index().pivot_table(
index='datetime',
columns='code',
values=column_
)
except:
return self.data.reset_index().pivot_table(
index='date',
columns='code',
values=column_
) | [
"增加对于多列的支持"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L1083-L1110 | [
"def",
"pivot",
"(",
"self",
",",
"column_",
")",
":",
"if",
"isinstance",
"(",
"column_",
",",
"str",
")",
":",
"try",
":",
"return",
"self",
".",
"data",
".",
"reset_index",
"(",
")",
".",
"pivot",
"(",
"index",
"=",
"'datetime'",
",",
"columns",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.selects | 选择code,start,end
如果end不填写,默认获取到结尾
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复 | QUANTAXIS/QAData/base_datastruct.py | def selects(self, code, start, end=None):
"""
选择code,start,end
如果end不填写,默认获取到结尾
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复
"""
def _selects(code, start, end):
if end is not None:
return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), code), :]
else:
return self.data.loc[(slice(pd.Timestamp(start), None), code), :]
try:
return self.new(_selects(code, start, end), self.type, self.if_fq)
except:
raise ValueError(
'QA CANNOT GET THIS CODE {}/START {}/END{} '.format(
code,
start,
end
)
) | def selects(self, code, start, end=None):
"""
选择code,start,end
如果end不填写,默认获取到结尾
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复
"""
def _selects(code, start, end):
if end is not None:
return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), code), :]
else:
return self.data.loc[(slice(pd.Timestamp(start), None), code), :]
try:
return self.new(_selects(code, start, end), self.type, self.if_fq)
except:
raise ValueError(
'QA CANNOT GET THIS CODE {}/START {}/END{} '.format(
code,
start,
end
)
) | [
"选择code",
"start",
"end"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L1112-L1146 | [
"def",
"selects",
"(",
"self",
",",
"code",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"def",
"_selects",
"(",
"code",
",",
"start",
",",
"end",
")",
":",
"if",
"end",
"is",
"not",
"None",
":",
"return",
"self",
".",
"data",
".",
"loc",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.select_time | 选择起始时间
如果end不填写,默认获取到结尾
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复 | QUANTAXIS/QAData/base_datastruct.py | def select_time(self, start, end=None):
"""
选择起始时间
如果end不填写,默认获取到结尾
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复
"""
def _select_time(start, end):
if end is not None:
return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), slice(None)), :]
else:
return self.data.loc[(slice(pd.Timestamp(start), None), slice(None)), :]
try:
return self.new(_select_time(start, end), self.type, self.if_fq)
except:
raise ValueError(
'QA CANNOT GET THIS START {}/END{} '.format(start,
end)
) | def select_time(self, start, end=None):
"""
选择起始时间
如果end不填写,默认获取到结尾
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复
"""
def _select_time(start, end):
if end is not None:
return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), slice(None)), :]
else:
return self.data.loc[(slice(pd.Timestamp(start), None), slice(None)), :]
try:
return self.new(_select_time(start, end), self.type, self.if_fq)
except:
raise ValueError(
'QA CANNOT GET THIS START {}/END{} '.format(start,
end)
) | [
"选择起始时间",
"如果end不填写",
"默认获取到结尾"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L1148-L1178 | [
"def",
"select_time",
"(",
"self",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"def",
"_select_time",
"(",
"start",
",",
"end",
")",
":",
"if",
"end",
"is",
"not",
"None",
":",
"return",
"self",
".",
"data",
".",
"loc",
"[",
"(",
"slice",
"(... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.select_day | 选取日期(一般用于分钟线)
Arguments:
day {[type]} -- [description]
Raises:
ValueError -- [description]
Returns:
[type] -- [description] | QUANTAXIS/QAData/base_datastruct.py | def select_day(self, day):
"""选取日期(一般用于分钟线)
Arguments:
day {[type]} -- [description]
Raises:
ValueError -- [description]
Returns:
[type] -- [description]
"""
def _select_day(day):
return self.data.loc[day, slice(None)]
try:
return self.new(_select_day(day), self.type, self.if_fq)
except:
raise ValueError('QA CANNOT GET THIS Day {} '.format(day)) | def select_day(self, day):
"""选取日期(一般用于分钟线)
Arguments:
day {[type]} -- [description]
Raises:
ValueError -- [description]
Returns:
[type] -- [description]
"""
def _select_day(day):
return self.data.loc[day, slice(None)]
try:
return self.new(_select_day(day), self.type, self.if_fq)
except:
raise ValueError('QA CANNOT GET THIS Day {} '.format(day)) | [
"选取日期",
"(",
"一般用于分钟线",
")"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L1180-L1199 | [
"def",
"select_day",
"(",
"self",
",",
"day",
")",
":",
"def",
"_select_day",
"(",
"day",
")",
":",
"return",
"self",
".",
"data",
".",
"loc",
"[",
"day",
",",
"slice",
"(",
"None",
")",
"]",
"try",
":",
"return",
"self",
".",
"new",
"(",
"_selec... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.select_month | 选择月份
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复 | QUANTAXIS/QAData/base_datastruct.py | def select_month(self, month):
"""
选择月份
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复
"""
def _select_month(month):
return self.data.loc[month, slice(None)]
try:
return self.new(_select_month(month), self.type, self.if_fq)
except:
raise ValueError('QA CANNOT GET THIS Month {} '.format(month)) | def select_month(self, month):
"""
选择月份
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复
"""
def _select_month(month):
return self.data.loc[month, slice(None)]
try:
return self.new(_select_month(month), self.type, self.if_fq)
except:
raise ValueError('QA CANNOT GET THIS Month {} '.format(month)) | [
"选择月份"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L1201-L1224 | [
"def",
"select_month",
"(",
"self",
",",
"month",
")",
":",
"def",
"_select_month",
"(",
"month",
")",
":",
"return",
"self",
".",
"data",
".",
"loc",
"[",
"month",
",",
"slice",
"(",
"None",
")",
"]",
"try",
":",
"return",
"self",
".",
"new",
"(",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.select_code | 选择股票
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复 | QUANTAXIS/QAData/base_datastruct.py | def select_code(self, code):
"""
选择股票
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复
"""
def _select_code(code):
return self.data.loc[(slice(None), code), :]
try:
return self.new(_select_code(code), self.type, self.if_fq)
except:
raise ValueError('QA CANNOT FIND THIS CODE {}'.format(code)) | def select_code(self, code):
"""
选择股票
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复
"""
def _select_code(code):
return self.data.loc[(slice(None), code), :]
try:
return self.new(_select_code(code), self.type, self.if_fq)
except:
raise ValueError('QA CANNOT FIND THIS CODE {}'.format(code)) | [
"选择股票"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L1226-L1249 | [
"def",
"select_code",
"(",
"self",
",",
"code",
")",
":",
"def",
"_select_code",
"(",
"code",
")",
":",
"return",
"self",
".",
"data",
".",
"loc",
"[",
"(",
"slice",
"(",
"None",
")",
",",
"code",
")",
",",
":",
"]",
"try",
":",
"return",
"self",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | _quotation_base.get_bar | 获取一个bar的数据
返回一个series
如果不存在,raise ValueError | QUANTAXIS/QAData/base_datastruct.py | def get_bar(self, code, time):
"""
获取一个bar的数据
返回一个series
如果不存在,raise ValueError
"""
try:
return self.data.loc[(pd.Timestamp(time), code)]
except:
raise ValueError(
'DATASTRUCT CURRENTLY CANNOT FIND THIS BAR WITH {} {}'.format(
code,
time
)
) | def get_bar(self, code, time):
"""
获取一个bar的数据
返回一个series
如果不存在,raise ValueError
"""
try:
return self.data.loc[(pd.Timestamp(time), code)]
except:
raise ValueError(
'DATASTRUCT CURRENTLY CANNOT FIND THIS BAR WITH {} {}'.format(
code,
time
)
) | [
"获取一个bar的数据",
"返回一个series",
"如果不存在",
"raise",
"ValueError"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L1264-L1278 | [
"def",
"get_bar",
"(",
"self",
",",
"code",
",",
"time",
")",
":",
"try",
":",
"return",
"self",
".",
"data",
".",
"loc",
"[",
"(",
"pd",
".",
"Timestamp",
"(",
"time",
")",
",",
"code",
")",
"]",
"except",
":",
"raise",
"ValueError",
"(",
"'DATA... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_trans_stock_min | 将天软本地数据导入 QA 数据库
:param client:
:param ui_log:
:param ui_progress:
:param data_path: 存放天软数据的路径,默认文件名格式为类似 "SH600000.csv" 格式 | QUANTAXIS/QASU/trans_ss.py | def QA_SU_trans_stock_min(client=DATABASE, ui_log=None, ui_progress=None,
data_path: str = "D:\\skysoft\\", type_="1min"):
"""
将天软本地数据导入 QA 数据库
:param client:
:param ui_log:
:param ui_progress:
:param data_path: 存放天软数据的路径,默认文件名格式为类似 "SH600000.csv" 格式
"""
code_list = list(map(lambda x: x[2:8], os.listdir(data_path)))
coll = client.stock_min
coll.create_index([
("code", pymongo.ASCENDING),
("time_stamp", pymongo.ASCENDING),
("date_stamp", pymongo.ASCENDING),
])
err = []
def __transform_ss_to_qa(file_path: str = None, end_time: str = None, type_="1min"):
"""
导入相应 csv 文件,并处理格式
1. 这里默认为天软数据格式:
time symbol open high low close volume amount
0 2013-08-01 09:31:00 SH600000 7.92 7.92 7.87 7.91 518700 4105381
...
2. 与 QUANTAXIS.QAFetch.QATdx.QA_fetch_get_stock_min 获取数据进行匹配,具体处理详见相应源码
open close high low vol amount ...
datetime
2018-12-03 09:31:00 10.99 10.90 10.99 10.90 2.211700e+06 2.425626e+07 ...
"""
if file_path is None:
raise ValueError("输入文件地址")
df_local = pd.read_csv(file_path)
# 列名处理
df_local = df_local.rename(
columns={"time": "datetime", "volume": "vol"})
# 格式处理
df_local = df_local.assign(
code=df_local.symbol.map(str).str.slice(2),
date=df_local.datetime.map(str).str.slice(0, 10),
).drop(
"symbol", axis=1)
df_local = df_local.assign(
datetime=pd.to_datetime(df_local.datetime),
date_stamp=df_local.date.apply(lambda x: QA_util_date_stamp(x)),
time_stamp=df_local.datetime.apply(
lambda x: QA_util_time_stamp(x)),
type="1min",
).set_index(
"datetime", drop=False)
df_local = df_local.loc[slice(None, end_time)]
df_local["datetime"] = df_local["datetime"].map(str)
df_local["type"] = type_
return df_local[[
"open",
"close",
"high",
"low",
"vol",
"amount",
"datetime",
"code",
"date",
"date_stamp",
"time_stamp",
"type",
]]
def __saving_work(code, coll):
QA_util_log_info(
"##JOB03 Now Saving STOCK_MIN ==== {}".format(code), ui_log=ui_log)
try:
col_filter = {"code": code, "type": type_}
ref_ = coll.find(col_filter)
end_time = ref_[0]['datetime'] # 本地存储分钟数据最早的时间
filename = "SH"+code+".csv" if code[0] == '6' else "SZ"+code+".csv"
__data = __transform_ss_to_qa(
data_path+filename, end_time, type_) # 加入 end_time, 避免出现数据重复
QA_util_log_info(
"##JOB03.{} Now Saving {} from {} to {} == {}".format(
type_,
code,
__data['datetime'].iloc[0],
__data['datetime'].iloc[-1],
type_,
),
ui_log=ui_log,
)
if len(__data) > 1:
coll.insert_many(
QA_util_to_json_from_pandas(__data)[1::])
except Exception as e:
QA_util_log_info(e, ui_log=ui_log)
err.append(code)
QA_util_log_info(err, ui_log=ui_log)
executor = ThreadPoolExecutor(max_workers=4)
res = {
executor.submit(__saving_work, code_list[i_], coll)
for i_ in range(len(code_list))
}
count = 0
for i_ in concurrent.futures.as_completed(res):
strProgress = "TRANSFORM PROGRESS {} ".format(
str(float(count / len(code_list) * 100))[0:4] + "%")
intProgress = int(count / len(code_list) * 10000.0)
count = count + 1
if len(err) < 1:
QA_util_log_info("SUCCESS", ui_log=ui_log)
else:
QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
QA_util_log_info(err, ui_log=ui_log)
if len(err) < 1:
QA_util_log_info("SUCCESS", ui_log=ui_log)
else:
QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
QA_util_log_info(err, ui_log=ui_log) | def QA_SU_trans_stock_min(client=DATABASE, ui_log=None, ui_progress=None,
data_path: str = "D:\\skysoft\\", type_="1min"):
"""
将天软本地数据导入 QA 数据库
:param client:
:param ui_log:
:param ui_progress:
:param data_path: 存放天软数据的路径,默认文件名格式为类似 "SH600000.csv" 格式
"""
code_list = list(map(lambda x: x[2:8], os.listdir(data_path)))
coll = client.stock_min
coll.create_index([
("code", pymongo.ASCENDING),
("time_stamp", pymongo.ASCENDING),
("date_stamp", pymongo.ASCENDING),
])
err = []
def __transform_ss_to_qa(file_path: str = None, end_time: str = None, type_="1min"):
"""
导入相应 csv 文件,并处理格式
1. 这里默认为天软数据格式:
time symbol open high low close volume amount
0 2013-08-01 09:31:00 SH600000 7.92 7.92 7.87 7.91 518700 4105381
...
2. 与 QUANTAXIS.QAFetch.QATdx.QA_fetch_get_stock_min 获取数据进行匹配,具体处理详见相应源码
open close high low vol amount ...
datetime
2018-12-03 09:31:00 10.99 10.90 10.99 10.90 2.211700e+06 2.425626e+07 ...
"""
if file_path is None:
raise ValueError("输入文件地址")
df_local = pd.read_csv(file_path)
# 列名处理
df_local = df_local.rename(
columns={"time": "datetime", "volume": "vol"})
# 格式处理
df_local = df_local.assign(
code=df_local.symbol.map(str).str.slice(2),
date=df_local.datetime.map(str).str.slice(0, 10),
).drop(
"symbol", axis=1)
df_local = df_local.assign(
datetime=pd.to_datetime(df_local.datetime),
date_stamp=df_local.date.apply(lambda x: QA_util_date_stamp(x)),
time_stamp=df_local.datetime.apply(
lambda x: QA_util_time_stamp(x)),
type="1min",
).set_index(
"datetime", drop=False)
df_local = df_local.loc[slice(None, end_time)]
df_local["datetime"] = df_local["datetime"].map(str)
df_local["type"] = type_
return df_local[[
"open",
"close",
"high",
"low",
"vol",
"amount",
"datetime",
"code",
"date",
"date_stamp",
"time_stamp",
"type",
]]
def __saving_work(code, coll):
QA_util_log_info(
"##JOB03 Now Saving STOCK_MIN ==== {}".format(code), ui_log=ui_log)
try:
col_filter = {"code": code, "type": type_}
ref_ = coll.find(col_filter)
end_time = ref_[0]['datetime'] # 本地存储分钟数据最早的时间
filename = "SH"+code+".csv" if code[0] == '6' else "SZ"+code+".csv"
__data = __transform_ss_to_qa(
data_path+filename, end_time, type_) # 加入 end_time, 避免出现数据重复
QA_util_log_info(
"##JOB03.{} Now Saving {} from {} to {} == {}".format(
type_,
code,
__data['datetime'].iloc[0],
__data['datetime'].iloc[-1],
type_,
),
ui_log=ui_log,
)
if len(__data) > 1:
coll.insert_many(
QA_util_to_json_from_pandas(__data)[1::])
except Exception as e:
QA_util_log_info(e, ui_log=ui_log)
err.append(code)
QA_util_log_info(err, ui_log=ui_log)
executor = ThreadPoolExecutor(max_workers=4)
res = {
executor.submit(__saving_work, code_list[i_], coll)
for i_ in range(len(code_list))
}
count = 0
for i_ in concurrent.futures.as_completed(res):
strProgress = "TRANSFORM PROGRESS {} ".format(
str(float(count / len(code_list) * 100))[0:4] + "%")
intProgress = int(count / len(code_list) * 10000.0)
count = count + 1
if len(err) < 1:
QA_util_log_info("SUCCESS", ui_log=ui_log)
else:
QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
QA_util_log_info(err, ui_log=ui_log)
if len(err) < 1:
QA_util_log_info("SUCCESS", ui_log=ui_log)
else:
QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
QA_util_log_info(err, ui_log=ui_log) | [
"将天软本地数据导入",
"QA",
"数据库",
":",
"param",
"client",
":",
":",
"param",
"ui_log",
":",
":",
"param",
"ui_progress",
":",
":",
"param",
"data_path",
":",
"存放天软数据的路径,默认文件名格式为类似",
"SH600000",
".",
"csv",
"格式"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/trans_ss.py#L21-L145 | [
"def",
"QA_SU_trans_stock_min",
"(",
"client",
"=",
"DATABASE",
",",
"ui_log",
"=",
"None",
",",
"ui_progress",
"=",
"None",
",",
"data_path",
":",
"str",
"=",
"\"D:\\\\skysoft\\\\\"",
",",
"type_",
"=",
"\"1min\"",
")",
":",
"code_list",
"=",
"list",
"(",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | get_best_ip_by_real_data_fetch | 用特定的数据获取函数测试数据获得的时间,从而选择下载数据最快的服务器ip
默认使用特定品种1min的方式的获取 | QUANTAXIS/QAFetch/QATdx.py | def get_best_ip_by_real_data_fetch(_type='stock'):
"""
用特定的数据获取函数测试数据获得的时间,从而选择下载数据最快的服务器ip
默认使用特定品种1min的方式的获取
"""
from QUANTAXIS.QAUtil.QADate import QA_util_today_str
import time
#找到前两天的有效交易日期
pre_trade_date=QA_util_get_real_date(QA_util_today_str())
pre_trade_date=QA_util_get_real_date(pre_trade_date)
# 某个函数获取的耗时测试
def get_stock_data_by_ip(ips):
start=time.time()
try:
QA_fetch_get_stock_transaction('000001',pre_trade_date,pre_trade_date,2,ips['ip'],ips['port'])
end=time.time()
return end-start
except:
return 9999
def get_future_data_by_ip(ips):
start=time.time()
try:
QA_fetch_get_future_transaction('RBL8',pre_trade_date,pre_trade_date,2,ips['ip'],ips['port'])
end=time.time()
return end-start
except:
return 9999
func,ip_list=0,0
if _type=='stock':
func,ip_list=get_stock_data_by_ip,stock_ip_list
else:
func,ip_list=get_future_data_by_ip,future_ip_list
from pathos.multiprocessing import Pool
def multiMap(func,sequence):
res=[]
pool=Pool(4)
for i in sequence:
res.append(pool.apply_async(func,(i,)))
pool.close()
pool.join()
return list(map(lambda x:x.get(),res))
res=multiMap(func,ip_list)
index=res.index(min(res))
return ip_list[index] | def get_best_ip_by_real_data_fetch(_type='stock'):
"""
用特定的数据获取函数测试数据获得的时间,从而选择下载数据最快的服务器ip
默认使用特定品种1min的方式的获取
"""
from QUANTAXIS.QAUtil.QADate import QA_util_today_str
import time
#找到前两天的有效交易日期
pre_trade_date=QA_util_get_real_date(QA_util_today_str())
pre_trade_date=QA_util_get_real_date(pre_trade_date)
# 某个函数获取的耗时测试
def get_stock_data_by_ip(ips):
start=time.time()
try:
QA_fetch_get_stock_transaction('000001',pre_trade_date,pre_trade_date,2,ips['ip'],ips['port'])
end=time.time()
return end-start
except:
return 9999
def get_future_data_by_ip(ips):
start=time.time()
try:
QA_fetch_get_future_transaction('RBL8',pre_trade_date,pre_trade_date,2,ips['ip'],ips['port'])
end=time.time()
return end-start
except:
return 9999
func,ip_list=0,0
if _type=='stock':
func,ip_list=get_stock_data_by_ip,stock_ip_list
else:
func,ip_list=get_future_data_by_ip,future_ip_list
from pathos.multiprocessing import Pool
def multiMap(func,sequence):
res=[]
pool=Pool(4)
for i in sequence:
res.append(pool.apply_async(func,(i,)))
pool.close()
pool.join()
return list(map(lambda x:x.get(),res))
res=multiMap(func,ip_list)
index=res.index(min(res))
return ip_list[index] | [
"用特定的数据获取函数测试数据获得的时间",
"从而选择下载数据最快的服务器ip",
"默认使用特定品种1min的方式的获取"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L158-L206 | [
"def",
"get_best_ip_by_real_data_fetch",
"(",
"_type",
"=",
"'stock'",
")",
":",
"from",
"QUANTAXIS",
".",
"QAUtil",
".",
"QADate",
"import",
"QA_util_today_str",
"import",
"time",
"#找到前两天的有效交易日期",
"pre_trade_date",
"=",
"QA_util_get_real_date",
"(",
"QA_util_today_str"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | get_ip_list_by_multi_process_ping | 根据ping排序返回可用的ip列表
2019 03 31 取消参数filename
:param ip_list: ip列表
:param n: 最多返回的ip数量, 当可用ip数量小于n,返回所有可用的ip;n=0时,返回所有可用ip
:param _type: ip类型
:return: 可以ping通的ip列表 | QUANTAXIS/QAFetch/QATdx.py | def get_ip_list_by_multi_process_ping(ip_list=[], n=0, _type='stock'):
''' 根据ping排序返回可用的ip列表
2019 03 31 取消参数filename
:param ip_list: ip列表
:param n: 最多返回的ip数量, 当可用ip数量小于n,返回所有可用的ip;n=0时,返回所有可用ip
:param _type: ip类型
:return: 可以ping通的ip列表
'''
cache = QA_util_cache()
results = cache.get(_type)
if results:
# read the data from cache
print('loading ip list from {} cache.'.format(_type))
else:
ips = [(x['ip'], x['port'], _type) for x in ip_list]
ps = Parallelism()
ps.add(ping, ips)
ps.run()
data = list(ps.get_results())
results = []
for i in range(len(data)):
# 删除ping不通的数据
if data[i] < datetime.timedelta(0, 9, 0):
results.append((data[i], ip_list[i]))
# 按照ping值从小大大排序
results = [x[1] for x in sorted(results, key=lambda x: x[0])]
if _type:
# store the data as binary data stream
cache.set(_type, results, age=86400)
print('saving ip list to {} cache {}.'.format(_type, len(results)))
if len(results) > 0:
if n == 0 and len(results) > 0:
return results
else:
return results[:n]
else:
print('ALL IP PING TIMEOUT!')
return [{'ip': None, 'port': None}] | def get_ip_list_by_multi_process_ping(ip_list=[], n=0, _type='stock'):
''' 根据ping排序返回可用的ip列表
2019 03 31 取消参数filename
:param ip_list: ip列表
:param n: 最多返回的ip数量, 当可用ip数量小于n,返回所有可用的ip;n=0时,返回所有可用ip
:param _type: ip类型
:return: 可以ping通的ip列表
'''
cache = QA_util_cache()
results = cache.get(_type)
if results:
# read the data from cache
print('loading ip list from {} cache.'.format(_type))
else:
ips = [(x['ip'], x['port'], _type) for x in ip_list]
ps = Parallelism()
ps.add(ping, ips)
ps.run()
data = list(ps.get_results())
results = []
for i in range(len(data)):
# 删除ping不通的数据
if data[i] < datetime.timedelta(0, 9, 0):
results.append((data[i], ip_list[i]))
# 按照ping值从小大大排序
results = [x[1] for x in sorted(results, key=lambda x: x[0])]
if _type:
# store the data as binary data stream
cache.set(_type, results, age=86400)
print('saving ip list to {} cache {}.'.format(_type, len(results)))
if len(results) > 0:
if n == 0 and len(results) > 0:
return results
else:
return results[:n]
else:
print('ALL IP PING TIMEOUT!')
return [{'ip': None, 'port': None}] | [
"根据ping排序返回可用的ip列表",
"2019",
"03",
"31",
"取消参数filename"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L208-L246 | [
"def",
"get_ip_list_by_multi_process_ping",
"(",
"ip_list",
"=",
"[",
"]",
",",
"n",
"=",
"0",
",",
"_type",
"=",
"'stock'",
")",
":",
"cache",
"=",
"QA_util_cache",
"(",
")",
"results",
"=",
"cache",
".",
"get",
"(",
"_type",
")",
"if",
"results",
":"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | get_mainmarket_ip | [summary]
Arguments:
ip {[type]} -- [description]
port {[type]} -- [description]
Returns:
[type] -- [description] | QUANTAXIS/QAFetch/QATdx.py | def get_mainmarket_ip(ip, port):
"""[summary]
Arguments:
ip {[type]} -- [description]
port {[type]} -- [description]
Returns:
[type] -- [description]
"""
global best_ip
if ip is None and port is None and best_ip['stock']['ip'] is None and best_ip['stock']['port'] is None:
best_ip = select_best_ip()
ip = best_ip['stock']['ip']
port = best_ip['stock']['port']
elif ip is None and port is None and best_ip['stock']['ip'] is not None and best_ip['stock']['port'] is not None:
ip = best_ip['stock']['ip']
port = best_ip['stock']['port']
else:
pass
return ip, port | def get_mainmarket_ip(ip, port):
"""[summary]
Arguments:
ip {[type]} -- [description]
port {[type]} -- [description]
Returns:
[type] -- [description]
"""
global best_ip
if ip is None and port is None and best_ip['stock']['ip'] is None and best_ip['stock']['port'] is None:
best_ip = select_best_ip()
ip = best_ip['stock']['ip']
port = best_ip['stock']['port']
elif ip is None and port is None and best_ip['stock']['ip'] is not None and best_ip['stock']['port'] is not None:
ip = best_ip['stock']['ip']
port = best_ip['stock']['port']
else:
pass
return ip, port | [
"[",
"summary",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L276-L297 | [
"def",
"get_mainmarket_ip",
"(",
"ip",
",",
"port",
")",
":",
"global",
"best_ip",
"if",
"ip",
"is",
"None",
"and",
"port",
"is",
"None",
"and",
"best_ip",
"[",
"'stock'",
"]",
"[",
"'ip'",
"]",
"is",
"None",
"and",
"best_ip",
"[",
"'stock'",
"]",
"[... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_security_bars | 按bar长度推算数据
Arguments:
code {[type]} -- [description]
_type {[type]} -- [description]
lens {[type]} -- [description]
Keyword Arguments:
ip {[type]} -- [description] (default: {best_ip})
port {[type]} -- [description] (default: {7709})
Returns:
[type] -- [description] | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_security_bars(code, _type, lens, ip=None, port=None):
"""按bar长度推算数据
Arguments:
code {[type]} -- [description]
_type {[type]} -- [description]
lens {[type]} -- [description]
Keyword Arguments:
ip {[type]} -- [description] (default: {best_ip})
port {[type]} -- [description] (default: {7709})
Returns:
[type] -- [description]
"""
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
with api.connect(ip, port):
data = pd.concat([api.to_df(api.get_security_bars(_select_type(_type), _select_market_code(
code), code, (i - 1) * 800, 800)) for i in range(1, int(lens / 800) + 2)], axis=0)
data = data \
.drop(['year', 'month', 'day', 'hour', 'minute'], axis=1, inplace=False) \
.assign(datetime=pd.to_datetime(data['datetime']),
date=data['datetime'].apply(lambda x: str(x)[0:10]),
date_stamp=data['datetime'].apply(
lambda x: QA_util_date_stamp(x)),
time_stamp=data['datetime'].apply(
lambda x: QA_util_time_stamp(x)),
type=_type, code=str(code)) \
.set_index('datetime', drop=False, inplace=False).tail(lens)
if data is not None:
return data
else:
return None | def QA_fetch_get_security_bars(code, _type, lens, ip=None, port=None):
"""按bar长度推算数据
Arguments:
code {[type]} -- [description]
_type {[type]} -- [description]
lens {[type]} -- [description]
Keyword Arguments:
ip {[type]} -- [description] (default: {best_ip})
port {[type]} -- [description] (default: {7709})
Returns:
[type] -- [description]
"""
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
with api.connect(ip, port):
data = pd.concat([api.to_df(api.get_security_bars(_select_type(_type), _select_market_code(
code), code, (i - 1) * 800, 800)) for i in range(1, int(lens / 800) + 2)], axis=0)
data = data \
.drop(['year', 'month', 'day', 'hour', 'minute'], axis=1, inplace=False) \
.assign(datetime=pd.to_datetime(data['datetime']),
date=data['datetime'].apply(lambda x: str(x)[0:10]),
date_stamp=data['datetime'].apply(
lambda x: QA_util_date_stamp(x)),
time_stamp=data['datetime'].apply(
lambda x: QA_util_time_stamp(x)),
type=_type, code=str(code)) \
.set_index('datetime', drop=False, inplace=False).tail(lens)
if data is not None:
return data
else:
return None | [
"按bar长度推算数据"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L300-L333 | [
"def",
"QA_fetch_get_security_bars",
"(",
"code",
",",
"_type",
",",
"lens",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_mainmarket_ip",
"(",
"ip",
",",
"port",
")",
"api",
"=",
"TdxHq_API",
"(",
")",
"wit... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_stock_day | 获取日线及以上级别的数据
Arguments:
code {str:6} -- code 是一个单独的code 6位长度的str
start_date {str:10} -- 10位长度的日期 比如'2017-01-01'
end_date {str:10} -- 10位长度的日期 比如'2018-01-01'
Keyword Arguments:
if_fq {str} -- '00'/'bfq' -- 不复权 '01'/'qfq' -- 前复权 '02'/'hfq' -- 后复权 '03'/'ddqfq' -- 定点前复权 '04'/'ddhfq' --定点后复权
frequency {str} -- day/week/month/quarter/year 也可以是简写 D/W/M/Q/Y
ip {str} -- [description] (default: None) ip可以通过select_best_ip()函数重新获取
port {int} -- [description] (default: {None})
Returns:
pd.DataFrame/None -- 返回的是dataframe,如果出错比如只获取了一天,而当天停牌,返回None
Exception:
如果出现网络问题/服务器拒绝, 会出现socket:time out 尝试再次获取/更换ip即可, 本函数不做处理 | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_stock_day(code, start_date, end_date, if_fq='00', frequence='day', ip=None, port=None):
"""获取日线及以上级别的数据
Arguments:
code {str:6} -- code 是一个单独的code 6位长度的str
start_date {str:10} -- 10位长度的日期 比如'2017-01-01'
end_date {str:10} -- 10位长度的日期 比如'2018-01-01'
Keyword Arguments:
if_fq {str} -- '00'/'bfq' -- 不复权 '01'/'qfq' -- 前复权 '02'/'hfq' -- 后复权 '03'/'ddqfq' -- 定点前复权 '04'/'ddhfq' --定点后复权
frequency {str} -- day/week/month/quarter/year 也可以是简写 D/W/M/Q/Y
ip {str} -- [description] (default: None) ip可以通过select_best_ip()函数重新获取
port {int} -- [description] (default: {None})
Returns:
pd.DataFrame/None -- 返回的是dataframe,如果出错比如只获取了一天,而当天停牌,返回None
Exception:
如果出现网络问题/服务器拒绝, 会出现socket:time out 尝试再次获取/更换ip即可, 本函数不做处理
"""
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
try:
with api.connect(ip, port, time_out=0.7):
if frequence in ['day', 'd', 'D', 'DAY', 'Day']:
frequence = 9
elif frequence in ['w', 'W', 'Week', 'week']:
frequence = 5
elif frequence in ['month', 'M', 'm', 'Month']:
frequence = 6
elif frequence in ['quarter', 'Q', 'Quarter', 'q']:
frequence = 10
elif frequence in ['y', 'Y', 'year', 'Year']:
frequence = 11
start_date = str(start_date)[0:10]
today_ = datetime.date.today()
lens = QA_util_get_trade_gap(start_date, today_)
data = pd.concat([api.to_df(api.get_security_bars(frequence, _select_market_code(
code), code, (int(lens / 800) - i) * 800, 800)) for i in range(int(lens / 800) + 1)], axis=0)
# 这里的问题是: 如果只取了一天的股票,而当天停牌, 那么就直接返回None了
if len(data) < 1:
return None
data = data[data['open'] != 0]
data = data.assign(date=data['datetime'].apply(lambda x: str(x[0:10])),
code=str(code),
date_stamp=data['datetime'].apply(lambda x: QA_util_date_stamp(str(x)[0:10]))) \
.set_index('date', drop=False, inplace=False)
end_date = str(end_date)[0:10]
data = data.drop(['year', 'month', 'day', 'hour', 'minute', 'datetime'], axis=1)[
start_date:end_date]
if if_fq in ['00', 'bfq']:
return data
else:
print('CURRENTLY NOT SUPPORT REALTIME FUQUAN')
return None
# xdxr = QA_fetch_get_stock_xdxr(code)
# if if_fq in ['01','qfq']:
# return QA_data_make_qfq(data,xdxr)
# elif if_fq in ['02','hfq']:
# return QA_data_make_hfq(data,xdxr)
except Exception as e:
if isinstance(e, TypeError):
print('Tushare内置的pytdx版本和QUANTAXIS使用的pytdx 版本不同, 请重新安装pytdx以解决此问题')
print('pip uninstall pytdx')
print('pip install pytdx')
else:
print(e) | def QA_fetch_get_stock_day(code, start_date, end_date, if_fq='00', frequence='day', ip=None, port=None):
"""获取日线及以上级别的数据
Arguments:
code {str:6} -- code 是一个单独的code 6位长度的str
start_date {str:10} -- 10位长度的日期 比如'2017-01-01'
end_date {str:10} -- 10位长度的日期 比如'2018-01-01'
Keyword Arguments:
if_fq {str} -- '00'/'bfq' -- 不复权 '01'/'qfq' -- 前复权 '02'/'hfq' -- 后复权 '03'/'ddqfq' -- 定点前复权 '04'/'ddhfq' --定点后复权
frequency {str} -- day/week/month/quarter/year 也可以是简写 D/W/M/Q/Y
ip {str} -- [description] (default: None) ip可以通过select_best_ip()函数重新获取
port {int} -- [description] (default: {None})
Returns:
pd.DataFrame/None -- 返回的是dataframe,如果出错比如只获取了一天,而当天停牌,返回None
Exception:
如果出现网络问题/服务器拒绝, 会出现socket:time out 尝试再次获取/更换ip即可, 本函数不做处理
"""
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
try:
with api.connect(ip, port, time_out=0.7):
if frequence in ['day', 'd', 'D', 'DAY', 'Day']:
frequence = 9
elif frequence in ['w', 'W', 'Week', 'week']:
frequence = 5
elif frequence in ['month', 'M', 'm', 'Month']:
frequence = 6
elif frequence in ['quarter', 'Q', 'Quarter', 'q']:
frequence = 10
elif frequence in ['y', 'Y', 'year', 'Year']:
frequence = 11
start_date = str(start_date)[0:10]
today_ = datetime.date.today()
lens = QA_util_get_trade_gap(start_date, today_)
data = pd.concat([api.to_df(api.get_security_bars(frequence, _select_market_code(
code), code, (int(lens / 800) - i) * 800, 800)) for i in range(int(lens / 800) + 1)], axis=0)
# 这里的问题是: 如果只取了一天的股票,而当天停牌, 那么就直接返回None了
if len(data) < 1:
return None
data = data[data['open'] != 0]
data = data.assign(date=data['datetime'].apply(lambda x: str(x[0:10])),
code=str(code),
date_stamp=data['datetime'].apply(lambda x: QA_util_date_stamp(str(x)[0:10]))) \
.set_index('date', drop=False, inplace=False)
end_date = str(end_date)[0:10]
data = data.drop(['year', 'month', 'day', 'hour', 'minute', 'datetime'], axis=1)[
start_date:end_date]
if if_fq in ['00', 'bfq']:
return data
else:
print('CURRENTLY NOT SUPPORT REALTIME FUQUAN')
return None
# xdxr = QA_fetch_get_stock_xdxr(code)
# if if_fq in ['01','qfq']:
# return QA_data_make_qfq(data,xdxr)
# elif if_fq in ['02','hfq']:
# return QA_data_make_hfq(data,xdxr)
except Exception as e:
if isinstance(e, TypeError):
print('Tushare内置的pytdx版本和QUANTAXIS使用的pytdx 版本不同, 请重新安装pytdx以解决此问题')
print('pip uninstall pytdx')
print('pip install pytdx')
else:
print(e) | [
"获取日线及以上级别的数据"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L336-L409 | [
"def",
"QA_fetch_get_stock_day",
"(",
"code",
",",
"start_date",
",",
"end_date",
",",
"if_fq",
"=",
"'00'",
",",
"frequence",
"=",
"'day'",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_mainmarket_ip",
"(",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | for_sz | 深市代码分类
Arguments:
code {[type]} -- [description]
Returns:
[type] -- [description] | QUANTAXIS/QAFetch/QATdx.py | def for_sz(code):
"""深市代码分类
Arguments:
code {[type]} -- [description]
Returns:
[type] -- [description]
"""
if str(code)[0:2] in ['00', '30', '02']:
return 'stock_cn'
elif str(code)[0:2] in ['39']:
return 'index_cn'
elif str(code)[0:2] in ['15']:
return 'etf_cn'
elif str(code)[0:2] in ['10', '11', '12', '13']:
# 10xxxx 国债现货
# 11xxxx 债券
# 12xxxx 可转换债券
# 12xxxx 国债回购
return 'bond_cn'
elif str(code)[0:2] in ['20']:
return 'stockB_cn'
else:
return 'undefined' | def for_sz(code):
"""深市代码分类
Arguments:
code {[type]} -- [description]
Returns:
[type] -- [description]
"""
if str(code)[0:2] in ['00', '30', '02']:
return 'stock_cn'
elif str(code)[0:2] in ['39']:
return 'index_cn'
elif str(code)[0:2] in ['15']:
return 'etf_cn'
elif str(code)[0:2] in ['10', '11', '12', '13']:
# 10xxxx 国债现货
# 11xxxx 债券
# 12xxxx 可转换债券
# 12xxxx 国债回购
return 'bond_cn'
elif str(code)[0:2] in ['20']:
return 'stockB_cn'
else:
return 'undefined' | [
"深市代码分类"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L591-L617 | [
"def",
"for_sz",
"(",
"code",
")",
":",
"if",
"str",
"(",
"code",
")",
"[",
"0",
":",
"2",
"]",
"in",
"[",
"'00'",
",",
"'30'",
",",
"'02'",
"]",
":",
"return",
"'stock_cn'",
"elif",
"str",
"(",
"code",
")",
"[",
"0",
":",
"2",
"]",
"in",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_index_list | 获取指数列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
Returns:
[type] -- [description] | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_index_list(ip=None, port=None):
"""获取指数列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
Returns:
[type] -- [description]
"""
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
with api.connect(ip, port):
data = pd.concat(
[pd.concat([api.to_df(api.get_security_list(j, i * 1000)).assign(sse='sz' if j == 0 else 'sh').set_index(
['code', 'sse'], drop=False) for i in range(int(api.get_security_count(j) / 1000) + 1)], axis=0) for j
in range(2)], axis=0)
# data.code = data.code.apply(int)
sz = data.query('sse=="sz"')
sh = data.query('sse=="sh"')
sz = sz.assign(sec=sz.code.apply(for_sz))
sh = sh.assign(sec=sh.code.apply(for_sh))
return pd.concat([sz, sh]).query('sec=="index_cn"').sort_index().assign(
name=data['name'].apply(lambda x: str(x)[0:6])) | def QA_fetch_get_index_list(ip=None, port=None):
"""获取指数列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
Returns:
[type] -- [description]
"""
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
with api.connect(ip, port):
data = pd.concat(
[pd.concat([api.to_df(api.get_security_list(j, i * 1000)).assign(sse='sz' if j == 0 else 'sh').set_index(
['code', 'sse'], drop=False) for i in range(int(api.get_security_count(j) / 1000) + 1)], axis=0) for j
in range(2)], axis=0)
# data.code = data.code.apply(int)
sz = data.query('sse=="sz"')
sh = data.query('sse=="sh"')
sz = sz.assign(sec=sz.code.apply(for_sz))
sh = sh.assign(sec=sh.code.apply(for_sh))
return pd.concat([sz, sh]).query('sec=="index_cn"').sort_index().assign(
name=data['name'].apply(lambda x: str(x)[0:6])) | [
"获取指数列表"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L672-L697 | [
"def",
"QA_fetch_get_index_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_mainmarket_ip",
"(",
"ip",
",",
"port",
")",
"api",
"=",
"TdxHq_API",
"(",
")",
"with",
"api",
".",
"connect",
"(",
"ip",
",",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_stock_transaction_realtime | 实时分笔成交 包含集合竞价 buyorsell 1--sell 0--buy 2--盘前 | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_stock_transaction_realtime(code, ip=None, port=None):
'实时分笔成交 包含集合竞价 buyorsell 1--sell 0--buy 2--盘前'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
try:
with api.connect(ip, port):
data = pd.DataFrame()
data = pd.concat([api.to_df(api.get_transaction_data(
_select_market_code(str(code)), code, (2 - i) * 2000, 2000)) for i in range(3)], axis=0)
if 'value' in data.columns:
data = data.drop(['value'], axis=1)
data = data.dropna()
day = datetime.date.today()
return data.assign(date=str(day)).assign(
datetime=pd.to_datetime(data['time'].apply(lambda x: str(day) + ' ' + str(x)))) \
.assign(code=str(code)).assign(order=range(len(data.index))).set_index('datetime', drop=False,
inplace=False)
except:
return None | def QA_fetch_get_stock_transaction_realtime(code, ip=None, port=None):
'实时分笔成交 包含集合竞价 buyorsell 1--sell 0--buy 2--盘前'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
try:
with api.connect(ip, port):
data = pd.DataFrame()
data = pd.concat([api.to_df(api.get_transaction_data(
_select_market_code(str(code)), code, (2 - i) * 2000, 2000)) for i in range(3)], axis=0)
if 'value' in data.columns:
data = data.drop(['value'], axis=1)
data = data.dropna()
day = datetime.date.today()
return data.assign(date=str(day)).assign(
datetime=pd.to_datetime(data['time'].apply(lambda x: str(day) + ' ' + str(x)))) \
.assign(code=str(code)).assign(order=range(len(data.index))).set_index('datetime', drop=False,
inplace=False)
except:
return None | [
"实时分笔成交",
"包含集合竞价",
"buyorsell",
"1",
"--",
"sell",
"0",
"--",
"buy",
"2",
"--",
"盘前"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L983-L1001 | [
"def",
"QA_fetch_get_stock_transaction_realtime",
"(",
"code",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_mainmarket_ip",
"(",
"ip",
",",
"port",
")",
"api",
"=",
"TdxHq_API",
"(",
")",
"try",
":",
"with",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.