create account

Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python by geekgirl

View this thread on: hive.blogpeakd.comecency.com
· @geekgirl ·
$10.17
Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python
I have been working on a simple script to automate records keeping for daily price changes for stocks in the watchlist. Previously I wrote in [What if your code is ugly but it works? Amateur python programmers journey](https://leofinance.io/hive-167922/@geekgirl/what-if-your-code-is-ugly-but-it-works-amateur-python-programmers-journey) how I was able to finish the project's core logic and was getting functional results, yet code wasn't organized well. This week I was able to make improvements in the organization of the code, fixing bugs, and adding styles to an output excel files so the end result looked good as well. I will share the screenshots for the full code at the end of the post. If you find it useful and would like a text version, I will be glad to share that as well.

Today, I would like talk about the purpose and potential use cases for a simple script like this, go through the logic of the code and how to apply styles to an excel file with python.

<center>**What is the purpose of this code?**</center>

I wrote it for a personal use to automate manual entry of daily price changes for stocks I am watching for a given week. However,  I can see it being used for testing various trading strategies, trading tips from others, and gathering data for making better trading decisions. While in its current form code only works to keep track of price changes of the current week, with simple date change it can also check prices in the past and be useful for backtesting.

One of my next projects will be working on is to automate picking stocks based on various strategies. Combing that with this code will help in seeing how each strategy is performing. 

<center>**Logic of the code.**</center>

![main.png](https://images.hive.blog/DQmSB2d9LbxmDASU7DkRRmeLdLg53c3isbbzc3eyKXT8RSv/main.png)

As I was trying to better organize the code I put most of the functionality into functions, so it is easier to reuse the functions elsewhere and make changes when needed. Then wrote calls to the functions in the main code section after `if __name__ == '__main__':`line per pythonic convention.

The main variable user would need to update every week is ***stocks*** variable with the list of stocks in the watchlist. Optionally, user can also change the values for ***strategy***, ***position***, and ***today***(date) variables. By default, they can be autofilled. Auto versions of the variables can be commented out and manual entered values uncommented as needed. To generate auto list of text values for ***strategy*** and ***positions***, we use ***auto_list(stocks, text)*** function to make a list of the same size as number of stocks in the watchlist. 

Second function is ***get_dates()***, which takes the date argument by default it is today's date. Then returns a list of dates that we need to get the stock prices for. Since research and preparation for the trading week is mostly done on weekends, the first date we use is Friday for the last and current prices. Depending on the week of the day, function also returns active trading days for the week until today or chosen date.

***get_xl_file_path('watchlist.xlsx)*** returns the absolute path to the excel file where all the data will be stored.

Everything up this point was a preparations of variables that will be used in the core function of the script that will get all the data from Yahoo Finance, open the Excel file, and store gathered data in a worksheet. ***build_xl_file_worksheet() is the core function. Arguments it takes are ***file_path***, ***stocks***, ***dates***, ***strategy***, and ***position***.

After the data is stored in the worksheet, this function returns a name of the updated or created worksheet, so that next we can apply styles to the file and make the worksheet more presentable. That takes us to our last function - ***apply_styles_xl()***. It will need ***file_path*** argument and with some new arguments. ***sheet_name*** is the name of the worksheet the styles will be applied on and was returned when worksheet data was stored. ***last_row*** and ***date_columns*** will help with identifying number of rows and columns used in storing data. 

<center>**Applying styles to an excel file.**</center>

**Openpyxl** module provides us with ability not only to manipulate data in excel files but also to apply and change styles.  The last function in the script, ***apply_styles_xl(file_path, sheet_name, last_row, date_columns), opens the excel file we are working with and the worksheet where the data is stored, and goes through all filled cells and apply necessary styles. Following is the list of style changes it applies:
1. Changes font size of the title cell to 24px, aligns values to center, and adds background fill color gray. 
2. Changes font size of the header row cells to 20px, aligns values to center, and adds background fill color gray.
3. Changes font size of the Stock names, Strategy, Position cells to 20px, aligns values to center, and adds background color gray.
4. Changes font size of Friday/Main prices column cells to 20px, and adds background color yellow.
5. Goes through each cell in the rest of the price columns, compares the prices to the Friday/Main prices. If price is higher adds background color green, if price is lower or equal adds background color red. Also changes the font size to 20px.
6. Goes through each column with data and adjusts width of the columns based on the longest value in the column, so that everything is visible.

The title cell was also merged among nine columns using ***sheet.merge_cells("B2:J2")*** method. This caused a problem when readjusting widths of columns, because title text in "B2" cell was too long and made every cell in column "B" of the same width. To avoid that, I simply added a comparison check to skip "B2" when calculating the width for the rest of the "B" cells. End result looks like the picture below.

![xl.png](https://images.hive.blog/DQmPFrdk43jfc6jvb3sTPtKpBRRUaKkMENmrwp1a84y28kL/xl.png)

Applying styles with **openpyxl** is straightforward with easy cell object properties like ***.font***, ***.fill***, ***.alignment***, etc and using module classes like ***Patternfill()***, ***Font()***, ***Alignment()***, ***Border()***, etc.

One problem I faced was that I wasn't able to apply styles to a range of cells at the same time. Only option I had was to apply styles to one cell at a time. With python iterations loops it is not big problem. Applying changes to one cell at the time works. 

<center>**Screenshots of the Code**</center>

<center>![code1.png](https://images.hive.blog/DQmfABSt7i5453tVMwntD9DaYRpXn4itTRK3yUs3tmD5s3t/code1.png)</center>

<center>![code2.png](https://images.hive.blog/DQmVrenpiKW8Ugp8Wb28mvLnWc8Y4jXQPoPohSo3X1YcZP8/code2.png)</center>

<center>![code3.png](https://images.hive.blog/DQmPDcRK2u6LifsmjHTQJRFTgpTdnmA8fqev842bAy6vHDD/code3.png)</center>

<center>![code4.png](https://images.hive.blog/DQmcJCYr9iVqZaAHaYePhwHwAsDjvPDDJ71uxuu9LgtLXGX/code4.png)</center>

<center>![main.png](https://images.hive.blog/DQmSB2d9LbxmDASU7DkRRmeLdLg53c3isbbzc3eyKXT8RSv/main.png)</center>

Posted Using [LeoFinance](https://leofinance.io/@geekgirl/automating-stocks-watchlist-daily-price-updates-improving-an-ugly-code-and-applying-styles-to-an-excel-file-with-python)
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 109 others
👎  
properties (23)
authorgeekgirl
permlinkautomating-stocks-watchlist-daily-price-updates-improving-an-ugly-code-and-applying-styles-to-an-excel-file-with-python
categoryhive-167922
json_metadata{"tags":["python","coding","stocks","trading","stem","dev","neoxian","ctp","pal","automating","excel","leofinance"],"image":["https://images.hive.blog/DQmSB2d9LbxmDASU7DkRRmeLdLg53c3isbbzc3eyKXT8RSv/main.png","https://images.hive.blog/DQmPFrdk43jfc6jvb3sTPtKpBRRUaKkMENmrwp1a84y28kL/xl.png","https://images.hive.blog/DQmfABSt7i5453tVMwntD9DaYRpXn4itTRK3yUs3tmD5s3t/code1.png","https://images.hive.blog/DQmVrenpiKW8Ugp8Wb28mvLnWc8Y4jXQPoPohSo3X1YcZP8/code2.png","https://images.hive.blog/DQmPDcRK2u6LifsmjHTQJRFTgpTdnmA8fqev842bAy6vHDD/code3.png","https://images.hive.blog/DQmcJCYr9iVqZaAHaYePhwHwAsDjvPDDJ71uxuu9LgtLXGX/code4.png"],"links":["https://leofinance.io/hive-167922/@geekgirl/what-if-your-code-is-ugly-but-it-works-amateur-python-programmers-journey"],"app":"leofinance/0.1","format":"markdown","canonical_url":"https://leofinance.io/@geekgirl/automating-stocks-watchlist-daily-price-updates-improving-an-ugly-code-and-applying-styles-to-an-excel-file-with-python"}
created2020-07-02 07:36:06
last_update2020-07-02 07:36:06
depth0
children12
last_payout2020-07-09 07:36:06
cashout_time1969-12-31 23:59:59
total_payout_value5.400 HBD
curator_payout_value4.772 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7,307
author_reputation1,586,488,611,824,452
root_title"Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,295,269
net_rshares28,000,520,692,305
author_curate_reward""
vote details (174)
@chitty ·
I have picked your post for my daily hive voting initiative, Keep it up and Hive On!!
properties (22)
authorchitty
permlinkre-automating-stocks-watchlist-daily-price-updates-improving-an-ugly-code-and-applying-styles-to-an-excel-file-with-python-20200706t000102
categoryhive-167922
json_metadata""
created2020-07-06 00:01:03
last_update2020-07-06 00:01:03
depth1
children0
last_payout2020-07-13 00:01:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length86
author_reputation86,901,300,608,582
root_title"Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,362,669
net_rshares0
@gitplait-mod1 ·
$0.14
Improvements come by doing efforts. It is so nice of you to share amazing python tutorial integrated with ms excel. Your efforts are laudable. 

<sub> Your post has been submitted to be curated with @gitplait community account because this is the kind of publications we like to see in our community. </sub>

Join our [Community on Hive](https://hive.blog/trending/hive-103590) and Chat with us on [Discord](https://discord.gg/CWCj3rw).

[[Gitplait-Team]](https://gitplait.tech/)
👍  
properties (23)
authorgitplait-mod1
permlinkqcu7sc
categoryhive-167922
json_metadata{"users":["gitplait"],"links":["https://hive.blog/trending/hive-103590","https://discord.gg/CWCj3rw","https://gitplait.tech/"],"app":"hiveblog/0.1"}
created2020-07-02 10:29:03
last_update2020-07-02 10:29:03
depth1
children1
last_payout2020-07-09 10:29:03
cashout_time1969-12-31 23:59:59
total_payout_value0.070 HBD
curator_payout_value0.070 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length479
author_reputation64,455,719,431
root_title"Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,297,333
net_rshares610,328,517,909
author_curate_reward""
vote details (1)
@geekgirl ·
Thank you @gitplait!
properties (22)
authorgeekgirl
permlinkre-gitplait-mod1-qcuyol
categoryhive-167922
json_metadata{"tags":["hive-167922"],"app":"peakd/2020.07.1"}
created2020-07-02 20:09:57
last_update2020-07-02 20:09:57
depth2
children0
last_payout2020-07-09 20:09:57
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length20
author_reputation1,586,488,611,824,452
root_title"Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,305,776
net_rshares0
@mytechtrail ·
$0.31
I would very much like to access a text version of you code so that I can experiment and learn from it,

Thanks for sharing.
👍  
properties (23)
authormytechtrail
permlinkre-geekgirl-qcuuu2
categoryhive-167922
json_metadata{"tags":["hive-167922"],"app":"peakd/2020.07.1"}
created2020-07-02 18:46:51
last_update2020-07-02 18:46:51
depth1
children2
last_payout2020-07-09 18:46:51
cashout_time1969-12-31 23:59:59
total_payout_value0.154 HBD
curator_payout_value0.154 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length124
author_reputation18,997,364,795,810
root_title"Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,304,679
net_rshares1,268,069,386,004
author_curate_reward""
vote details (1)
@geekgirl ·
Hi @mytechtrail! You can find the full code here: 

https://github.com/librarian-hive/automate-stocks-watchlist/blob/master/watchlist.py

Before running the script, make sure to pip install all imported dependencies and also create a 'watchlist.xlsx' file. You man have to change the path to the file in the code too. 

Thank you.
properties (22)
authorgeekgirl
permlinkre-mytechtrail-qcuy0u
categoryhive-167922
json_metadata{"tags":["hive-167922"],"app":"peakd/2020.07.1"}
created2020-07-02 19:55:42
last_update2020-07-02 19:55:42
depth2
children1
last_payout2020-07-09 19:55:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length330
author_reputation1,586,488,611,824,452
root_title"Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,305,576
net_rshares0
@mytechtrail ·
$0.13
Thank you for the link and your Welcome for posting your experience.

I created <a href="https://peakd.com/c/hive-164872/created" rel="nofollow noopener" title="This link will take you away from peakd.com">Learning Python Community</a>
 if you would like to post there in the future.
👍  
properties (23)
authormytechtrail
permlinkre-geekgirl-qcv4al
categoryhive-167922
json_metadata{"tags":["hive-167922"],"app":"peakd/2020.07.1"}
created2020-07-02 22:11:00
last_update2020-07-02 22:11:00
depth3
children0
last_payout2020-07-09 22:11:00
cashout_time1969-12-31 23:59:59
total_payout_value0.066 HBD
curator_payout_value0.066 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length283
author_reputation18,997,364,795,810
root_title"Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,307,269
net_rshares581,191,440,910
author_curate_reward""
vote details (1)
@puncakbukit ·
Very useful and interesting program..   Maybe the next step is to add some AI to predict the stock price in the future.. 😎
properties (22)
authorpuncakbukit
permlinkqcw66c
categoryhive-167922
json_metadata{"app":"hiveblog/0.1"}
created2020-07-03 11:49:27
last_update2020-07-03 11:49:27
depth1
children0
last_payout2020-07-10 11:49:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length122
author_reputation59,018,532,294,625
root_title"Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,316,725
net_rshares0
@roleerob · (edited)
$0.30
As much more of a "part-timer" more these days @geekgirl, I enjoyed reading through this and getting a sense of your "shift" in focus on creating new content.  Sad to me and, I would imagine, to a much greater degree with you, to see what became of the Hunt community.  I know you invested a great deal of time into it and were (from my perspective) very good at it.

Your new focus of investing and coding is something I have experienced in the past.  And, perhaps, will have time to get into more in the future.  I will look to your posts, for encouragement, if and when I do ...

Until next time, I hope all is well with you and yours, my friend, in this crazy "new normal" world of ours. 👋
👍  
properties (23)
authorroleerob
permlinkre-geekgirl-qcuh9g
categoryhive-167922
json_metadata{"tags":["hive-167922"],"app":"peakd/2020.07.1"}
created2020-07-02 13:53:42
last_update2020-07-02 13:54:15
depth1
children4
last_payout2020-07-09 13:53:42
cashout_time1969-12-31 23:59:59
total_payout_value0.152 HBD
curator_payout_value0.152 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length693
author_reputation121,016,488,104,457
root_title"Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,300,096
net_rshares1,242,817,283,250
author_curate_reward""
vote details (1)
@geekgirl ·
$0.16
Thank you @roleerob! Always great to hear from you. Yea things with Hunt project turned out to be a disappointment. At the same time I realized tech product posts don't really have to use Hunt platform. They can be posted directly on Hive. With tech loving communities like Stem, it may even be more fun.

I did shift focus to trading, and coding a little bit for those purposes. So, I figured why not share that. Also, @trumpman encouraged to start using leofinance.io, one of the the most active tribes on Hive.

Thanks again. Hopefully things will become better soon. 2020 is due for some positivity.
👍  
👎  
properties (23)
authorgeekgirl
permlinkre-roleerob-qcuyn6
categoryhive-167922
json_metadata{"tags":["hive-167922"],"app":"peakd/2020.07.1"}
created2020-07-02 20:09:03
last_update2020-07-02 20:09:03
depth2
children3
last_payout2020-07-09 20:09:03
cashout_time1969-12-31 23:59:59
total_payout_value0.078 HBD
curator_payout_value0.078 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length603
author_reputation1,586,488,611,824,452
root_title"Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,305,768
net_rshares677,900,546,513
author_curate_reward""
vote details (2)
@roleerob ·
$0.22
Glad to "hear" you appear to be doing well @geekgirl.  Although I have often been challenged as to "what on earth are you doing in there?", associations with people like you is what has kept me going "in here." 🙂

Interesting that you mention Stem community as an alternative place for your tech product posts.  I don't know anything about them, but isn't that community doing quite well on Hive Engine?

Speaking of which ...

> *"Also, @trumpman encouraged to start using leofinance.io, one of the the most active tribes on Hive."*

... I had not even noticed you posted this on LeoFinance.  I actually just wrote my first post (or at least attempted to ...) on LeoFinance and trying to execute my first ever market trade on LeoDex.  *"Great minds think alike"* ... 😉

As mentioned in the post, always the "good soldier," I had never powered down anything on ~~Steem~~, so never had any discretionary funds to consider trading in some of these other tokens.  So, with some now, I decided to increase my LEO stake.

But ... It didn't go too well ... 🙃

I am persistent, though, so I will be back to try again, as time permits.

> *"2020 is due for some positivity."*

No doubt about that, my friend.  I wonder if we will actually see much of it, as this world just seems to be going to pieces ...

Well, take care and I'll stay in touch, from time to time! 👋
👍  ,
properties (23)
authorroleerob
permlinkre-geekgirl-qcv11y
categoryhive-167922
json_metadata{"tags":["hive-167922"],"app":"peakd/2020.07.1"}
created2020-07-02 21:01:12
last_update2020-07-02 21:01:12
depth3
children2
last_payout2020-07-09 21:01:12
cashout_time1969-12-31 23:59:59
total_payout_value0.110 HBD
curator_payout_value0.110 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,359
author_reputation121,016,488,104,457
root_title"Automating Stocks Watchlist Daily Price Updates: Improving an ugly code and applying styles to an excel file with python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,306,488
net_rshares935,151,294,809
author_curate_reward""
vote details (2)