Wednesday, March 2, 2016

Where we are

The original purpose of this blog was to setup a stream of consciousness format for me to share my experience in learning how to speculate in the financial markets using a quantitative framework. Quantitative trading is not the holy grail of strategies. I know plenty of great discretionary traders who operate in Buddhist-like risk management fashion in order to carve consistent money out of the markets.

My goal was always  to couple that risk management with a real quantifiable edge in markets. If a stop gets hit, I will honor it like any other discretionary trader. I know far too many people/shops who have been on the wrong side of a "100% winner in the past" which eventually takes them out of the game. The goal is always to remain solvent and compound your capital whenever I see an opportunity.

So with that being said, I decided to turn this into a blog about my personal trades in the market. My strategy involves trading on timeframes from one day to one week. Usually the later. I am starting with a "$1,000" account. My goal is to compound this  account monthly at a rate of

I saw an edge on March 1st, 2016 after the gap up. Small-caps initially filled the gap and held. The pattern was bullish for the S&P where a down Friday and down Monday usually meant the S&P would be up big given over conditions in relative value rankings of stocks/bonds. The strategy was to buy the weakness on the day. The choice was UPRO, TQQQ or TNA. TNA offered the best risk reward. I loaded up at $47 with 60% off the account. I sold later at $48.30 at new highs and collected my coin. I usually hate day trading, but the risk:reward was too good here. March 1st: Balance + 1009.91 (101bps).

On March 2nd, I didn't make a trade. We appear to be observing a very bullish pattern in markets at this time. The chair pointed out and asked his traders to take a look at what happens when stocks are unch for the year after suffering a huge drawdown. Here is a histogram of returns on SPY 20 days later.

YTD SPY Plot
Here are the return distrubutions for t+5,10,20 and 30 after such an occurence where the S&P is slightly down for the year but had a drawdown of < 8%, This has historically been a bullish event. I will be looking to put on a multi-week long trade in the coming weeks on my personal account. The risk-reward I see here is roughly 2-3% down in the S&P to make 3x that.



Wednesday, June 24, 2015

Value-at-Risk for a portfolio

I have yet to see a comprehensive variance/co-variance method for getting VaR values for individual securities in a portfolio. So lets begin.

First, we need pandas, numpy, scipy and a datasource for our portfolio. I prefer 'bt' for the later.

import pandas as pd
import numpy as np
import pandas.io.data as web
import datetime
import matplotlib.pyplot as plt
import bt
from scipy.stats import norm


So lets pull the data

start = datetime.datetime(2013, 5, 1)


portfolio = bt.get('aapl, tlt, fxe, gs, c, fb, ms, ko, bac', start=start)
port = pd.DataFrame(index=portfolio.columns)


Now we have two dataframes. One with our historical values as portfolio, the other as port which holds the security names which we will later store our VaR values in. Next we create the actual VaRCoV function:


def var_cov_var(P, c, mu, sigma):
    alpha = norm.ppf(1-c, mu, sigma)
    return P - P*(alpha + 1)


def getVar(portfolio, c): #portfolio dataframe, confidence interval    P = 15000   #each position % of portfolio, should create a new one to store marketvalue of each position to be more precise    #c = 0.99    #confidence interval, moved to function    totalrisk = 0    for i in portfolio:
        rets = portfolio[i].pct_change()
        mu = np.mean(rets)
        sigma = np.std(rets)
        var = var_cov_var(P, c, mu, sigma)
        port["VaR"][i] = var
        totalrisk += var
    return port, totalrisk


getVar(portfolio, .95)
Out[471]: 
(             VaR
 aapl  328.585833
 tlt   205.453309
 fxe   136.978460
 gs    274.577792
 c     315.838626
 fb    566.777609
 ms    332.530446
 ko    220.500392
 bac   319.658819, 2700.9012842524335)


Chees.

thinkorswim RTD/DDE data into Python

Many may not know it, but thinkorswim provides users the ability to access real time data (RTD) in excel. This is a great feature that a lot of data-streams ask their customers to pay a pretty penny for each month. Unfortunately, not many people know how to leverage the the functionality as it is pretty limiting out of the box.

So you are a thinkorswim customer and you want real time data in a python environment? No problem.

First, install the xlwings module. Load up your python IDE of choice.

from xlwings import Workbook, Sheet, Range, Chart
import time
wb = Workbook()


You need to have thinkorswim open and running. A blank excel spreadsheet should open up after you execute the last command above.

def getQuote(ticker, type):
    Range('B1').value = '=RTD("tos.rtd", ,"%s", "%s")' % (type, ticker)
    time.sleep(2.5)
    return Range('B1').value
So we create a getQuote function above that takes in two variables, both strings. We utilize the Write value feature in python to input the DDE/RTD function into the Excel cell. After about a second, this will return a value where we can use the return feature to read it back. 

Really, this is just a work-around. Unfortunately, I could not find a way to get RTD data working into the python environment directly. If anyone does, please feel free to drop a note in the comments.

So now we can call the getQuote function a ticker and input type of our choice:
getQuote("/ESU5", "LAST")
Out[447]: 2101.0


Pretty awesome! You can experiment with options as well:

def quoteOption(type, ticker, cp, exp, strike):
    Range('B1').value = '=RTD("tos.rtd", ,"%s", ".%s%s%s%s")' % (type, ticker, exp, cp, strike)
    time.sleep(2.5) #wait for excel to update the cell, usually a couple of seconds.    return Range('B1').value

quoteOption('LAST', 'VXX', 'C', 150731, 17)
Out[446]: 1.23

Cheers.