title: Mt4 Probability Script
body: <p>I'm fairly new to <code>python</code></p>
  
  <p>I have made a simple script that imports price feeds from <strong><code>mt4</code></strong></p>
  
  <p>My idea / Project is to turn this into some sort of a probability indicator, that is giving the probability, besides the bid and ask,
  for example:</p>
  
  <pre><code>TIME/                BID             ASK
  USD/CADD     22:19   1.30451 60%^    1.30D39 40%v
  </code></pre>
  
  <p>and the probability is changing within specific period, i.e for example 1hr period, so every hour it will give a new probability of the direction</p>
  
  <p>It is looking for two patterns: A, B,</p>
  
  <p>Pattern A represents a bullish pattern</p>
  
  <p>Pattern B represents a bearish pattern </p>
  
  <p>basically looking for how strong is the probability A or B reoccurring
  out of the two which has a higher chance of reoccurring,</p>
  
  <p>Here is where I am stuck</p>
  
  <p>I have no idea how to put that together...</p>
  
  <p>Here is what I have so far:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>import datetime
  import numpy as np
  import pandas as pd
  import sklearn
  
  from pandas.io.data       import DataReader
  from sklearn.ensemble     import RandomForestClassifier
  from sklearn.linear_model import LogisticRegression
  from sklearn.lda          import LDA
  from sklearn.metrics      import confusion_matrix
  from sklearn.qda          import QDA
  from sklearn.svm          import LinearSVC, SVC
  
  import dde_client as ddec
  import time
  
  QUOTE_client = ddec.DDEClient('MT4', 'QUOTE')
  
  symbols = ['USDCAD', 'GOLD','EURUSD', 'SILVER', 'US30Cash',  ]
  for i in symbols:
      QUOTE_client.advise(i)
  
  
  def Get_quote():
   while 1:
      time.sleep(1)
      print "Symbol\tDATE\t\tTIME\tBID\tASK"
      for i in symbols:
          current_quote = QUOTE_client.request(i).split(" ")
          day, _time, bid, ask = (current_quote[0], current_quote[1],
                              current_quote[2], current_quote[3])
          print i + ":\t" + day + "\t" + _time +"\t" +bid+ "\t" + ask
          break
          time.sleep(1)
          return Get_quote()
          continue
  
  
      def create_lagged_series(cuurent_quote,start_time, end_time, lags=1):
        ts = DataReader(cuurent_quote,symbols,
                      start_time-datetime.timedelta(hours=1),
                      end_time
                      )
        tslag = pd.DataFrame(index=ts.index)
        ts['Today'] = ts['Adj Close']
        tslag["Volume"] = ts["Volume"]
        for i in xrange(0, lags):
           tslag["Lag%s" % str(i+1)] = ts["Adj Close"].shift(i+1)
  
        tsret = pd.DataFrame(index=tslag.index)
        tsret["Volume"] = tslag["Volume"]
        tsret["Today"] = tslag["Today"].pct_change()*100.0
  
        for i in xrange(0, lags):
               if (abs(x) &lt; 0.0001):
                tsret["Today"][i] = 0.0001
  
        for i in xrange(0,lags):
              tsret["Lag%s" % str(i+1)] = \
              tslag["Lag%s" % str(i+1)].pct_change()*100.0
  
        tsret["Direction"] = np.sign(tsret["Today"])
        tsret = tsret[tsret.index &gt;= start_time]
  
        return tsret
  
        if __name__ == "__main__":
           snpert = create_lagged_series(len('GOLD', Get_quote(), 1))
           X = snpret[["Lag1","Lag2"]]
           y = snpret["Direction"]
           start_test = cuurernt_quote
  
  
           X_train = X[X.index &lt; start_test]
           X_test = X[X.index &gt;= start_test]
           y_train = y[y.index &lt; start_test]
           y_test = y[y.index &gt;= start_test]
           print "Hit Rates/Confusion Matrices:\n"
           models = [ ( "LR",   LogisticRegression() ),
                      ( "LDA",  LDA() ),
                      ( "QDA",  QDA() ),
                      ( "LSVC", LinearSVC() ),
                      ( "RSVM", SVC( C            = 1000000.0,
                                     cache_size   = 200,
                                     class_weight = None,
                                     coef0        = 0.0,
                                     degree       = 3,
                                     gamma        = 0.0001,
                                     kernel       = 'rbf',
                                     max_iter     = -1,
                                     probability  = False,
                                     random_state = None,
                                     shrinking    = True,
                                     tol          = 0.001,
                                     verbose      = False
                                     )
                        ),
                      ( "RF",   RandomForestClassifier( n_estimators = 1000,
                                                        criterion    = 'gini',
                                                        max_depth         = None,
                                                        min_samples_split = 2,
                                                        min_samples_leaf  = 1,
                                                        max_features      = 'auto',
                                                        bootstrap         = True,
                                                        oob_score         = False,
                                                        n_jobs            = 1,
                                                        random_state      = None,
                                                        verbose           = 0
                                                        )
                        )
                      ]
  
      # Iterate through the models
        for m in models:
  
          # Train each of the models on the training set
                   m[1].fit(X_train, y_train)
  
  
                   pred = m[1].predict(X_test)
  
  
                   print "%s:\n%0.3f" % (m[0], m[1].score(X_test, y_test))
                   print "%s\n" % confusion_matrix(pred, y_test)</code></pre>
  </div>
  </div>
  </p>
  
  <p>Here is just my <strong><code>MT4</code></strong> price feed script on its own:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>import dde_client as ddec
  import time
  
  __author__ = 'forex Ticker'
  
  print __author__
  
  
  QUOTE_client = ddec.DDEClient('MT4', 'QUOTE')
  
  symbols = ['USDCAD', 'GOLD','EURUSD', 'SILVER', 'US30Cash',  ]
  for i in symbols:
      QUOTE_client.advise(i)
  
  
  
  while 1:
      time.sleep(1)
      print "Symbol\tDATE\t\tTIME\tBID\tASK"
      for i in symbols:
          current_quote = QUOTE_client.request(i).split(" ")
          day, _time, bid, ask = (current_quote[0], current_quote[1],
                              current_quote[2], current_quote[3])
          print i + ":\t" + day + "\t" + _time +"\t" +bid+ "\t" + ask
          break
          time.sleep(1)
          continue</code></pre>
  </div>
  </div>
  </p>