Thoughtful Thursday #8

Back at it again with another Thoughtful Thursday. School has kept me busy and I’ve been writing some different stuff so I took a short break from them. For those who don’t remember/know, this practice is inspired by Timothy Ferris’ 5-Bullet Friday where he lists 5 things he is keeping up on.

Timothy Ferris is a best selling author and self-proclaimed human guinea pig. If you are unfamiliar with his work, I highly recommend checking out his blog here: https://tim.blog/

What I’m Doing: I’ve been extremely busy learning to analyze and visualize data using python. School has been going great so far! In previous blogs, I’ve posted things I’ve done for homework assignments.

What I’m Missing: Since I shifted my hours back to mornings, and since school is eating up all of my free time, I have put trading on the back burner and have barely touched the markets lately. Overall, I needed a break from it anyways so I can come back with fresh eyes. I am working on some pretty cool stuff for Project Edge, and I’ve been experimenting with API calls to my broker. I can’t wait to get back into the game!

What I’m Watching: I’ve been watching old Family Guy episodes lately. Even at 32, I love cartoons. I haven’t kept up with anything after season 9, but I can’t tell you how many times I’ve gone through seasons 1-9 especially 1-5… The golden years.

What I’m Excited About: DESSERT TASTING! I am going to taste cakes with Kristen this Sunday so we can decide what to serve at the wedding. Only six months away! Also, it is almost Rigby’s birthday! I can’t believe we’ve almost had him for a year. Time sure flies.

What I’m Eating: I’ve been cooking a lot of pasta lately. Kristen and I didn’t eat it for the longest time, but lately we’ve been indulging. As an adult, I love red sauce! If kid me could see me know… He’d be disgusted.

One more for good measure:

What I’m Pondering: Carl Icahn’s summary of Anti-Darwinism in Corporate America, lol: https://oyc.yale.edu/economics/econ-252-08/lecture-15# An Anti-Darwinian Corporate America [00:06:10]

Assuming does What?

The assumption we’re all taught about assumptions is that they will make an a-s-s out of u-m-e… In other words, assuming too much can make you seem foolish. Color me foolish then because I find assumptions to be one of the most useful mental tools in my toolbox. I think they act as helpful mental shortcuts and can help maintain mental resilience. I make the following assumptions constantly; I am wrong a lot:

I assume I’ll be good at whatever I try. Why sell myself short before I even begin? When I am not good at something I feel I should be, instead of feeling discouraged, I find myself putting in more work and effort because I want my performance to sync with my mental framework. Even if my assumption is wrong and I end up being terrible at something, I know I put in effort to align my actions with my thoughts, and I don’t need to beat myself up about it.

I assume everything will be easy for me. Nothing comes without a learning curve, but believing something will be too hard before I begin is giving myself an excuse to avoid effort. For example, learning to code is one of the most challenging things I’ve done in a long time. Before beginning, I knew it was going to be challenging, but I believed it would be easy for me to overcome that challenge. I know it will take time to become fluent, but I believe it will be an easy road to travel if I pave it with patience, diligence, and honest feedback. I attribute my lack of proficiency to the steepness of the learning curve, not the difficulty of the task.

I assume that everything will be OK if my assumptions are wrong. Being wrong doesn’t have to be a blow to the ego. Just shrug it off and learn something! When I’m wrong, I consider it an opportunity to be honest with myself, and I give myself a chance to reflect. It allows me to self-correct and adapt my mental framework. I’d rather try and be wrong than be afraid and inactive.

Those three assumptions allow me to maintain a positive and resilient state of mind when I approach new tasks or need to learn new things. Although it might sound like overconfidence to some, it is an approach I use to reduce the weight of the external factors putting pressure on me. My assumptions act as mechanisms to help me align my thoughts and actions, and they act as frames for positive self talk. For example, instead of telling myself I’m terrible at writing python scripts when a concept doesn’t click, I make my assumptions and remind myself that I am good, and that it is easy, and that I am just not yet doing what it takes to perform at the level I imagine. My assumptions move me.

Two Python Scripts

For a homework assignment we had to write a couple python scripts. The first analyzes monthly financial data to find the average monthly change, and the min and max changes along with their corresponding month. The second one can be used to count votes for an election and determine the winner. Both scripts output to a text file. The second one uses Pandas Data Frames. Both written using python 3. These and more are available on my github:
https://github.com/bendgame

Find Monthly Change:

import csv
import os

#fetch the file
file = os.path.join ('..', 'PyBank','PyBank_data.csv')

#create placeholder lists for the data
months = []
net_total = []

with open (file, newline = "") as csvfile:
    readcsv = csv.reader(csvfile, delimiter = ',')

    csv_header = next(csvfile)
    
    #put the data into lists
    for row in readcsv:
        months.append(row[0])
        net_total.append(int(row[1]))
        
    #count the number of months
    month_count = len(months)
    
    #set variables for loops
    x = 1
    y = 0
    
    #average change place holder
    average_change = (net_total[1]-net_total[0])
    
    #place holder list for changes 
    changes = []
    
    #for loop to calculate month to month change and dump the values into a list
    for month in range(month_count-1):
        average_change = (net_total[x] - net_total[y])
        changes.append(int(average_change))
        x+=1
        y+=1
        
    
    #Calcuate the average monthly change and round it    
    av_mon_chng = round(sum(changes)/(month_count -1),2)

    #find the min and max change
    min_change = min(changes)
    max_change = max(changes)

    #return the index to find the positions in the list
    chng_i_min = changes.index(min_change)
    chng_i_max = changes.index(max_change)
    
    #find the months for the min and max changes
    min_chng_month = months[chng_i_min + 1]
    max_chng_month = months[chng_i_max + 1]
  

#Print the values in console

print("Financial Analysis")
print("----------------------------")
print(f"Months: {len(months)}")
print(f"Total: ${sum(net_total)}")
print(f"Average Monthly Change: {av_mon_chng}")
print(f"Greatest Increase in Profits: {max_chng_month} (${max_change})")
print(f"Greatest Decrease in Profits: {min_chng_month} (${min_change})")

#Write the output to a text file
fin_analysis = open("Financial_Analysis.txt","w")

fin_analysis.write("Financial Analysis\n")
fin_analysis.write("----------------------------\n")
fin_analysis.write(f"Months: {len(months)}\n")
fin_analysis.write(f"Total: ${sum(net_total)}\n")
fin_analysis.write(f"Average Monthly Change: {av_mon_chng}\n")
fin_analysis.write(f"Greatest Increase in Profits: {max_chng_month} (${max_change})\n")
fin_analysis.write(f"Greatest Decrease in Profits: {min_chng_month} (${min_change})\n")

 
fin_analysis.close() 

Count votes and determine a winner:

import pandas as pd
import os

# Make a reference to the csv file path
csvfile = os.path.join ('..', 'PyPoll','election_data.csv')

# read the csv file as a DataFrame
elec_data = pd.read_csv(csvfile)

df_ed = pd.DataFrame(elec_data)

#create an empty list to store vote counts as percent
percent_count = []

#Create a list of unique(distinct) candidates
candidates = list(df_ed["Candidate"].unique())

#count the number of times the candidate appears and put into a list
counts = list(df_ed['Candidate'].value_counts())

#get the total vote count
total_votes = sum(counts)

#set variable for for loop
x = 0

#for loop to calculate percentages
for candidate in candidates:
    percentage = round(counts[x]/total_votes,3)
    percentage="{:.3%}".format(percentage)
    percent_count.append(percentage)
    x+=1

#create a zipped list of data to rebuild data frame
data = list(zip(candidates, percent_count, counts))

#calculate counts to find winner
max_count = df_ed['Candidate'].value_counts()

#find the most counts
winner_count = max_count.max()

#put the zipped data into a data frame
df_data = pd.DataFrame(data)

#search the data frame for the candidate with the most counts put it into a list
winner = list(df_data.loc[df_data[2]== winner_count,0])

#rename the columns for df_data
sorted_data =df_data.columns =["Candidate |", "Percent of Votes |", "Vote Count"]

#sort the columns by vote count in descending order for clean output
sorted_data = df_data.sort_values("Vote Count", ascending = False )

#print the output into console
print("Election Results")
print(" -------------------------")
print(f"Total Votes: {total_votes}")
print("--------------------------")
print(f"{sorted_data}")
print(f" -------------------------")
print(f"Winner: {winner}")
print(f"-------------------------")

#Write the outcome data to a txt file named election_winner

election_winner = open("election_winner.txt","w")

election_winner.write("Election Results\n")
election_winner.write("----------------------------\n")
election_winner.write(f"Total Votes: {total_votes}\n")
election_winner.write(f"--------------------------\n")
election_winner.write(f"{sorted_data}\n")
election_winner.write(f" -------------------------\n")
election_winner.write(f"Winner: {winner}\n")
election_winner.write(f"-------------------------")

election_winner.close()

When I stopped Procrastinating

No lies. In my younger years, I procrastinated a lot. I was always putting off homework and chores until I forgot about it. For whatever reason, I didn’t take many things seriously, and I didn’t care about doing things on time. Sure, I wanted to be smart, and I loved delving into things for which I had passion like computers and dancing, but I mostly wanted one thing in life: To be cool. I wasn’t.

What did it mean to be cool to me? In a simple definition, I wanted to live the life in which men wanted to be me and women wanted to be with me. I filled my head with pop-culture references and started reading self-help classics like How to Win Friends and Influence People. I read up on philosophy so I could wax intellectual with the artsy hippies, and I got into dance music so I could relate to the people partying in the clubs. I did everything I could think of to meet girls, become wise, and stay fit. I met some extraordinary women and made some great friends along the way, but I always suffered from shyness and a bit of social anxiety. Although an annoyance, that anxiety drove me to learn to prepare.

Once I got into a degree program at the University of Minnesota, I still wanted to be cool, but I started taking my academics seriously. Although I didn’t have my procrastination problem completely figured out, I was in a writing intensive program, and I felt I had something to prove. Transferring in from a community college, I felt my college experience was lacking. Everyone seemed smarter and better connected since most of the people in my cohort had started their undergrad at the U of M. I thought I had to catch up. I was wrong.

Most people were average, too busy to try, and not nearly as smart as I thought. Some people even openly admitted to plagiarizing content and simply changing words using Word’s thesaurus before handing it in as their own. I found that despicable and vowed to outwork the lot of them. If they were studying one hour, I was studying two. If they were posting essays, I was critiquing them. They were my competition, and I wanted to see what they were made of. That is when I stopped procrastinating.

One of the of the first things I noticed was anxiety relief. If I just took care of things when they were assigned, I didn’t need to think about them anymore. My mind was free to focus on my passions. It didn’t matter that I had to sacrifice the time; I still found a way to party plenty. With the changed perspective, I transformed into a bit of a workaholic.

The second thing I noticed was an overall improvement in my content. Since I had extra time to edit and expand the ideas, I was able to push my research, imagination, and explore the depths of my creativity. I was relentlessly critical in my self-talk, and I carefully crafted rhetorically sound arguments in my essays. I was proud to earn A’s from professors who rarely gave them. I showed promise, and I loved it.

These habits shaped the way I approached work too. I wasn’t employed to slack off; I was there to climb the ladder. Employment is a zero-sum game. If someone else gets the promotion, that means I can’t. It was just another environment in which procrastination wouldn’t cut it. I decided I am the guy to pick up the slack and step up to take the responsibility no one else wants. That work ethic has led to promotions at every job I’ve ever held. I am a ladder climber. I am a grinder. I am willing to put in the work.

Adopting an ethic in which procrastination is an after-thought got me to where I am today: 32 years young and still perpetually moving forward by writing, coding, and climbing the corporate ladder. I recently completed a certification in Data Analytics and designed my first web app. I’ve climbed the ladder into a technical position at work. I’m getting married to a great woman at the end of the year, have a lovely home and adorable dog… I have what’s left of the American dream, and I’m not about to stop plotting my path to wealth and retirement. All of this hard-work will pay off; it already has, and I think that is pretty cool.

Using VBA to Analyze Stocks

Coding in VBA to crunch excel spreadsheet data wasn’t very fun, but it was good mental exercise and got my mind working. I found the language obtuse compared to python, and making mistakes that output to the spreadsheet was annoying to clean up. Not to mention the numerous times I crashed the excel application with infinite loops, lol. Either way, I am proud of the code I wrote. I don’t do much stock analysis in excel, and typically use SQL and python for that stuff, but I still might revisit this exercise and use it to crunch some of the stock and option data I collect. My code produces the I-L values:

Sub stock_hw()

Dim total_rows As Double
Dim sym_array() As Variant
Dim total_volume As Double
Dim i As Long
Dim j As Long
Dim unique_syms As New Collection
Dim sym As Variant
Dim ws As Worksheet
Dim unique_index As Double
Dim first_price As Double
Dim last_price As Double
Dim first_bool As Boolean
Dim prcnt_chng As Double

'Creates the loop to go through each worksheet in the workbook
For Each ws In Worksheets

    'activate the worksheet and enter new column names in J and K
    ws.Activate
    
    'insert the headers
    Cells(1, 9).Value = "Ticker"
    Cells(1, 12).Value = "Total Volume"
    Cells(1, 10).Value = "Yearly Change"
    Cells(1, 11).Value = "Percent Change"
    
    'calculate the total rows to use in the array range
    total_rows = Rows(Rows.Count).End(xlUp).Row
    
    'add stock tickers to array
    sym_array = Range(Cells(2, 1), Cells(total_rows, 1)).Value
    
    'loop through array to find distinct values and add them to a collection object
    'set the collection to Nothing to reset it on each worksheet
    
    Set unique_syms = Nothing
    
    'resuming on error is needed or it will error on duplicate values
    On Error Resume Next
    For Each sym In sym_array
    unique_syms.Add sym, sym
    Next
  
'populate column J with distinct ticker values
    For i = 1 To unique_syms.Count
        Cells(i + 1, 9).Value = unique_syms(i)
    Next i

'USED FOR DEBUGGING 'Cells(1, 11).Value = Cells(2, 1).Value
'USED FOR DEBUGGING 'Cells(1, 14).Value = Cells(2, 9).Value
      
    'check to see if the distinct value = sym and total the volume if it does
    'j loops through the master ticker list
    'unique_index is used to stay on the correct distinct ticker
    'set the first boolean to true so the logic knows to store the first price
    
        first_bool = True
        unique_index = 2
        For j = 2 To total_rows + 1
            If Cells(j, 1).Value = Cells(unique_index, 9).Value Then
               total_volume = Cells(j, 7).Value + total_volume
               
               'Logic for storing the first price when it is greater than 0
                 If first_bool = True And Cells(j, 6).Value > 0 Then
                    first_price = Cells(j, 6).Value
                    
                   'set the first boolean to false so the logic doesn't change the first price
                    first_bool = False
                 End If
                
            Else
                'subtract 1 from j so you don't skip the first row for the next distinct ticker
                'also so you can select the correct last closing price
                 j = j - 1
                 
                 'set the last closing price value
                last_price = Cells(j, 6).Value
                
                'output volume
                Cells(unique_index, 12).Value = total_volume
                
                'output difference between start and end price
                Cells(unique_index, 10).Value = last_price - first_price
                
                'calculate the percent change
                prcnt_chng = ((last_price / first_price) - 1) * 100
                
                'output the percent change
                Cells(unique_index, 11).Value = prcnt_chng
               
               'format the cell color based on the percent change being positive or negative or 0
                    If prcnt_chng > 0 Then
                        Cells(unique_index, 10).Interior.ColorIndex = 4
                    ElseIf prcnt_chng < 0 Then
                        Cells(unique_index, 10).Interior.ColorIndex = 3
                    Else
                        Cells(unique_index, 10).Interior.ColorIndex = 2
                    End If
                                        
                'increase the unique index
                unique_index = unique_index + 1
                
                'rest the sum of volume so it doesn't carry over for the next ticker
                total_volume = 0
                
                             
                'reset the boolean value for figuring the first price
                first_bool = True
           
           'USED FOR DEBUGGING ' Cells(1, 11).Value = first_price
           'USED FOR DEBUGGING ' Cells(1, 14).Value = last_price
            End If
         Next j
'USED FOR DEBUGGING 'Cells(1, 15).Value = total_volume
      ws.Columns("A:M").AutoFit
    Next ws
End Sub

Thoughtful Thursday #7

Another thoughtful Thursday coming to you Saturday. Thursday has become homework day since I’m back in school, so I have less time to pump these out on those days. Even so, I’m still sticking with the title…

What I’m playing: The new league in Path of Exile dropped on Friday. I wish I had more time to play it! It seems pretty fun. I just hope the end game more rewarding than the last league. The new boss fights in the previews were really cool looking, so hopefully they aren’t going to be too rare, but it is GGG, so they I won’t hold my breath… Anyone unfamiliar, Path of Exile is a completely free to play action rpg. I’ve been playing it for 6 years. I can’t recommend it enough!

What I’m thinking: We got our 3rd homework assignment today! It is writing a couple python scripts to analyze some finical and polling data. My start to this assignment is going much smoother than the last one! Hopefully that means I’m thinking more algorithmically. I’ve worked in python a little bit before the class, so not everything was brand new. I can’t wait until we start working with Pandas and matplotlib!

What I’m eating: I’ve been making ranch wraps with bacon crusted turkey, shredded cheese, tomato, oregano, and a pinch of Lowry’s salt. They are delicious hot or cold. I’ve been bringing them to class with me in my new Titan lunch cooler.

What I’m watching: We’ve had Friends replaying in the background still. I think we’re both about sick of it though. I had a good laugh when Chandler gets a new laptop and is bragging about the 12mb of ram, built in spreadsheet capabilities, and 500mb hard drive it has. Our phones blow that away these days, let alone my gaming computers, hahaha.

What I’m missing: I miss trading. Being in school and working the morning shift leaves little time for me to keep up with the markets. I’ll be back on the grind eventually, but I definitely don’t need any more stress in my life, especially with a wedding around the corner.

Thoughtful Thursday #6

A few days late on this one, but better late than never!

What I’m doing: It feels great to be a student again. Every time I get out of my car and walk into the UofM building, I think about all the brilliance that has been through those doors before me and become inspired. Class is tough, but everyone in it seems supportive, and the teacher and TAs seem great. I’ve always believed you get out what you put in when it comes to learning, so I’ve been trying to put in 100%. This is only the beginning, but I love it so far.

What I’m watching: True Detective season 3 is over, but I haven’t finished it. We will be watching the last three episodes tomorrow. I can’t wait to find out how it ends. This season might be better than the first. The show we keep on in the background lately has been Friends. It is funny to see how many actors play small roles in it and also appear in shows like The Office, Parks and Rec, and others.

What I’m eating: Kristen finally let me cook salmon for her! I prepared it like my mom used to do: Miracle whip, garlic and Parmesan. Kristen loved it!

What I’m playing: I haven’t had much time for games lately, but I reinstalled Hunt: Showdown, and completely forgot how awesome that game is. I am glad they keep adding more content.

What I’m lifting: It’s still snowing.

Thoughtful Thursday #5

What I’m thinking: Since we have had a ton of snow this February, I’ve been thinking about my shovel technique. I think the best way to shovel a driveway is to start down the middle vertically. Then, horizontally push the snow closer to the banks of the driveway until you’re close enough to throw the snow far enough to prevent high snow banks. Shovel every 2.5-3 inches for the easiest time. Beyond that it becomes too much to push horizontally and gets heavy.

What I’m doing: I started school! We got our first assignment: Analyze 4000+ kickstarter records to identify 3 trends. So far, class is fun. I think the teacher has done a great job, and the cohort seems like a diverse group of bright people. I can’t wait to see how the class evolves.

What I’m listening to: My coworker turned me on to Denzel Curry (rap). I like a few of the tracks, but I’ll have to give it another listen before I can recommend any tracks. I’ve been listening to his albums on Spotify.

What I’m eating: I started eating a lot of nuts again. I prefer the Raw Unsalted mix nuts from target since it has a good variety! The pistachios are always soft.

What I’m watching: I discovered Hulu has Boston Legal! I used to watch that show with my mom when it first aired. I remember some of the episodes so far, but we’re still in season 1. I can’t wait to finally know how the series ends!

Thoughtful Thursday #4

I’m back to the blogosphere… if that is still a thing. Happy Valentine’s day!

What I’m doing: I have been enjoying my last week of freedom before the Data Analysis coding camp begins. The new video game, Apex Legends has captivated me and my group of friends. It is great to play if you have a squad of friends to play with; otherwise, it can be a bit of a drag playing with random people. I am excited to see how the game evolves, and I’m already impressed by the impact it has had on EA’s stock price.

What I’m watching: True detectives season 3 has been phenomenal so far. If you have an HBO subscription and aren’t watching it, stop reading this right now and turn on episode 1. You will not be disappointed as long as you’re into that genre. Besides that, we finally got bored of the office and started reruns of New Girl. That show is hilarious.

What I’m reading: I’ve been reading a lot of blogs relating to Data Science in an effort to familiarize myself with some concepts and terminology before school begins. I’ve explored decision trees, linear regression, and gradient boosting models using python and sci-kit learn so far, and I can’t wait to learn more about the mathematics and methodologies used for analyzing data!

What I’m eating: We cooked up a big batch of pork fried rice over the weekend! We threw in lots of broccoli, peas, garlic, basil, egg, and diced pork. It turned out great! Thanks kikkoman!

What’s I’m lifting: I live in Minnesota and the amount of snow getting dumped on us this year is impressive. We haven’t had this much snow in a long time so I should really dust off my skis and hit the hills! Shoveling along with a light kettle-bell workout is all I’ve needed to keep my muscles sore.

Thoughtful Thursday #3

What I’m Doing: I have the rest of the week off of work and am focusing on improving my python. I figured out how to connect to my Microsoft SQL Server using pyodb. Here is the easy to remember connection string using set variables:

cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)

From there, I have been using pandas and matplotlib to graph some of the financial data I store in my “Project Edge” database. I am practicing elements of feature engineering to see if I can get more insight from my data using machine learning in the future.

What I’m Lifting: As a Christmas gift to myself, I bought a 15lb kettle-bell and have been swinging that around a little bit. I want to get back into the gym, but I’ll tackle switching my hours and getting back to school first. In the meantime, I enjoy using it to work out and wish I would have gotten one sooner.

What I’m Eating: We made some fajita seasoning using some spices and herbs we had sitting around, and then cooked up a big batch of chicken and peppers. It was delicious! Much better than the store bought seasoning we used last time. Unfortunately, no margaritas since we’ve been out of tequila for months.

What I’m Thinking about: I can’t wait for warm weather. The past couple days have been the coldest days of the year coming in at -35f. Rigby couldn’t even last outside for more than thirty seconds!

What I’m Studying: I’ve been trying to add more elements of technical analysis to my financial data database, so I’ve been researching how to write things like sma, ema, Bollinger bands, RSI, etc… Some of them are much more difficult to write in SQL than I would have imagined! It has been some fun problem solving.