2017年9月27日水曜日

python 1) read CSV file 2) regular expression 3) utilize multi dimension array to compare file contents.

#
#  USAGE:
# "py3 t4.py oldfilename newfilename "
# when more than 1 filename is given, this program to compare each other  and output newly added e-mail address indexed list
#            OR
# "py3 t4.py filename"
# when only 1 filename is give, to output e-mail addr index list.
#
# import required package csv for CSV, re for regular expression sys for system.
import csv
import re
import sys

# input CSV file format
# 0 for incident ID
# 12 for new alias
# 21 for assignee
# 40 for cc history to contain all related email addr.
#
# prepare buffers for 1) original file 2) new file to compare each other 3) final output.
# prepare global multi dimension array, there sould be better way but it is enough for now.
origin_arr = [[]]
new_arr = [[]]
arr = [[]]

# define functions here function to be defined before main(try).
def  make_arr(fname,buff):
    with open(fname,'r',encoding='shift_jis') as csvfile:  # file encoding = shift jis.
        csv_reader = csv.reader(csvfile,delimiter=',',quotechar='"')
        next(csv_reader) # discard the fist line.
        line_counter = 0
        for row in csv_reader:
            outbuf = re.sub(' ',"",row[40]) # remove all unnecessary spaces from the line
            outbuf = re.sub(';$',"",outbuf) # delete the last semi colon other wise blank is appended to the array.
            text = outbuf.split(";") # split by semi colon
            for addr in text:
                list = [re.sub(' ',"",row[0]),row[12],row[21],re.sub(' ',"",addr)]
                buff.append(list)
                line_counter += 1
    # print(buff) #debug

def comp_arr(origin,new):
    line_counter = 0
    # print("new size is ",len(new))  # debug
    # print("origin size is ",len(origin))  #dubug
    for new_num in range(1,len(new)):
        for origin_num in range(1,len(origin)):
            if new[new_num][3] == origin[origin_num][3]:
                if new[new_num][0] == origin[origin_num][0]:
                    break
                else:
                    m = re.search(r"@kaspersky.co", new[new_num][3])
                    if m:
                        break
                    else:
                        const_array(new[new_num][0],new[new_num][1],new[new_num][2],new[new_num][3])
                        break
            else:
                if origin_num == len(origin)-1:
                    m = re.search(r"@kaspersky.co", new[new_num][3])
                    if m:
                        pass
                    else:
                        # 0 = incident id, 1 = new alias, 2 = assignee, 3 = addr
                        const_array(new[new_num][0],new[new_num][1],new[new_num][2],new[new_num][3])
    # print(arr) # debug

def const_array(inc,alias,assignee,addr):
    work = re.sub(r"$","\"",alias)
    work = re.sub(r"^","\"",work)
    list = [assignee,addr,work,inc]
    arr.append(list)

def output_array(arr):
    for arr_num in range(1,len(arr)):  # skip the fist array to avoid vacant.
        outbuf = ','.join(map(str,arr[arr_num]))
        outbuf = re.sub(r"^\[","",outbuf) # remove sq bracket at the start and the end of the line
        outbuf = re.sub(r"\]$","",outbuf) #
        outbuf = re.sub(r"'","",outbuf)   # remove single quotation
        outbuf = re.sub(r", ",",",outbuf) # remove uncessary spaces in the line. this is necessary to be CSV.
        print(outbuf)

try:
    argvs = sys.argv
    fname = argvs[1]
    make_arr(fname,origin_arr)    # 1)pick up inc id, addr and other info from the original file, 2) construct table.
    if len(argvs) > 2:            # if # of args is more than 2, compare old file and new file and output delta.
        fname = argvs[2]
        make_arr(fname,new_arr)       # from the new file.
        comp_arr(origin_arr,new_arr)  # 1)compare each other 2)output result to arr.
    else:                         # if not pick up related infos, indexes them by addr and build output in arr.
        # print(" 1 args")
        make_arr(fname,new_arr)
        for line_counter in range(1,len(new_arr)):
            const_array(new_arr[line_counter][0],new_arr[line_counter][1],new_arr[line_counter][2],new_arr[line_counter][3])
    arr.sort()  # in both cases, sort arr and output with format.
    output_array(arr)
    sys.exit()


except FileNotFoundError as e:
    print(e)
except csv.Error as e:
    print(e)
ß

2017年9月26日火曜日

Calculate Portfolio market value. and draw the graph.


getSymbols('FAS',src="google")
getSymbols('SPXL',src="google")

l <- seq(as.Date("2014-01-01"),Sys.Date(),by="days")
fas_shares <- (as.xts(rep(3472*4,length(l)),l))

l2 <- seq(as.Date("2016-12-19"),Sys.Date(),by="days")
s2 <- c(rep(0,length(l)-length(l2)),rep(750,length(l2)))

fas_shares <- fas_shares - s2
spxl_shares <- as.xts(rep(21000,length(l)),l)


fas_shares * apply.monthly(FAS,last)[,4]
spxl_shares * apply.monthly(SPXL,last)[,4]


fas_shares * apply.monthly(FAS,last)[,4] +spxl_shares * apply.monthly(SPXL,last)[,4] #monthly historcal price


# weekly closed price chart
plot(fas_shares * apply.weekly(FAS,last)[,4] +spxl_shares * apply.weekly(SPXL,last)[,4])
# weekly candle chart
candleChart(to.weekly(fas_shares * FAS[,4] +spxl_shares * SPXL[,4]),theme='white')

# store weekly balance
weekly_pf <- fas_shares * apply.weekly(FAS,last)[,4] +spxl_shares * apply.weekly(SPXL,last)[,4]

2017年9月13日水曜日

use regular expression to pick up multiple columns to meet the criteria.

when columns as below

> names(b2b_mon_xts)
 [1] "SMB.Q"                      "Enterprise.Q"               "B2B.Total.Q"              
 [4] "SMB.Q.New"                  "SMB.Q.Renew"                "Enterprise.Q.New"        
 [7] "Enterprise.Q.Renew"         "SMB.Gross.Bkg"              "Enterprise.Gross.Bkg"    
[10] "B2B.Gross.BkgTotal"         "SMB.Gross.Bkg.New"          "SMB.Gross.Bkg.Renew"      
[13] "Enterprise.Gross.Bkg.New"   "Enterprise.Gross.Bkg.Renew" "SMB.Net.Bkg"              
[16] "Enterprise.Net.Bkg"         "B2B.Net.Bkg.Total"          "New"                      
[19] "Actual"    

use grep and it regular expression to pick up multiple columns to meet the criteria.
            
> b2b_mon_xts[,grep("^New|^Actual",names(b2b_mon_xts))]
           New Actual
2013-01-01 195    111
2013-02-01 344    165
2013-03-01 307    188
2013-04-01 322    223
2013-05-01 238    260
2013-06-01 237    254

2017年9月12日火曜日

PERL multi dimensional array

use strict;
use Text::CSV_XS;
my $csv = Text::CSV_XS->new ({ binary => 1 }); # open file w/ binary mode
# prepare array to store input file names;
# 2 arguments. no.1($ARGV[0]) is the original file and no.2($ARGV[1]) is the new file to compare each other.
my @inputfile = ($ARGV[0],$ARGV[1]);
my @origin;
my @new;

foreach my $count(@inputfile){
  # print "input file = $count\n"; # this line is for debug
  open my $fh, "<", $count; # case for foreach
  while (my $columns = $csv->getline ($fh)) {
    if($. == 1){ next;}  # skip the first line, as they are header info.
    #
    #  40 for cc addr, 21 for assignee, 21 for new alias(customer name), 0 for incident ID.
    #
    $$columns[40] =~ s/,/;/g; # replace comma with semi colong in the column no.40 CC history.
    $$columns[40] =~ s/ //g; # surpress all spaces in the line for future purpose.
    my @line;
    @line = ($$columns[21],$$columns[0],$$columns[12],$$columns[40]);
    if($count eq $ARGV[0]){ # arg no.0  is the name of original file.
      push @{$origin[$.-1]}, @line;  # store data into the multi dimension aray "origin" for original to compare.
    }
    if($count eq $ARGV[1]){ # arg no.1 is the name of new file.
      push @{$new[$.-1]}, @line; # into the buffer for new.
    }
  }
  close $fh;
  # print "close fh\n";  # this is for debug
}
my $size = @origin;
my $origin_size = @origin;
my $new_size = @new;
print "new size is ",$new_size,"\n";  # debug.
# print "file read end\n";
# foreach my $outbuf(@origin){
#   print @$outbuf[1],@$outbuf[2],@$outbuf[3],@$outbuf[4]," NL\n";
#
#   $size = @origin;
#   print "origin is ",$size,"\n";
# }
my $inc = 1;
my $alias = 2;
my $cc = 3;
my $assign = 0;
# debug output
# print "1 ",$origin[0][1],$origin[0][2],$origin[0][3],$origin[0][0]," NL\n";
# print $size," ",$origin[$size-1][1],$origin[$size-1][2],$origin[$size-1][3],$origin[$size-1][0]," NL\n";
# print "##################################\n";
# $size = @new;
# print "1 ",$new[0][1],$new[0][2],$new[0][3],$new[0][0]," NL\n";
# print $size," ",$new[$size-1][1],$new[$size-1][2],$new[$size-1][3],$new[$size-1][0]," NL\n";
print "############## start ####################\n";
# my $i = 1; my $j = 1;
for(my $i =0; $i <= $new_size-1; $i++){
  my $break = 0;  # initialize the flag if it is newly added in new or not.
  for(my $j=0; $j <= $origin_size-1; $j++){
    if($new[$i][$inc] eq $origin[$j][$inc]){  # all incident id in new is compared to the ones in origin.
        if($new[$i][$cc] ne $origin[$j][$cc]){ # when found the entry, compare cc history each other
          print "### unmatch ### ,";             # for the case there is delta.
        }else{
          print "### matched ### ,";             # or cc history is not updated at all.
        }
      print $new[$i][$assign],",",$new[$i][$inc],",\"",$new[$i][$alias],"\",",$new[$i][$cc],",=,",$origin[$j][$cc],"\n";
      last;   # exit if find the equal in the origin.
    }else{
      if($j == $origin_size -1){ # reached the final entry means this is new.
        print "### __new__ ### ,";
        print $new[$i][$assign],",",$new[$i][$inc],",\"",$new[$i][$alias],"\",",$new[$i][$cc],"\n";
      }
    }
  }
}
$csv->eof;

2017年8月9日水曜日

PAYEMS monthly delta and S&P500

plot(to.monthly(SP5)[kikan][,1],axes=T)
par(new=T)
plot(diff(PA[kikan]),axes=F,ylim=c(-900,900),col=3)
par(new=T)
plot(rep(0,length(PA[kikan])),col=2,ylim=c(-900,900),axes=F,type='l')




2017年8月6日日曜日

S&P500 vs. GDP and other macroecnomic data and PAYEMS moving average


1.S&P500 vs macroenomics

kikan <- "1992-01-01::2017-06-30"
x <- seq(min(as.Date(index(to.quarterly(SP5[kikan])[,1]))),as.Date(max(index(to.quarterly(SP5[kikan])[,1]))),"quarters")
plot(predict(lm(to.quarterly(SP5[kikan])[,1] ~ apply.quarterly(PA[kikan],mean) * apply.quarterly(UC[kikan],mean) * GDP[kikan] - apply.quarterly(UC[kikan],mean) )),type='l',col=2,axes=F,ylim=c(0,2500),ylab="")
par(new=T)
plot(x,to.quarterly(SP5[kikan])[,1],type='l',ylim=c(0,2500))
par(new=T)
plot(x,rep(2000,length(x)),type='l',col=4,ylim=c(0,2500)) # draw the line at 2000 level
axis(side=2, pos=as.Date("2017-01-01"),labels=F)  # draw aux axis at 2017-01-01
par(new=T)
plot(x,rep(2250,length(x)),type='l',col=4,ylim=c(0,2500)) # draw the line at 2250 level

2.PAYEMS

----------- updated
l <- 300  # length of sample period
a <- 6     # base for moving average
print(strsplit(kikan,"::")[[1]][1])
x <- last(seq(as.Date(strsplit(kikan,"::")[[1]][1]),as.Date(last(index(PA))),by="months"),n=(l-a))
plot(x,na.trim(filter(diff(last(PA,n=l)),rep(1,a))/a),type='h',ylim=c(-800,300))
axis(side=2, pos=as.Date("2017-07-01"),labels=F)
par(new=T)
plot(x,rep(last(na.trim(filter(diff(last(PA,n=l)),rep(1,a))/a)),length(x)),typ='l',col=2,ylim=c(-800,300))
paste(head(x)[1],last(x),sep="::")  
par(new=T)
plot(SP5[paste(head(x)[1],last(x),sep="::")],axes=F,col=3)  # add spx.
------------- ends here

l <- 300  # length of sample period
a <- 6     # base for moving average
x <- last(seq(as.Date("1992-01-01"),as.Date(last(index(PA))),by="months"),n=(l-a))
plot(x,na.trim(filter(diff(last(PA,n=l)),rep(1,a))/a),type='h',ylim=c(-800,300))
axis(side=2, pos=as.Date("2017-07-01"),labels=F)
par(new=T)
plot(x,rep(173,length(x)),typ='l',col=2,ylim=c(-800,300))


3.GDP

x <- seq(as.Date(strsplit(kikan,'::')[[1]][1]),as.Date(strsplit(kikan,'::')[[1]][2]),"quarters")
plot(x,G[kikan],type='h')
axis(side=2, pos=as.Date("2008-07-01"),labels=F,col=2)
axis(side=1, pos=15000,labels=F,col=3)




2017年8月3日木曜日

Draw graph S&P500 vs. refined GDP/S&P500 model



kikan <- "1992-01-01::2017-06-30"
x <- seq(min(as.Date(index(to.quarterly(SP5[kikan])[,1]))),as.Date(max(index(to.quarterly(SP5[kikan])[,1]))),"quarters")
result <- (lm(apply.quarterly(SP5[kikan],mean)[,1] ~ apply.quarterly(PA[kikan],mean) * apply.quarterly(UC[kikan],mean) * G[kikan] *PROP[kikan] - apply.quarterly(UC[kikan],mean) ))
plot(predict(result),type='l',col=2,axes=F,ylim=c(0,2500),ylab="")
par(new=T)
plot(x,to.quarterly(SP5[kikan])[,1],type='l',ylim=c(0,2500))
axis(side=2, pos=as.Date("2017-01-01"))  # draw aux axis at 2017-01-01
axis(side=2, pos=as.Date("2010-01-01"),labels=F)  # draw aux axis at 2010-01-01
par(new=T)
plot(x,rep(2400,length(x)),type='l',col=3,ylim=c(0,2500)) # draw the line at 2400 level

summary(result)

Residual standard error: 61.12 on 87 degrees of freedom
Multiple R-squared:  0.9863, Adjusted R-squared:  0.9841
F-statistic: 446.8 on 14 and 87 DF,  p-value: < 2.2e-16


2017年8月2日水曜日

PAYEMS and UNDCONTSA forecast

# --------------------------------------- starts here
 library(forecast)
 as.xts(forecast(auto.arima(PA),h=10)$mean[1:10],as.Date(as.yearmon(seq(mondate(index(last(PA)))+1,by=1,length.out=10))))[(3-month(index(last(PA))) %% 3) + c(1,4,7)]
# --------------------------------------- ends here
               [,1]
2017-10-01 147069.6
2018-01-01 147531.6
2018-04-01 147967.9

# --------------------------------------- starts here
as.xts(forecast(auto.arima(UC),h=10)$mean[1:10],as.Date(as.yearmon(seq(mondate(index(last(UC)))+1,by=1,length.out=10))))[(3-month(index(last(UC))) %% 3) + c(1,4,7)]
# --------------------------------------- ends here
               [,1]
2017-10-01 1063.764
2018-01-01 1060.613
2018-04-01 1058.185

my_sp5(as.xts(as.vector(last(GDP)) * 1.05**(2/4),as.Date("2017-10-01")),147069.6,1063.764)


> my_sp5(as.xts(as.vector(last(GDP)) * 1.05**(2/4),as.Date("2017-10-01")),147069.6,1063.764)
[1] "m_m params! apply.quarter - UC w/ nominal GDP"
               [,1]
2017-10-01 2584.023
> my_sp5(as.xts(as.vector(last(GDP)) * 1.05**(3/4),as.Date("2018-01-01")),147531.6,1060.613)
[1] "m_m params! apply.quarter - UC w/ nominal GDP"
               [,1]
2018-01-01 2677.544
> my_sp5(as.xts(as.vector(last(GDP)) * 1.05**(4/4),as.Date("2018-04-01")),147967.9,1058.185)
[1] "m_m params! apply.quarter - UC w/ nominal GDP"
               [,1]
2018-04-01 2767.471

2017年7月31日月曜日

S&P500,GDP,PAYEMS,UNDCONTSA

# --------------------------------------- starts here
l <- 120  # # of months to predict
i <- seq(2,l/3,1)  # seq of quarters to predict
d <- as.Date(as.yearqtr(seq(Sys.Date(),as.Date("2100-12-31"),by="quarters")[i])) # pick up the first day of each quarters.
r <- 1.05 # pesumed GDP growth rate
last(PA);last(UC);last(GDP)
m_GDP <- as.xts(as.vector(last(GDP)) * r**(i/4),d)
m_PA <- (as.xts(forecast(auto.arima(PA),h=l)$mean[1:l],as.Date(as.yearmon(seq(mondate(index(last(PA)))+1,by=1,length.out=l))))[(3-month(index(last(PA))) %% 3) + seq(1,l-3,3)])[d]
m_UC <- (as.xts(forecast(auto.arima(UC),h=l)$mean[1:l],as.Date(as.yearmon(seq(mondate(index(last(UC)))+1,by=1,length.out=l))))[(3-month(index(last(UC))) %% 3) + seq(1,l-3,3)])[d]
my_sp5(m_GDP,m_PA,m_UC)
# --------------------------------------- ends here

> my_sp5(m_GDP,m_PA,m_UC)
[1] "m_m params! apply.quarter - UC w/ nominal GDP"
               [,1]
2017-10-01 2584.017
2018-01-01 2677.548
2018-04-01 2767.463
2018-07-01 2855.281
2018-10-01 2942.127
2019-01-01 3028.843
2019-04-01 3116.057
2019-07-01 3204.248
2019-10-01 3293.780
2020-01-01 3384.937
2020-04-01 3477.938
2020-07-01 3572.961
2020-10-01 3670.150
2021-01-01 3769.625
2021-04-01 3871.485

2017年7月30日日曜日

2017Q2GDP and other economic data vs. S&P500


--------------------------------------------- starts here
last(GDP,n=3)
getSymbols("GDP",src="FRED");last(GDP,n=3)  # gdp
G <- GDP
last(PA)
getSymbols("PAYEMS",src="FRED");last(PAYEMS,n=3)  # non farm payroll
PA <- PAYEMS
last(UC)
getSymbols("UNDCONTSA",src="FRED");last(UNDCONTSA,n=3) # private housing under construction
UC <- UNDCONTSA
kikan <-  "1992-01-01::2017-04-30"
summary(lm(apply.quarterly(SP5[kikan],mean)[,1] ~ apply.quarterly(PA[kikan],mean) * apply.quarterly(UC[kikan],mean) * G[kikan] - apply.quarterly(UC[kikan],mean) ))
--------------------------------------------- ends here

Residual standard error: 104 on 95 degrees of freedom
Multiple R-squared:  0.9566, Adjusted R-squared:  0.9539
F-statistic:   349 on 6 and 95 DF,  p-value: < 2.2e-16