Harigami
ログイン
Harigamiは、ログイン不要のコード共有サービスです。コードの投稿後に発行されるURLでコードを共有できます。
PythonやRubyなど一部の言語は、投稿後にオンラインで実行することもできます。
誰でも無料で使えて、広告もありません。コードレビューやスニペットの代わりに使ってみてください。


詳細設定
+
anonymous タイトルなし
Python
# coding: utf-8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import japanize_matplotlib#matplotlibでのグラフの日本語化
import hashlib

moriyama = pd.read_excel('C://Users/21477.TOYOINKGROUP/Documents/python_study/datarobo/datarobo_2.xlsx')
moriyama_set = moriyama

moriyama_set.isnull().sum()#データの欠損値数の確認
moriyama_set.fillna(moriyama_set.mean(), inplace = True)#データの欠損値にそれぞれの中央値を補完
#print(moriyama_set)#欠損値が補完されているかの確認用。

#moriyama_setから文字データを取り除いたデータセットを作成
moriyama_num = moriyama_set.drop(["Lot","Line","SR4C-Lot.","No.308-Lot.","前処理-Line"], axis='columns')
#print(moriyama_num)#確認用

#目的変数用のデータセットを作成
moriyama_CR=moriyama_set["CR"]
moriyama_excess=moriyama_set["2μm>粒子"]
moriyama_less=moriyama_set[">2μm粒子"]
#print(moriyama_CR, moriyama_less,moriyama_excess)#できてるか確認用

#説明変数用のデータセットを作成
moriyama_Exp=moriyama_set.drop(["CR","2μm>粒子",">2μm粒子"], axis=1)
#print(moriyama_Exp)#できてるか確認用

#データの情報の確認
#moriyama.info()

#Lot内の要素内容と要素数を出力
#print(moriyama["Lot"].value_counts())

#テストセットを作る
def split_train_test(data, test_ratio):
    shuffled_indices = np.random.permutation(len(data))
    test_set_size = int(len(data) * test_ratio)
    test_indices = shuffled_indices[:test_set_size]
    train_indices = shuffled_indices[test_set_size:]
    return data.iloc[train_indices],data.iloc[test_indices]
def split_train_test_by_id(data, test_ratio, id_column):
    ids = data[id_column]
    in_test_set = ids.apply(lambda id_: test_set_check(id_, test_ratio))
    return data.loc[~in_test_set], data.loc[in_test_set]
train_set, test_set = split_train_test(moriyama, 0.2)
#print(len(train_set), "train +", len(test_set), "test")#164 train + 40 test

#hashからランダムでデータセットを作る
def test_set_check(identifier, test_ratio, hash=hashlib.md5):
    return bytearray(hash(np.int64(identifier)).digest())[-1] < 256 * test_ratio
moriyama_with_id = moriyama.reset_index()#ID列の追加
train_set, test_set = split_train_test_by_id(moriyama_with_id, 0.2, "index")
#print(test_set.head())

#one_hot_encording
# One Hot化
from sklearn import preprocessing
from sklearn.preprocessing import OneHotEncoder
#"Lot"のOne Hot化
Lot_onehot = moriyama_set['Lot'].values
Lot_onehot_enc = preprocessing.LabelEncoder().fit_transform(Lot_onehot).reshape(-1,1)
Lot_onehot_enc2 = OneHotEncoder().fit_transform(Lot_onehot_enc).toarray()

#"Line"のOne Hot化
Line_onehot = moriyama_set['Line'].values
Line_onehot_enc = preprocessing.LabelEncoder().fit_transform(Line_onehot).reshape(-1,1)
Line_onehot_enc2 = OneHotEncoder().fit_transform(Line_onehot_enc).toarray()

#"SR4C-Lot."のOne Hot化
SR4C_onehot = moriyama_set['SR4C-Lot.'].values
SR4C_onehot_enc = preprocessing.LabelEncoder().fit_transform(SR4C_onehot).reshape(-1,1)
SR4C_onehot_enc2 = OneHotEncoder().fit_transform(SR4C_onehot_enc).toarray()

#"No.308-Lot."のOne Hot化
No308_onehot = moriyama_set['No.308-Lot.'].values
No308_onehot_enc = preprocessing.LabelEncoder().fit_transform(No308_onehot).reshape(-1,1)
No308_onehot_enc2 = OneHotEncoder().fit_transform(No308_onehot_enc).toarray()

#"前処理-Line"のOne Hot化
mae_onehot = moriyama_set['前処理-Line'].values
mae_onehot_enc = preprocessing.LabelEncoder().fit_transform(mae_onehot).reshape(-1,1)
mae_onehot_enc2 = OneHotEncoder().fit_transform(mae_onehot_enc).toarray()

#標準化
#from sklearn.preprocessing import StandardScaler
#stdsc = StandardScaler()
#moriyama_set_std = stdsc.fit_transform(moriyama_set)
#print(moriyama_set_std.mean())
#print(moriyama_set_std.std())

#変換パイプライン
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

num_pipeline = Pipeline([
        ('std_scaler', StandardScaler()),
    ])

moriyama_num_tr = num_pipeline.fit_transform(moriyama_num)
print(moriyama_num_tr)

'''
try:
    from sklearn.compose import ColumnTransformer
except ImportError:
    from future_encoders import ColumnTransformer # Scikit-Learn < 0.20

num_attribs = list(moriyama_num_tr)
cat_attribs = ["Lot","Line","SR4C-Lot.","No.308-Lot.","前処理-Line"]
#"Lot_onehot_enc2","Line_onehot_enc2","SR4C_onehot_enc2","No308_onehot_enc2","mae_onehot_enc2"
#"Lot","Line","SR4C-Lot.","No.308-Lot.","前処理-Line"
full_pipeline = ColumnTransformer([
        ("num", num_pipeline, num_attribs),
        ("cat", OneHotEncoder(), cat_attribs),
    ])

moriyama_prepared = full_pipeline.fit_transform(moriyama_set)
print(moriyama_prepared)
'''

#線形回帰モデルを訓練してみる
#from sklearn.linear_model import LinearRegression
#lin_reg = LinerRegression()
#lin_reg.fit()
  • 0
  • 1
anonymous 価格乖離(XRPZ19/XRPBTC)
Python
//@version=3
study("価格乖離(XRPZ19/XRPBTC)")

binance = security("binance:xrpbtc",period,close)
mexZ = security("bitmex:xrpz19",period,close)

KAIRIZ = (mexZ - binance) / binance *100

plot(KAIRIZ,linewidth=2,color=aqua,style=histogram)

hline(0.0,color=white,linestyle=dotted,linewidth=1)
hline(-5.0,color=red,linestyle=solid,linewidth=1)
hline(5.0,color=red,linestyle=solid,linewidth=1)
  • 0
  • 1
ガンマ@駆け出しエンジニア コゲクラウドDMA零式
Python
//@version=3
study('コゲクラウドDMA零式', overlay=true)
//クラウド
EMAorSMA = input(title="平均線の選択", defval="SMA", options=["SMA", "EMA"])
FAST= input(title="FASTMA", type=integer, defval=20, minval=1, maxval=10000)
SLOW = input(title="SLOWMA", type=integer, defval=80, minval=1, maxval=10000)
FASTMA = EMAorSMA == "EMA" ? ema(close, FAST) : sma(close, FAST)
SLOWMA = EMAorSMA == "EMA" ? ema(close, SLOW) : sma(close, SLOW)
displacement = input(26, minval=1,title="遅行線")
//高値安値
len1=input(9, title="FAST-HL")
len2=input(26, title="SLOW-HL")
upper1 = highest(len1)
lower1= lowest(len1)
upper2 = highest(len2)
lower2= lowest(len2)
basis1= avg(upper1, lower1)
basis2= avg(upper2, lower2)
//カラー等
off = input(26, title="シフト")
ec = FASTMA > SLOWMA ? lime:red
plot(FASTMA, color=ec, linewidth=2, offset = off+1)
plot(SLOWMA, color=ec, linewidth=2, offset = off+1)
ec2 = basis1 > basis2 ? green:purple
fill(plot(FASTMA, offset = off+1), plot(SLOWMA, offset = off+1), color = ec)
plot(close,offset=-displacement+1, color=aqua, title="遅行スパン")
plot(basis1,color=ec2,transp=5)
plot(basis2,color=ec2,transp=5)
  • 0
  • 0
ガンマ@駆け出しエンジニア Momentum Strateg
Python
//@version=3
strategy("Momentum Strategy", overlay=false)
length = input(12)
price = close
momentum(seria, length) =>
    mom = seria - seria[length]
    mom
mom0 = momentum(price, length)
mom1 = momentum( mom0, 1)
if (mom0 > 0 and mom1 > 0)
    strategy.entry("MomLE", strategy.long, stop=high+syminfo.mintick, comment="LONG")
else
    strategy.cancel("MomLE")
if (mom0 < 0 and mom1 < 0)
    strategy.entry("MomSE", strategy.short, stop=low-syminfo.mintick, comment="SHORT")
else
    strategy.cancel("MomSE")
plot(mom0,color=lime)
plot(mom1,color=red)
hline(0)
  • 0
  • 0
ガンマ@駆け出しエンジニア Hull cross and ATR
Python
//@version=3
study("Hull cross and ATR", shorttitle="H&ATR", overlay=true)
keh=input(title="Hull Length",type=integer,defval=52)
length = input(title="ATR Length", defval=46, minval=1)
smoothing = input(title="ATR Smoothing", defval="WMA", options=["RMA", "SMA", "EMA", "WMA"])
p=input(ohlc4,type=source,title="Price data")
n2ma=2*wma(p,round(keh/2))
nma=wma(p,keh)
diff=n2ma-nma
sqn=round(sqrt(keh))
n2ma1=2*wma(p[1],round(keh/2))
nma1=wma(p[1],keh)
diff1=n2ma1-nma1
sqn1=round(sqrt(keh))
n1=wma(diff,sqn)
n2=wma(diff1,sqn)
ma_function(source, length) => 
    if smoothing == "RMA"
        rma(p, length)
    else
        if smoothing == "SMA"
            sma(p, length)
        else
            if smoothing == "EMA"
                ema(p, length)
            else
                wma(p, length)
plot(ma_function(tr(true), length), title = "ATR", color=#00000000, transp=50)
exitLong = n1<n2
exitShort = n1>n2
longCondition = ma_function(tr(true), length)<p and p>p[length] and n1>n2
shortCondition = ma_function(tr(true), length)>p and p<p[length] and n1<n2
_state = 0
_prev  = nz(_state[1])
_state := _prev
if _prev == 0
    if longCondition 
        _state := 1
    if shortCondition 
        _state := 2
if _prev == 1
    if exitLong
        _state := 0
if _prev == 2
    if exitShort
        _state := 0
_bLongEntry  = (_state == 1 and _prev == 0)
_bShortEntry = (_state == 2 and _prev == 0)
_bLclose  = (_state == 0 and _prev == 1)
_bSclose   = (_state == 0 and _prev == 2)
alertcondition(_bLongEntry, title="BUY", message="Buy")
alertcondition(_bShortEntry, title="SELL", message="Sell")
alertcondition(_bLclose or _bSclose, title="CLOSE", message="Close")
bgcolor(_bLongEntry?lime:na, transp=30)
bgcolor(_bShortEntry?red:na, transp=30)
bgcolor(_bLclose or _bSclose?yellow:na, transp=30)
  • 0
  • 1
ガンマ@駆け出しエンジニア MAcross&trnd
Python
//@version=3
strategy(title = "MAcross&trnd", overlay = true)
len = input(20, minval=1, title="SMA")
len1 = input(20, minval=1, title="EMA")
len2 = input(120, minval=1, title="TREND MA")
ma1 = sma(close,len)
ma2 = ema(close,len1)
ma3 = sma(close,len2)
buy = crossover(ma1,ma2) and ma1>ma3
sel = crossunder(ma1,ma2) and ma1<ma3
strategy.entry("BUY",  strategy.long , when=buy)
strategy.entry("SELL", strategy.short, when=sel)
plot(ma1,color=lime,linewidth=1)
plot(ma2,color=red,linewidth=1)
plot(ma3,color=aqua,linewidth=1)
  • 0
  • 1
ガンマ@駆け出しエンジニア RCI3lines optimized
Python
//
// @author Jadbrother modified by gero, optimized by yuza
//
//@version=3
study(title = "RCI3lines optimized", shorttitle = "RCI3lines opt") 
itvs = input(9, "short interval")
itvm = input(26, "middle interval")
itvl = input(52, "long interval")
src = input(close, "source")
res = input(9, "resolution", minval=9)
upperband=input(title="High line[%]",defval=80,type=integer)
lowerband=input(title="Low line[%]",defval=-80,type=integer)
dmul = 600 / res / (res*res-1)
ord(seq, idx, itv) =>
    p = seq[idx]
    o = 0.5
    for i = 0 to res-1
        d = (p - seq[i*itv])
        o := o + ((d<0) ? 1 : ((d==0) ? 0.5 : 0))
    o
d(itv) =>
    sum = 0.0
    step = itv/res
    for i = 0 to res-1
        x = (i + 1) - ord(src, i*step, step)
        sum := sum + x*x
    sum
rci(itv) => sma(100.0 - dmul * d(itv), ceil(itv/res))
hline(upperband,color=gray,linestyle=dashed)
hline(lowerband,color=gray,linestyle=dashed)
plot(rci(itvs), title = "RCI short", color = red)
plot(rci(itvm), title = "RCI middle", color = blue)
plot(rci(itvl), title = "RCI long", color = green)
  • 0
  • 1
ガンマ@駆け出しエンジニア CCI CURRENCY INDEX
Python
//@version=2
study("CCI CURRENCY INDEX")
//               100
// CCI = 100 - --------
//              1 + RS
// RS = Average Gain / Average Loss
Length = input(14, minval=1)
eurusd = security("EURUSD", period, close)
eurgbp = security("EURGBP", period, close)
euraud = security("EURAUD", period, close)
eurjpy = security("EURJPY", period, close)
eurcad = security("EURCAD", period, close)
eurnzd = security("EURNZD", period, close)
eurchf = security("EURCHF", period, close)
gbpeur = (1 / eurgbp)
gbpusd = security("GBPUSD", period, close)
gbpaud = security("GBPAUD", period, close)
gbpjpy = security("GBPJPY", period, close)
gbpcad = security("GBPCAD", period, close)
gbpnzd = security("GBPNZD", period, close)
gbpchf = security("GBPCHF", period, close)
audeur = (1 / euraud)
audusd = security("AUDUSD", period, close)
audgbp = (1 / gbpaud)
audjpy = security("AUDJPY", period, close)
audcad = security("AUDCAD", period, close)
audnzd = security("AUDNZD", period, close)
audchf = security("AUDCHF", period, close)
nzdeur = (1 / eurnzd)
nzdusd = security("NZDUSD", period, close)
nzdaud = (1 / audnzd)
nzdgbp = (1 / gbpnzd)
nzdjpy = security("NZDJPY", period, close)
nzdcad = security("NZDCAD", period, close)
nzdchf = security("NZDCHF", period, close)
usdeur = (1 / eurusd)
usdgbp = (1 / gbpusd)
usdaud = (1 / audusd)
usdjpy = security("USDJPY", period, close)
usdcad = security("USDCAD", period, close)
usdnzd = (1 / nzdusd)
usdchf = security("USDCHF", period, close)
cadeur = (1 / eurcad)
cadusd = (1 / usdcad)
cadaud = (1 / audcad)
cadgbp = (1 / gbpcad)
cadjpy = security("CADJPY", period, close)
cadnzd = (1 / nzdcad)
cadchf = security("CADCHF", period, close)
chfeur = (1 / eurchf)
chfgbp = (1 / gbpchf)
chfusd = (1 / usdchf)
chfaud = (1 / audchf)
chfnzd = (1 / nzdchf)
chfcad = (1 / cadchf)
chfjpy = security("CHFJPY", period, close)
jpyeur = (1 / eurjpy)
jpyusd = (1 / usdjpy)
jpyaud = (1 / audjpy)
jpygbp = (1 / gbpjpy)
jpycad = (1 / cadjpy)
jpynzd = (1 / nzdjpy)
jpychf = (1 / chfjpy)
EUROD = (eurusd * eurgbp * eurjpy * euraud * eurnzd * eurcad * eurchf)
GBPD = (gbpusd * gbpeur * gbpaud * gbpjpy * gbpcad * gbpnzd * gbpchf) 
USDD = (usdaud * usdgbp * usdeur * usdjpy * usdcad * usdnzd * usdchf)
AUDD = (audusd * audgbp * audeur * audjpy * audcad * audnzd * audchf)
NZDD = (nzdusd * nzdgbp * nzdaud * nzdjpy * nzdcad * nzdeur * nzdchf)
CADD = (cadusd * cadgbp * cadaud * cadnzd * cadjpy * cadeur * cadchf)
JPYD = (usdjpy * gbpjpy * audjpy * nzdjpy * cadjpy * eurjpy * chfjpy)
CHFD = (chfeur * chfgbp * chfusd * chfaud * chfnzd * chfcad * chfjpy)
EURORSI = cci(EUROD, Length)
GBPRSI = cci(GBPD, Length)
USDRSI = cci(USDD, Length)
AUDRSI = cci(AUDD, Length)
NZDRSI = cci(NZDD, Length)
CADRSI = cci(CADD, Length)
JPYRSI = cci(JPYD, Length)
CHFRSI = cci(CHFD, Length)
plot(EURORSI, "EUR", blue)
plot(USDRSI, "USD", yellow)
plot(GBPRSI, "GBP", teal)
plot(AUDRSI, "AUD", green)
plot(NZDRSI, "NZD", orange)
plot(JPYRSI, "JPY", white)
plot(CADRSI, "CAD", red)
plot(CHFRSI, "CHF", red)
hline(50)
  • 0
  • 0
ガンマ@駆け出しエンジニア Parabolic SAR Strategy
Python
//@version=3
strategy("Parabolic SAR Strategy", overlay=true)
start = input(0.02)
increment = input(0.02)
maximum = input(0.2)
psar = sar(start, increment, maximum)
if (psar >= high)
    strategy.entry("ParLE", strategy.long, stop=psar, comment="LONG")
else
    strategy.cancel("ParLE")
if (psar <= low)
    strategy.entry("ParSE", strategy.short, stop=psar, comment="SHORT")
else
    strategy.cancel("ParSE")
plot(psar,color=lime,style =circles,linewidth = 2)

  • 0
  • 1
ガンマ@駆け出しエンジニア BBMA-PO
Python
//@version=3
study(title = "BBMA-PO")
source = hlc3
length = input(20, minval=1), mult = input(2.0, minval=0.001, maxval=50)
len = input(15, minval=1, title="FASTMA")
len2 = input(20, minval=1, title="FASTMA2")
len3 = input(35, minval=1, title="FASTMA3")
len4 = input(55, minval=1, title="SLOWMA")
len5 = input(85, minval=1, title="SLOWMA2")
len6 = input(120, minval=1, title="SLOWMA3")
hiline = input(0.8, "HL")
lowline = input(0.2, "LL")
showPerfectOrder = input(title="Show Perfect Order?", type=bool, defval=true)
//RSI
rsi1 = rsi(source, length)
// BB of RSI
basis = sma(rsi1, length)
dev = mult * stdev(rsi1, length)
upper = basis + dev
lower = basis - dev
br = (rsi1 - lower)/(upper - lower)
//MA OF RSI
er = ema(br,len)
er2 = ema(br,len2)
er3 = ema(br,len3)
er4 = ema(br,len4)
er5 = ema(br,len5)
er6 = ema(br,len6)
//COLOR
plot(er, title="FMA", style=line, linewidth=1, color=lime,transp=10)
plot(er2, title="FMA2", style=line, linewidth=1, color=red,transp=10)
plot(er3, title="FMA3", style=line, linewidth=1, color=yellow,transp=10)
plot(er4, title="SMA", style=line, linewidth=1, color=purple,transp=10)
plot(er5, title="SMA2", style=line, linewidth=1, color=aqua,transp=10)
plot(er6, title="SMA3", style=line, linewidth=1, color=orange,transp=10)
plot(hiline, title="HL",color=gray,style =circles,linewidth = 1)
plot(lowline, title="LL",color=gray,style =circles,linewidth = 1)
perfectOrderByUpTrend = er[1] > er2[1] and er3[1] > er4[1] and er5[1] > er6[1] ? true : false
perfectOrderByDownTrend = er[1] < er2[1] and er3[1] < er4[1] and er5[1] < er6[1] ? true : false
bgcolor(perfectOrderByUpTrend and showPerfectOrder ? green : white, transp=90, offset=-1)
bgcolor(perfectOrderByDownTrend and showPerfectOrder ? red : white, transp=90, offset=-1)
  • 0
  • 1