Exemplo n.º 1
0
 def ShowAll(self):
     df = pd.DataFrame({
         'EURUSD': self.pairList['EURUSD']['Close'],
         'EURJPY': self.pairList['EURJPY']['Close'],
         'USDJPY': self.pairList['USDJPY']['Close']
     })
     display_charts(df, chart_type="stock", title="MA cross", grid=True)
Exemplo n.º 2
0
def PositionChart(Open, long, short, tech):
    df = pd.DataFrame(({"Open": Open, "Long": long, "Short": short}))
    position_chart = display_charts(df,
                                    title=tech + "_position",
                                    figsize=(560, 400),
                                    chart_type="stock",
                                    grid=True)
    return
Exemplo n.º 3
0
def ModelChart(df, tech):
    df = pd.DataFrame(df)
    chart = display_charts(df,
                           title=tech + "_cross",
                           figsize=(560, 400),
                           chart_type="stock",
                           grid=True)
    return
Exemplo n.º 4
0
    def ShowVersusCurrency(self, currency):
        versusList = {}
        for key in self.pairList.keys():
            forward = key[:3]
            backward = key[3:6]
            strVs = 'VS. '
            if forward == currency:
                # 前半がキー
                versusList[strVs + backward] = self.pairList[key]['Close']
            elif backward == currency:
                # 後半がキー
                # 反転して格納
                versusList[strVs + forward] = self.pairList[key]['Close'] * -1
        df = pd.DataFrame(versusList)
        display_charts(df,
                       chart_type="stock",
                       title=currency + ' ' + strVs,
                       grid=True)

        return df
Exemplo n.º 5
0
# Ensure we're in the correct directory
import os

# Import Data
# ===========
#
# Load data from Google Trends.

data = pd.read_csv('data/GoogleTrendsData.csv',
                   index_col='Date',
                   parse_dates=True)
data.head()

# Show DJIA vs. debt related query volume.
display_charts(data,
               chart_type="stock",
               title="DJIA vs. Debt Query Volume",
               secondary_y="debt")
seaborn.lmplot("debt", "djia", data=data, size=7)

# Detect if search volume is increasing or decreasing in
# any given week by forming a moving average and testing if the current value
# crosses the moving average of the past 3 weeks.
#
# Let's first compute the moving average.

data['debt_mavg'] = data.debt.rolling(window=3, center=False).mean()
data.head()

# Since we want to see if the current value is above the moving average of the
# *preceeding* weeks, we have to shift the moving average timeseries forward by one.
Exemplo n.º 6
0
        if trade[i] > 0:
            Position = True
        elif Position:
            PosPeriod += 1  # ポジションの期間をカウント
        if trade[i] < 0:
            if PosPeriod > 0:
                Line[i] = -trade[i]
                diff = (Line[i] - Line[i - PosPeriod]) / PosPeriod
                for j in range(i - 1, i - PosPeriod, -1):
                    Line[j] = Line[j + 1] - diff  # ポジションの期間を補間
                PosPeriod = 0
                Position = False
        if trade[i] == 0 and not Position:
            Line[i] = 'NaN'
    return Line


long1 = Trade["Long"]
long = Position(long1)

#Chart
position = pd.DataFrame({
    "Close": Close[1:],
    "Long": long[1:]
})  #"Short":short, "UpSigma":UpSigma, "LowSigma":LowSigma
position = position[88000:89000]
display_charts(position,
               title="Position",
               figsize=(600, 400),
               chart_type="stock",
               grid=True)
Exemplo n.º 7
0
            if PosPeriod > 0:
                Line[i] = -trade[i]
                diff = (Line[i] - Line[i - PosPeriod]) / PosPeriod
                for j in range(i - 1, i - PosPeriod, -1):
                    Line[j] = Line[j + 1] - diff  # ポジションの期間を補間
                PosPeriod = 0
                Position = False
        if trade[i] == 0 and not Position:
            Line[i] = 'NaN'
    return Line


plot = pd.DataFrame({'Equity': Equity + Initial})
display_charts(plot[:1000],
               chart_type="stock",
               title="Position",
               figsize=(640, 480),
               grid=True)
long1 = Trade["Long"]
short1 = Trade["Short"]
long = PositionLine(long1)
short = PositionLine(short1)

#Chart
position = pd.DataFrame({
    "Open": Open,
    "Long": long
})  #"Short":short, position = position[:1000]
display_charts(position,
               title="Position",
               figsize=(600, 400),
Exemplo n.º 8
0
def BacktestReport(Trade, PL, HoldPro, Initial):
    LongPL = PL['Long']
    LongPLResult = LongPL.sum()
    LongTrades = np.count_nonzero(Trade['Long']) // 2
    LongWinTrades = np.count_nonzero(LongPL.clip_lower(0))
    LongLoseTrades = np.count_nonzero(LongPL.clip_upper(0))
    try:
        AveProLong = LongPLResult / LongTrades
    except:
        print("Error")

    ShortPL = PL['Short']
    ShortPLResult = ShortPL.sum()
    ShortTrades = np.count_nonzero(Trade['Short']) // 2
    ShortWinTrades = np.count_nonzero(ShortPL.clip_lower(0))
    ShortLoseTrades = np.count_nonzero(ShortPL.clip_upper(0))
    try:
        AveProShort = ShortPLResult / ShortTrades
    except:
        print("Error")

    Trades = LongTrades + ShortTrades
    WinTrades = LongWinTrades + ShortWinTrades
    LoseTrades = LongLoseTrades + ShortLoseTrades
    AssetChart = (LongPL + ShortPL).cumsum()

    GrossProfit = LongPL.clip_lower(0).sum() + ShortPL.clip_lower(0).sum()
    GrossLoss = LongPL.clip_upper(0).sum() + ShortPL.clip_upper(0).sum()
    Profit = GrossProfit + GrossLoss
    AvePro = Profit / Trades
    Equity = (LongPL + ShortPL).cumsum()
    Asset = Initial + Profit
    ROI = (Asset - Initial) / Initial * 100
    MDD = (Equity.cummax() - Equity).max()

    vs = HoldPro - Profit
    HoldIni = HoldPro + Initial
    HoldROI = (HoldIni - Initial) / Initial * 100

    print("Long")
    print('買い数 :', LongTrades)
    print('勝数 :', LongWinTrades)
    print('最大勝 ¥:', LongPL.max())
    try:
        print('平均勝 ¥:', round(LongPL.clip_lower(0).sum() / LongWinTrades, 2))
    except:
        print("Error")
    print('負数 :', LongLoseTrades)
    print('最大負 ¥:', LongPL.min())
    try:
        print('平均負 ¥:', round(LongPL.clip_upper(0).sum() / LongLoseTrades, 2))
    except:
        print("Error")
    print('損益 ¥:', round((LongPLResult), 2))
    print('平均損益 ¥:', round((AveProLong), 2))
    try:
        print('勝率 :', round(LongWinTrades / LongTrades * 100, 2), '%\n')
    except:
        print("Error")

    print("Short")
    print('売り数 :', ShortTrades)
    print('勝数 :', ShortWinTrades)
    print('最大勝 ¥:', ShortPL.max())
    try:
        print('平均勝 ¥:', round(ShortPL.clip_lower(0).sum() / ShortWinTrades, 2))
    except:
        print("Error")
    print('負数 :', ShortLoseTrades)
    print('最大負 ¥:', ShortPL.min())
    try:
        print('平均負 ¥:',
              round(ShortPL.clip_upper(0).sum() / ShortLoseTrades, 2))
    except:
        print("Error")
    print('損益 ¥:', round((ShortPLResult), 2))
    print('平均損益 ¥:', round((AveProShort), 2))
    try:
        print('勝率 :', round(ShortWinTrades / ShortTrades * 100, 2), '%\n')
    except:
        print("Error")

    print("Total")
    print('総数 :', Trades)
    print('総勝数 :', WinTrades)
    print('最大勝 ¥:', max(LongPL.max(), ShortPL.max()))
    try:
        print(
            '平均勝 ¥:',
            round((LongPL.clip_lower(0).sum() + ShortPL.clip_lower(0).sum()) /
                  WinTrades, 2))
    except:
        print("Error")
    print('負数 :', LoseTrades)
    print('最大負 ¥:', min(LongPL.min(), ShortPL.min()))
    try:
        print(
            '平均負 ¥:',
            round((LongPL.clip_upper(0).sum() + ShortPL.clip_upper(0).sum()) /
                  LoseTrades, 2))
    except:
        print("Error")
    print('平均損益 ¥', round(AvePro, 2))
    try:
        print('勝率 :', round(WinTrades / Trades * 100, 2), '%\n')
    except:
        print("Error")
    print("結果")
    print('総損益 :', round(Profit, 2))
    print('資産 :¥', Asset)
    print('ROI :', round(ROI, 2), '%')
    print('総利益 :', round(GrossProfit, 2))
    print('総損失 :', round(GrossLoss, 2))

    print('\n' '指標')
    try:
        print('Profit Factor :', round(-GrossProfit / GrossLoss, 2))
    except:
        print("Error")
    print('最大ドローダウン :', round(MDD, 2))
    print('Recovery Factor :', round(Profit / MDD, 2))

    print("\n" "Hold Position")
    print("Hold 損益 :¥", round(HoldPro, 2))
    print("Hold 資産 :¥", round(HoldIni, 2))
    print("Hold ROI :", round(HoldROI, 2), '%')
    print("Hold vs Technical :¥", round(vs, 2))
    display_charts(pd.DataFrame({"Assets": AssetChart + Initial}),
                   chart_type="stock",
                   title="資産_Chart",
                   figsize=(560, 400),
                   grid=True)
    return
Exemplo n.º 9
0
import json
data = pd.read_csv("G://gongxiang//busyZones.csv",
                   header=None,
                   names=("area", "counts"))
pre = pd.read_csv("G://gongxiang//kmresult2.csv",
                  header=None,
                  names=("lon", "lat"))
pre["area"] = pre.index
df = pd.merge(data, pre, on="area", how="left")


def foundloc(lon, lat):
    url = "http://api.map.baidu.com/geocoder/v2/?location=%f,%f&output=json&ak=Yrf32LVk9DEHOYchZAQlG9nFICRTst5V" % (
        lat, lon)
    req = urllib.request.urlopen(url)
    res = req.read().decode("utf-8")
    temp = json.loads(res)
    return temp["result"]["formatted_address"]


lon = list(df["lon"])
lat = list(df["lat"])
situation = zip(lon, lat)
situa = []
for i in situation:
    situa.append(foundloc(i[0], i[1])[6:-1])
df["name"] = situa
df1 = df[["counts", "name"]]
df1 = df1.set_index("name")
display_charts(df1, title="区域打车次数")
Exemplo n.º 10
0
 def Show(self, pair):
     df = pd.DataFrame({pair: self.pairList[pair]['Close']})
     display_charts(df, chart_type="stock", title="MA cross", grid=True)