Jump to content
  • 0

UK Capital Gains report for Smart Portfolios - MySQL script to calculate it


dabb1er

Question

Posted

I was disappointed to discover that the IG platform does not provide Capital gains figures for the reballancing and monthly transaction fees on any shares account (easier to track share account but Smart Portfolio in its nature is harder as you are not in control of transactions)

In order to resolve this I created a MySQL script to calculate the allowable costs to offset against sales for each of the transactions.

Just export all your transactions to a csv file and import this into a MySQL database (free to install on numerous platforms).

The SQL query at the end will provide a report that can be exported showing your gains/losses for each SELL transaction.

Obviously use this script at your own risk - this was created purely for my personal use and manual checking of the first few units showed it was calculating accurately based on UK's HMRC's current allowance for a 104 section holding.

 

The script is listed below:

/* use this script with a MySQL database */
/* use MySQL workbench data import wizard to import data into tradehistory_import table into a schema called smartportfolio */
/* make sure the date and time fields at the start of the table have their name changed to tdate and ttime */

use smartportfolio;
ALTER TABLE `smartportfolio`.`tradehistory_import` 
CHANGE COLUMN `Cost/Proceeds` `Cost_Proceeds` DOUBLE NULL DEFAULT NULL ,
CHANGE COLUMN `Conversion rate` `Conversionrate` DOUBLE NULL DEFAULT NULL ,
CHANGE COLUMN `Order type` `Order_type` TEXT NULL DEFAULT NULL ,
CHANGE COLUMN `Venue ID` `VenueID` TEXT NULL DEFAULT NULL ,
CHANGE COLUMN `Settlement date` `Settlement_date` TEXT NULL DEFAULT NULL ,
CHANGE COLUMN `Order ID` `OrderID` TEXT NULL DEFAULT NULL ; 
drop table if exists tradehistory;
create table tradehistory as select *,str_to_date(concat(tdate, ' ',ttime),"%d-%m-%Y %H:%i:%s") as tradedate from tradehistory_import;
drop table if exists purchasecost;
CREATE TABLE `smartportfolio`.`purchasecost` (
  `tradedate` DATETIME NOT NULL,
  `Market` VARCHAR(255) NULL,
  `LastPoolOfCost` DOUBLE NULL,
  `PoolOfCost` DOUBLE NULL,
  `LastQuantityHeld` DOUBLE NULL,
  `QuantityHeld` DOUBLE NULL,
  `OrderID` TEXT NULL,
  INDEX `tradedate_idx` (`tradedate` ASC) INVISIBLE,
  INDEX `market_idx` (`Market` ASC) VISIBLE);
drop procedure if exists calculate_purchase_cost;
DELIMITER $$
create procedure calculate_purchase_cost()
BEGIN
  declare done int default false;
  declare c_tradedate datetime;
  declare c_orderid varchar(255);
  declare c_market varchar(255);
  declare c_direction varchar(255);
  declare c_quantity double;
  declare c_price double;
  declare last_poolofcost double;
  declare last_quantity double;
  declare last_tradedate datetime;
  declare last_orderid varchar(255);
  declare cur1 cursor for select tradedate, orderid, market, direction, quantity, price from tradehistory order by tradedate asc;
  delete from purchasecost;
  open cur1;
  read_loop: LOOP
    fetch cur1 into c_tradedate,c_orderid,c_market,c_direction,c_quantity,c_price;
    if done THEN
      leave read_loop;
    end if;
    select null,null,null,null into last_poolofcost, last_quantity, last_tradedate, last_orderid;
    select a.orderid, a.tradedate into last_orderid, last_tradedate from purchasecost a where a.market = c_market and a.tradedate < c_tradedate order by tradedate desc limit 1;
    select a.poolofcost,a.quantityheld into last_poolofcost, last_quantity from purchasecost a where a.market = c_market and a.orderid = last_orderid;
    if c_direction = 'SELL' then
      insert into purchasecost select c_tradedate,c_market,last_poolofcost,last_poolofcost + c_quantity / last_quantity * last_poolofcost,ifnull(last_quantity,0),ifnull(last_quantity,0) + c_quantity,c_orderid;
    end if;
    if c_direction = 'BUY' THEN
      insert into purchasecost select c_tradedate,c_market, ifnull(last_poolofcost,0), (c_price * c_quantity / 100 + ifnull(last_poolofcost,0)) ,ifnull(last_quantity,0), ifnull(last_quantity,0) + c_quantity,c_orderid;
    end if;
  end loop;
  close cur1;
end$$
DELIMITER ;

call calculate_purchase_cost;

SELECT a.tradedate,a.settlement_date,a.direction, a.orderid, a.market,a.quantity,a.price, b.lastquantityheld,b.quantityheld,b.lastpoolofcost,b.poolofcost, 
case when a.direction = 'SELL' then -1*a.quantity*a.price/100 else 0 end as price,
case when a.direction = 'SELL' then -1*a.quantity/b.lastquantityheld*lastpoolofcost else 0 end as allowable_cost, 
case when a.direction = 'SELL' then ifnull(-1*a.quantity*a.price/100 + a.quantity/b.lastquantityheld*lastpoolofcost,0) else 0 end as gain FROM tradehistory a, purchasecost b where a.orderid = b.orderid order by a.tradedate asc;

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • image.png

  • Posts

    • I've recently received a total allocation of 88,310 $TOMA tokens for the TGE. Tap-to-earn games have been popular on Telegram, offering a fun way to earn rewards. I've played games like Major and Dogs, but Tomarket has been exciting.   This innovative platform takes the tap-to-earn concept to the next level, offering a unique ecosystem where users can earn tokens through gaming activities and community participation. What drew me to Tomarket was its engaging features, such as the Tomato Drop game, contributing to its rapid growth of over 40 million users since its launch.   As Tomarket prepares for its pre-market listing on Bitget, users can buy TOMA tokens early at the best prices before the spot listing. I'm excited to see where this project goes, and I think it's definitely worth checking out, especially if you're a fan of tap-to-earn games like myself!
    • Unicorn Ultra Network (U2U Network) has revolutionized cryptocurrency with a breakthrough solution to blockchain scalability issues. Their innovative approach offers infinite scalability, enhancing the efficiency of blockchain applications. U2U’s technology positions it as a leader in the crypto space, driving the future of decentralized finance (DeFi) and seamless real-world blockchain integration. Solving Blockchain's Scalability Challenge: U2U Network Leads the Way Blockchain technology has long struggled with scalability, hindering its ability to handle high transaction volumes efficiently. Networks like Bitcoin and Ethereum process only 7 and 15-25 transactions per second (TPS), while traditional payment systems like Visa can handle thousands of TPS. This scalability bottleneck leads to slow transaction speeds and high fees, limiting blockchain's real-world adoption. U2U Network offers an innovative solution, addressing this issue with infinite scalability to improve blockchain performance and make decentralized applications more practical for global use, enhancing the future of crypto and blockchain technology. U2U Network introduces an exponential scalability solution with its U2U Chain and U2U Subnet. U2U Chain, a DAG-based, EVM-compatible chain, offers low latency, faster transaction finality, and enhanced security through aBFT consensus and DPoS. Built on U2U Chain, U2U Subnet leverages Universal Messages Verification (UMV) and OstracismVM for seamless connectivity and interoperability. This combination allows U2U Network to achieve up to 72,000 TPS at launch, with a peak of 500,000 TPS and just 650 ms transaction finality, making it a groundbreaking solution for blockchain scalability and real-world applications. How to claim U2U Network (U2U) Token on Coinpedia Launchpad? Follow these steps below to claim a U2U Network token through CP Launchpad: Register on Coinpedia Launchpad: Sign up or log in to your Coinpedia account. If you don’t have one, create an account on the Coinpedia Launchpad platform. Complete KYC (Know Your Customer): Most platforms, including Coinpedia, require you to complete KYC verification to participate in ICOs. Submit the required documents and wait for verification approval. Deposit Funds: Deposit the required funds into your Coinpedia account. Typically, this could be in the form of cryptocurrency (e.g., BTC, ETH) or stablecoins, depending on the token sale's guidelines. Check for U2U Token Sale Details: Once your account is ready, navigate to the U2U Network token sale page on the Coinpedia Launchpad. Review the sale details such as the token price, allocation, and start/end time of the ICO. Participate in the Token Sale: During the sale period, use the available funds in your Coinpedia account to purchase U2U tokens. Follow the on-screen instructions to participate. Claim Your Tokens: After the token sale ends and if you have successfully participated, you can claim your U2U tokens. This may involve following a claim procedure via the Coinpedia Launchpad platform or receiving them directly into your connected wallet. Store Your Tokens: Once you’ve claimed your U2U tokens, ensure you transfer them to a secure wallet for safekeeping if they’re not automatically stored on the platform. For more accurate details about U2U Network's upcoming and ongoing crypto ICOs, you can visit their Coinpedia Launchpad and search for U2U Network listings on various cryptocurrency platforms and social media channels for updates and participation instructions.    
    • The ADA price has slipped into the red zone, currently trading below the crucial $1.20 level despite a weekly gain of over 15%. While the Cardano coin shows no immediate signs of bullish momentum, analysts remain optimistic about its potential upside. Short-Term ADA Price Prediction On smaller time frames, the ADA coin faces a pullback scenario. Key support levels lie between $1.11 and $1.21, with further downside risks if the price of Cardano drops below $1.05. However, if ADA coin regains traction, it could target $1.42, $1.72, and even $2.36 during a euphoric rally. Bitcoin’s Role in Cardano’s Future With Bitcoin’s dominance rising, Cardano crypto has been moving sideways. If Bitcoin consolidates above $100K, altcoins like ADA may rally. Such a scenario could see the Cardano price soaring to $2, a 33% rise from the current levels. Whale Activity and Long-Term Cardano Prediction Crypto whales recently accumulated over 100 million ADA, pushing the Cardano ADA price higher. Market experts foresee ADA forming a textbook ascending triangle pattern, potentially driving the Cardano crypto price to $1.50. Long-term Cardano predictions remain bullish, with some analysts eyeing a parabolic rise to $10 by 2025. Also Read: Optimism Price Prediction 2024, 2025, 2030 Cardano Price Outlook The Cardano price prediction 2024 suggests significant upside potential if ADA maintains its current structure. Traders should watch for breakouts above $1.25 and $1.33 to confirm bullish momentum.
×
×
  • Create New...
us