test

Sunday, October 29, 2017

For poker fans: All possible seven card combinations in a database

I have created a script that puts all possible seven card combinations in Texas Holdem poker into an SQLite database. It could be useful to do some calculations. The database becomes several gigabytes big and very slow on personal computers. But in future with faster PCs this solution could be great. This script needs an SQLite database with 7 columns called tables.db. Please find the Python code below:

import numpy

arrayt=[102,103,104,105,106,107,108,109,110,111,112,113,114,202,203,204,205,206,207,208,209,210,211,212,213,214,302,303,304,305,306,307,308,309,310,311,312,313,314,402,403,404,405,406,407,408,409,410,411,412,413,414]

conn=sqlite3.connect('tables.db')
c=conn.cursor()
pos1=0
pos2=1
pos3=2
pos4=3
pos5=4
pos6=5
pos7=6
i=0
while pos1<=45:
   
    while pos2<=46:
       
        while pos3<=47:  
               
            while pos4<=48:
               
                while pos5<=49:    
                   
                    while pos6<=50:
                       
                        while pos7<=51:
                            c.execute("INSERT INTO TABLE2 VALUES (?, ?, ?, ?, ?, ?, ?)", ((arrayt[pos1]),(arrayt[pos2]),(arrayt[pos3]),(arrayt[pos4]),(arrayt[pos5]),(arrayt[pos6]),(arrayt[pos6])))   
                            pos7+=1
                            i+=1
                        pos6+=1
                        pos7=pos6+1
                    pos5+=1
                    pos6=pos5  
                pos4+=1
                pos5=pos4
            pos3+=1
            pos4=pos3    
        pos2+=1
        pos3=pos2
    pos1+=1
    pos2=pos1
conn.commit()
conn.close()

Wednesday, September 27, 2017

Hedging interest rates with currencies

Many investors facing the problem of raising interest rates and hedging. If you buy a swap you have to pay massively. But usuallymit should be possible to do the same with currency derivatives. The longterm charts of currencies and interest rates look very similar.

Setting up Django CMS

Django CMS is a powerful system for building homepages. But it takes time to set it up properly even if you are experienced in coding.

Tuesday, April 25, 2017

Get EUREX options chains to Python Pandas Dataframe

I haven't found a tool to get the options chains of Eurex to pandas. Just go to boerse.de and open an Eurex option chain. Use a web scraper to export the option chain table to a csv file. The firefox plugin is very comfortable to do it. After it change the file name and execute this program to get it into Python:

import pandas as pd
import datetime
import math
from datetime import date


df = pd.read_csv('my_file.csv', delimiter=',')

df['Bid'].replace(',','.', inplace=True,regex=True)
df['Bid'].replace('-','0', inplace=True,regex=True)
df['Ask'].replace(',','.', inplace=True,regex=True)
df['Ask'].replace('-','0', inplace=True,regex=True)
df['Bid']=df['Bid'].astype(np.float64)
df['Ask']=df['Ask'].astype(np.float64)

df['Settle'].replace(',','.', inplace=True,regex=True)
df2=df[[0]] + '/18'
df['vdatum']=df2
newdate=pd.to_datetime(df['vdatum'], format='%Y/%m/%d')
df['vdatum']=newdate
df['weekday']=df['vdatum'].dt.dayofweek
df['weekday'].replace('0','7', inplace=True,regex=True)
df['weekday']=df['weekday'].astype(np.float64)
df['timedifference']=df['vdatum']-datetime.datetime.now()  
df['timedifference']=df['timedifference'].dt.days
df['timedifference']=df['timedifference']+4-df['weekday']

Stock, Currency and Commodity Analysis for Volatility Investing in Python

Here is a small program written in Python (Anaconda newest version) to analyse stocks etc.. It's great to get feeling for the drift and volatility of a specific asset.

# -*- coding: utf-8 -*-
"""
Spyder Editor

"""
PR = 20
START='2005-02-01'
END='2017-03-27'
SYMBOL="dez.de"
SYMBOL2="eur=x"
from pandas_datareader.data import get_data_yahoo
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from numpy import convolve
def movingaverage (values, window):
    weights = np.repeat(1.0, window)/window
    sma = np.convolve(values, weights, 'valid')
    return sma
def EOM(df, n):
    EoM = (df['High'].diff(1) + df['Low'].diff(1)) * (df['High'] - df['Low']) / (2 * df['Volume'])
    Eom_ma = pd.Series(pd.rolling_mean(EoM, n), name = 'EoM')
    df = df.join(Eom_ma)
    return df
def ACCDIST(df, n):
    ad = (2 * df['Close'] - df['High'] - df['Low']) / (df['High'] - df['Low']) * df['Volume']
    M = ad.diff(n - 1)
    N = ad.shift(n - 1)
    ROC = M / N
    AD = pd.Series(ROC, name = 'Acc/Dist_ROC')
    df = df.join(AD)
    return df
def ROC(df, n):
    M = df['Close'].diff(n - 1)
    N = df['Close'].shift(n - 1)
    ROC = pd.Series(M / N*100, name = 'ROC')
    df = df.join(ROC)
    return df
def STDDEV(df, n):
    df = df.join(pd.Series(pd.rolling_std(df['ROC'], n)*15.87450786638754, name = 'STD'))
    return df

datahighlowclosevolume = get_data_yahoo(SYMBOL, start = START, end = END)[['Close','Volume','High','Low']]
"""datahighlowclosevolume2 = get_data_yahoo(SYMBOL2, start = START, end = END)[['Close','Volume','High','Low']]
datahighlowclosevolume['Close']=datahighlowclosevolume['Close']/datahighlowclosevolume2['Close']"""
sma = movingaverage(np.asarray(datahighlowclosevolume['Close']), 20)
beginningzeros=np.repeat(0, 20-1)
fullsma = np.concatenate([beginningzeros,sma])
acc = ACCDIST((datahighlowclosevolume), PR)
datahighlowclosevolume['sma']=fullsma
roc=ROC((datahighlowclosevolume), PR)
rocdaily=ROC((datahighlowclosevolume), 2)
std=STDDEV((rocdaily), PR)
plt.figure(1,figsize=(16, 24))
plt.subplot(211)
plt.plot(datahighlowclosevolume['Close']);
plt.plot(datahighlowclosevolume['sma']);
plt.ylim(datahighlowclosevolume['Close'].min()*0.98,datahighlowclosevolume['Close'].max()*1.02)

plt.figure(2,figsize=(16, 14))
plt.subplot(211)
y_pos = np.arange(len(datahighlowclosevolume['Volume']))
plt.bar(y_pos, datahighlowclosevolume['Volume'], align='center', alpha=0.5)
plt.ylim(acc['Volume'].quantile(.05),acc['Volume'].quantile(.95))    
'''plt.plot(datahighlowclosevolume['Volume'])'''
plt.subplot(212)      
plt.plot(acc['Acc/Dist_ROC'])
plt.ylim(acc['Acc/Dist_ROC'].quantile(.05),acc['Acc/Dist_ROC'].quantile(.95))

plt.figure(3,figsize=(16, 14))
plt.subplot(211)
plt.plot(roc['ROC'])
plt.ylim(roc['ROC'].quantile(.05),roc['ROC'].quantile(.95))
plt.axhline(roc['ROC'].mean())
rocquantp=list(filter(lambda x: x < roc['ROC'].quantile(.05), roc['ROC']))
rocquantn=list(filter(lambda x: x > roc['ROC'].quantile(.95), roc['ROC']))
plt.subplot(212)
plt.plot(std['STD'])
plt.axhline(std['STD'].quantile(.25))
plt.axhline(std['STD'].quantile(.50))
plt.axhline(std['STD'].quantile(.75))
plt.ylim(std['STD'].quantile(.05),std['STD'].quantile(.95))



To run this program you have to install pandas datareader as well. Change the dates and the period (PR) to change the timeframe for all windows. SYMBOL is the symbol yo use. Use yahoo symbols. You can use the program with two symbols as well. This could be beneficial for currency pairs or pairs trading in general.

Saturday, February 25, 2017

Which brokers to choose and how to setup?

Which brokers to choose?

For the MetaTrader terminal one you need a fast broker. Usually ECN brokers are the fastest. If you plan to trade in London LMAX could be a good choice. Your second terminal should be a slow broker. Usually these are Market Makers but sometimes it’s also possible to arbitrage other ECN marketplaces. An important point to consider is the execution. Most of the Market Makers offer instant execution. Instant execution has the advantage that you can set the maximum slippage allowed.

How to setup

The right settings depend on the broker you choose. The minimum difference between the prices of terminal one and terminal two should be at least the maximum difference of the Bid and Ask. Then you can make sure that you get an edge over the market. The standard setting for closing is 0 difference of the price of terminal one and terminal two. Some brokers require to keep the position a few minutes before you can close it. Testing in demo mode is really helpful.

Do I need a VPS?

A Virtual Private Server (VPS) is popular in automatic Forex trading and necessary. It is possible to choose one near the Terminal 1 or Terminal 2 to get latency advantages. A VPS starts from less than $10 a month. If you want to trade with just one broker, a VPS with 1024 Megabyte Ram and an average processor is sufficient. If you want to trade with more brokers at the same time from one VPS you will need more capacity. A VPS can easily be accessed with Microsoft Windows Remote Desktop. With the help of this tool it is possible to access and control the VPS like a local desktop computer.

How many brokers can I trade at the same time?

It is possible to trade with as many brokers at the same time as you want. The quote provider Terminal 1 only has to be installed once. The Terminal 2 has to be installed at least once. It will depend on how many brokers you would like to trade with.

Some Basics

What is MetaTrader 4?

MetaTrader 4 (MT4) is the leading Foreign Exchange Trading platform from the company MetaQuotes. The largest number of trades, in the world’s largest market are executed using this platform. You get charting options as well scripting and automation options.

What are Expert Advisors?

Expert Advisors are programs which automate the trading in Forex. Expert Advisors “EAs” can modify your chart, indicators and trade full or half automatically. The programming language, the Expert Advisors are coded in, is called MetaQuotes Language “MQL”.

What is the MetaEditor?

The MetaEditor is included in MT4. Simply click on the button with the book icon next to the New Order button or press the F4 key on your keyboard. The MetaEditor will then start.

On the right you can see your experts, indicators and scripts. At the top are buttons to create a new EA or load, safe compile, debug and profile an EA. The toolbox on the bottom shows you errors, the search results, articles and code examples from the community and the journal.

How to install an Expert Advisor?

First you have to transfer the EA files to the correct folders. Open the MetaEditor, click on File and then Open Data Folder. Next open the MQL4 folder and then open the Experts folder. This is the location where you copy your ex4 file.

If the EA uses dll files go back to the MQL4 folder and then open Libraries. This is the location where you copy the dll files.

How to compile an Expert Advisor?

Before you can start an EA you have to compile it.

To compile it, press the Compile button on the top toolbar and watch for errors in the toolbox. If no errors occur, the EA is ready to start.

How to start an Expert Advisor?

After you have copied the files to the correct folders, restart MetaTrader.

On the right you will see your EA in the tree under Expert Advisors, double click on it.

Go to the Common” tab and allow the import of dlls. Furthermore, you have to allow live trading for trading.

On the inputs tab choose the right parameters of your EA. Then click OK.

Now the EA is applied to your chart. You will see it in the top right corner of your chart. One chart can carry one expert advisor.

The last step is that you start auto trading in general. Press AutoTrading in the top bar or Ctrl+E on your keyboard. If the green play symbol appears EAs are activated for trading.

First steps to develop an Expert Advisor

Go to the MetaEditor click New on the top bar or Ctrl+N on your keyboard. Click Next. Give your EA a name. Click Next and then Finish. Now you have your basic EA.

What is Visual Studio?


Visual Studio is a popular integrated development environment from Microsoft. It’s easy and straightforward to use. In this book Visual Studio is used to generate a small program that transfers the quotes from the first terminal to the second. The programming language C++ is used, because it’s fast and reliable.