<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yashaswa Varshney on Medium]]></title>
        <description><![CDATA[Stories by Yashaswa Varshney on Medium]]></description>
        <link>https://medium.com/@yashaswa?source=rss-121ee62fb5ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nhvcq_4L_BzZM1KWKoFQ9w.jpeg</url>
            <title>Stories by Yashaswa Varshney on Medium</title>
            <link>https://medium.com/@yashaswa?source=rss-121ee62fb5ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:12:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yashaswa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Engineer’s Guide to Solana: Part 2 The Raw Fundamentals, State Management (Native Rust)]]></title>
            <link>https://medium.com/@yashaswa/engineers-guide-to-solana-part-2-the-raw-fundamentals-state-management-native-rust-c125635ad1fd?source=rss-121ee62fb5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/c125635ad1fd</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[solanas]]></category>
            <dc:creator><![CDATA[Yashaswa Varshney]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 23:54:06 GMT</pubDate>
            <atom:updated>2025-08-08T23:54:06.498Z</atom:updated>
            <content:encoded><![CDATA[<p>In part one of the series, we covered the fundamentals of solana. In this part we will understand how do we code a smart contract in native rust, sure there is an easier approach “Anchor” to code smart contracts, but this framework hides a lot of boiler plate code which i think is very important as to understand the approach of solana towards it’s developement. Also knowing this makes anchor actually helpful.</p><h3>Environment setup</h3><ol><li><strong>Install Rust</strong> (Use this <a href="https://www.rust-lang.org/tools/install">link</a> to download the right version for your operating system. You may also have to download Xcode. On macOS, you can get this C compiler by typing: <strong>$ xcode-select — install</strong> into the terminal. If you’re using a pc, you may have to download <a href="https://visualstudio.microsoft.com/visual-cpp-build-tools/">C++ build tools</a>.</li><li><strong>Download </strong><a href="https://code.visualstudio.com/download"><strong>Visual Studio</strong></a></li><li><strong>Download The Right Extensions</strong> There are a few Rust extensions for VS Code. Surprisingly, you shouldn’t download the Rust extension. You should instead download the Rust-analyzer. You can do so by searching for it in the extensions tab. Next, install Code Runner by searching in the extensions tab. It can also be helpful to download Better TOML (this helps you read TOML files). A helpful extension for debugging purposes is Code LLDB or the C/C++ (Windows) extension. To make sure all your crates are up to date, you can download the Crates extension. This displays the latest version of the crate next to it in the TOML file, as well as a few other nice features.</li><li>Download Solana, and Anchor tools: <a href="https://solana.com/pl/docs/intro/installation">https://solana.com/pl/docs/intro/installation</a></li></ol><p>once we have all the arsenal, let’s move to the war.</p><h3>What is a Smart Contract on Solana?</h3><ul><li>a smart contract is a program. More specifically, it’s a piece of self-executing code that lives permanently on the Solana blockchain.</li><li>Its purpose is to define the logic for how data is stored and modified.</li><li>Think of smart contracts not as databases that hold data, but as powerful gatekeepers. They stand in front of the data and enforce a strict, unchangeable set of rules on how that data can be accessed and altered. They are the guardians of logic on the blockchain.</li></ul><p><strong>Solana CLI</strong></p><p>to build, test and interact with the solana network, devs rely on the solana CLI.</p><p>It tipically have three environments:</p><ol><li>local test Vlaidators (aka. “$local-server$”): a loco dev send box, it runs a solana cluster entirly on the local machine, <br>This allows the user to airdrop nearly unlimited amout of test sols (these sols have no real-world-value)</li><li>devnet (“$dev-net$”): once we have a stable contract, it’s time for devnet. This is live, public blockchain run by actual validators that is designed to mimic the behaviour of the real network. the SOL on dev net is free (get them from “faucet”), but limited supply.<br>used for preproduction testig</li><li>main`net Beta ($main-net$)” : final frontier, the live, public solana blockchain where the transactions are real and have real-world-value.<br>After a contract is well tested on both the local-server and dev-net, we. deploy it to the main net, making it avilable to the public use.</li></ol><p>how to setup these and for more details (<a href="https://solana.com/pl/developers/cookbook/development/start-local-validator">https://solana.com/pl/developers/cookbook/development/start-local-validator</a>)</p><p>the counter contract we are about to build, the native way to understand the solana pholosophy</p><h3><strong>what are we building?</strong></h3><p>a counter simply start a counter with 0, this contract make a storage, content of which can an only be modified by this contract. this contract makes separate db for each account. which is how we can have parallelism from solana, since the db is separated the contract will have no issues running them concurrently.</p><pre>use borsh::{BorshDeserialize, BorshSerialize};<br>use solana_program::{<br>    account_info::{AccountInfo, next_account_info},<br>    entrypoint::ProgramResult,<br>    entrypoint,<br>    msg,<br>    pubkey::Pubkey,<br>};<br><br>#[derive(BorshDeserialize, BorshSerialize)]<br>enum InstructionType {<br>    Increment(u32),<br>    Decrement(u32),<br>}<br><br>#[derive(BorshDeserialize, BorshSerialize)]<br>struct Counter {<br>    count: u32, <br>}<br><br>entrypoint!(counter_program);<br><br>fn counter_program(<br>    _program_id: &amp;Pubkey,<br>    accounts: &amp;[AccountInfo],<br>    instruction_data: &amp;[u8], // array of bytes<br>) -&gt; ProgramResult {<br>    let acc = next_account_info(&amp;mut accounts.iter())?;<br>    let mut counter = Counter::try_from_slice(&amp;acc.data.borrow())?;<br><br>    match InstructionType::try_from_slice(instruction_data)? {<br>        InstructionType::Increment(count) =&gt; {<br>            msg!(&quot;Incrementing counter by {}&quot;, count);<br>            counter.count += count;<br>        }<br>        InstructionType::Decrement(count) =&gt; {<br>            msg!(&quot;Decrementing counter by {}&quot;, count);<br>            counter.count -= count;<br>        }<br>    }<br>    counter.serialize(&amp;mut &amp;mut acc.data.borrow_mut()[..])?;<br>    Ok(())    <br>}</pre><h3>Rust and solana’s standard libs</h3><pre>use borsh::{BorshDeserialize, BorshSerialize};<br>use solana_program::{<br>    account_info::{AccountInfo, next_account_info},<br>    entrypoint::{self, ProgramResult},<br>    msg,<br>    pubkey::Pubkey,<br>};</pre><ul><li><em>use borsh::{BorshDeserialize, BorshSerialize}; </em>Solana programs don’t natively understand rust data structures as like protoBuf used in gRPC goolge introduced binary based communication solana used Borsh, they only deal with [u8] Borsh is a serilization library which converts (or “serialized”) a rust data structure into a byte array and on chain side converts bytes back to rust structures (primarily structs and enums) called Deserialization.<br>we use this with #[derive(BorshDeserialize, BorshSerialize)] this trait automatically generate the required code to perform this task.</li><li><em>use solana_program::… </em>this line importes solana specefic tools.<br>&gt; <em>account_info::AccountInfo</em>: This is a key concept<br>- used by the main instruction function as it contains meta data of the accounts required to perform a given action. like publickey (pubkey) it’s owner, and the raw data it holds (data).<br>- <em>account_info:: next_account_info</em>: a helper funciton to itterate over account in accounts array of AccountInfo passed to our program<br>- <em>entrypoint</em>: a boiler plate code from solana, entrupoint! is a macro sets up the main function that the solana runtime will call. ProgramResult is a type alias for Result&lt;(), ProgramError&gt;, which is a standard Rust way of representing success (Ok(())) or failure (Err(ProgramError)).</li><li><em>msg!</em> : a macro to print messages majorly used for on chain logs and debugging.</li><li><em>pubkey::PubKey</em> : this represent a 32byte buplica key on solana every account and program has a publickey</li></ul><h4>Defining Data Structure</h4><p>we need to define the data structures our program will use, all of them in this case only two</p><pre>// the kind of instruction we need for a dev to call and access <br>// think of them like diffrent type of instruction function defined<br>// when we use solidity for eth development.<br>#[derive(BorshDeserilize, BorshSerilize)] // for solana to import and export in desired formats<br>enum InstructionTypes {<br>  Increment(u32),<br>  Decrement(u32),<br>}<br><br>#[derive(BorshDeserilize, BorshSerilize)] <br>struct Counter {<br>  count: u32,<br>}</pre><ul><li><em>#[derive(BorshDeserialize, BorshSerialize)]</em>: This is a Rust attribute. As mentioned before, it automatically generates the code to serialize and deserialize our data structures using Borsh. We need this for both our instructions and our data.</li><li><em>enum InstructionType</em>: In Solana, an “instruction” is a command sent to a program. Since programs only receive a byte array, we need a way to encode what we want to do. An enum is perfect for this.</li><li><em>Increment(u32)</em>: This instruction tells the program to increment the counter. The u32 inside the parentheses is a payload, it carries the value by which we want to increment.</li><li><em>Decrement(u32)</em>: This instruction tells the program to decrement the counter, again with a u32 payload.</li><li><em>struct Counter</em>: This struct defines the state of our program. It’s the data that will be stored in an account on the blockchain. In this simple case, the state is just a single u32 integer named count.</li></ul><h3>The Program’s Entry Point</h3><p>This is where the magic happens. The entrypoint! macro sets up the counter_program function to be the function that gets executed by the Solana runtime.</p><pre>entrypoint!(counter_program);</pre><pre>fn counter_program(<br>    _program_id: &amp;Pubkey,<br>    accounts: &amp;[AccountInfo],<br>    instruction_data: &amp;[u8], // array of bytes<br>) -&gt; ProgramResult {<br>    // ...<br>}</pre><ul><li>_program_id: &amp;Pubkey: This is the public key of the program itself. We don’t use it in this example, which is why it’s prefixed with an underscore (_) to tell the Rust compiler we’re intentionally not using it.</li><li>accounts: &amp;[AccountInfo]: This is a slice of AccountInfo structs. It’s a list of all the accounts that the program needs to read from or write to. In this simple case, we’ll only need one: the account that holds our Counter data.</li><li>instruction_data: &amp;[u8]: This is the raw byte array that contains the instruction we want to execute. This is where the serialized InstructionType from the client will be.</li></ul><h3>The Program Logic: Inside counter_program</h3><p>Let’s dissect the core logic inside the function.</p><pre>let acc = next_account_info(&amp;mut accounts.iter())?;</pre><ul><li>let acc = …: We get a reference to the first account in the list.</li><li>next_account_info(&amp;mut accounts.iter())?: this is the standard way to grab accounts one by one. the accounts.iter() creates an iterator over the slice of accounts. the &amp;mut gives us a mutable reference, allowing the iterator to be consumed. the ? at the end is a shorthand for error handling; if next_account_info fails (eg if there are no accounts), it will return the error and exit the function</li></ul><pre>let mut counter = Counter::try_from_slice(&amp;acc.data.borrow())?</pre><ul><li>acc.data.borrow(): This is crucial for understanding how accounts work. The data field of AccountInfo is a RefCell&lt;Vec&lt;u8&gt;&gt;. and RefCell is a Rust type that allows for multiple immutable borrows or one mutable borrow at runtime. we are getting an immutable reference (borrow()) to the raw data stored in the account.</li><li>Counter::try_from_slice(…): this is where borsh comes in. It takes the byte array (&amp;acc.data.borrow()) and attempts to deserialize it into our Counter struct. If successful, we get a Counter struct; if not, it returns an error. we use let mut counter because we intend to modify its value.</li></ul><pre>match InstructionType::try_from_slice(instruction_data)? {<br>    InstructionType::Increment(count) =&gt; {<br>        msg!(&quot;Incrementing counter by {}&quot;, count);<br>        counter.count += count;<br>    }<br>    InstructionType::Decrement(count) =&gt; {<br>        msg!(&quot;Decrementing counter by {}&quot;, count);<br>        counter.count -= count;<br>    }<br>}</pre><ul><li>InstructionType::try_from_slice(instruction_data)?: We deserialize the incoming instruction_data byte array into our InstructionType enum.</li><li>match …: This is a powerful Rust feature for pattern matching. We check which variant of the InstructionType enum we received.</li><li>InstructionType::Increment(count) =&gt; …: If the instruction was Increment, we extract the count value and then add it to our counter.count. The msg! macro logs a message to the blockchain.</li><li>InstructionType::Decrement(count) =&gt; …: Similarly, if it was Decrement, we subtract the count</li></ul><pre>counter.serialize(&amp;mut &amp;mut acc.data.borrow_mut()[..])?</pre><ul><li>acc.data.borrow_mut(): After we’ve modified our counter struct in memory, we need to write the changes back to the account. This line gets a mutable reference to the account’s data. This is why it’s so important that we only got an immutable borrow earlier to read the data; you can’t have both a mutable and an immutable borrow at the same time in Rust.</li><li>counter.serialize(&amp;mut &amp;mut acc.data.borrow_mut()[..])?: This is the reverse of deserialization. We use Borsh to serialize our updated counter struct back into a byte array. The &amp;mut &amp;mut …[..] part is a bit of a Rust-specific pattern to get a mutable slice that serialize expects. It takes the mutable borrow of the data and creates a mutable slice of it.</li></ul><pre>Ok(())</pre><ul><li>This line shows that the program executed successfully. If at any point an error occurred (like a failed deserialization), the ? operator would returned the error and this line would never be reached.</li></ul><h3>Testing for counter contract</h3><h4>The Testing Stack</h4><p><strong>Local Validator</strong><br>- Runs a full Solana node on your machine<br>- Provides the same environment as mainnet<br>- Allows unlimited airdrops for testing<br>- Generates detailed logs for debugging</p><p><strong>Web3.js Library</strong><br>- Connects your tests to the validator<br>- Handles transaction creation and signing<br>- Manages account interactions<br>- Provides utility functions for common operations</p><p><strong>Test Framework</strong><br>- We use Bun’s built-in test runner<br>- Supports async operations<br>- Provides assertion methods<br>- Runs tests in parallel</p><p>Program Architecture: Counter Example</p><h4>this test program shows core Solana concepts:</h4><pre>enum InstructionType {<br> Increment(u32),<br> Decrement(u32),<br>}<br>struct Counter {<br> count: u32, <br>}</pre><p><strong>Key points:</strong><br>- Programs contain logic only, no data storage<br>- Instructions define operations the program can perform<br>- Data lives in separate accounts owned by the program<br>- Borsh serialization handles data encoding/decoding</p><p><strong>Test Structure Breakdown</strong></p><h4>1. Setup Phase</h4><pre>const connection = new Connection(RPC_URL, { commitment: &quot;confirmed&quot; });<br>const payer = Keypair.generate();<br>await airdropAndConfirm(connection, payer.publicKey, 200);</pre><p><strong>What happens here:</strong><br>- Connect to local validator at `<a href="http://127.0.0.1:8899`">http://127.0.0.1:8899`</a><br>- Generate a new wallet for paying fees<br>- Request test SOL from the validator’s faucet<br>- Wait for confirmation before proceeding</p><h4><strong>2. Account Creation</strong></h4><pre>const counter = Keypair.generate();<br>const rentLamports = await connection.getMinimumBalanceForRentExemption(COUNTER_ACCOUNT_SPACE);<br>const createIx = SystemProgram.createAccount({<br> fromPubkey: payer.publicKey,<br> newAccountPubkey: counter.publicKey,<br> space: COUNTER_ACCOUNT_SPACE,<br> lamports: rentLamports,<br> programId: PROGRAM_ID,<br>});</pre><p>Critical steps:<br>- Generate account keypair for the counter data<br>- Calculate rent exemption to keep account alive<br>- Set program as owner so it can modify the account<br>- Allocate exact space needed (4 bytes for u32)</p><h4>3. Instruction Encoding</h4><pre>function encodeIncrement(amount: number): Buffer {<br> return Buffer.concat([Buffer.from([0]), Buffer.from(u32ToLeBytes(amount))]);<br>}</pre><p><strong>Encoding rules:</strong><br>- First byte is enum variant (0 for Increment, 1 for Decrement)<br>- Next 4 bytes are the number in little-endian format<br>- Must match Rust program expectations exactly<br>- Borsh handles serialization on both sides</p><h4>4. Transaction Building</h4><pre>const incIx = new TransactionInstruction({<br> programId: PROGRAM_ID,<br> keys: [<br> { pubkey: counter.publicKey, isSigner: false, isWritable: true },<br> ],<br> data: encodeIncrement(5),<br>});<br>const tx = new Transaction().add(incIx);<br>tx.recentBlockhash = latest.blockhash;<br>tx.feePayer = payer.publicKey;<br>tx.sign(payer);</pre><p><strong>Transaction components:</strong><br>- Program ID tells the validator which program to call<br>- Account keys specify which accounts the program can access<br>- Instruction data contains the encoded parameters<br>- Recent blockhash prevents replay attacks<br>- Fee payer covers transaction costs</p><p>5. Verification</p><pre>const value = await getCounterValue(connection, counter.publicKey);<br>expect(value).toBe(5);</pre><p><strong>Verification process:</strong><br>- Read account data from the blockchain<br>- Deserialize the bytes back to a number<br>- Assert expected value using test framework<br>- Confirm state changes happened correctly</p><h3>Common Testing Patterns</h3><p><strong>Account Data Validation</strong><br>- Always check account exists before reading data<br>- Verify account owner matches expected program<br>- Confirm data size matches struct definition<br>- Handle deserialization errors gracefully</p><p><strong>Transaction Error Handling</strong><br>- Test both success and failure cases<br>- Verify proper error messages<br>- Check account state remains unchanged on failure<br>- Test edge cases like insufficient funds</p><p><strong>Multiple Instruction Testing</strong><br>- Test instruction sequences in single transactions<br>- Verify state changes persist between instructions<br>- Test instruction ordering dependencies<br>- Check gas consumption limits</p><h4><strong>Best Practices</strong></h4><p><strong>Test Organization</strong><br>- One test per user story, keep tests focused<br>- Setup helpers reduce code duplication<br>- Clear test names describe what you’re testing<br>- Async/await properly, don’t skip confirmations</p><p><strong>Account Management</strong><br>- Generate fresh keypairs for each test<br>- Clean up accounts if running many tests<br>- Use deterministic seeds when account addresses matter<br>- Test with realistic data sizes</p><p><strong>Error Scenarios</strong><br>- Test insufficient funds situations<br>- Verify access control works correctly<br>- Check invalid instruction data handling<br>- Test concurrent access patterns</p><p><strong>Performance Considerations</strong><br>- Batch related operations in single transactions<br>- Use appropriate commitment levels for your needs<br>- Monitor compute unit consumption<br>- Test with realistic network conditions</p><p><strong>View real-time logs</strong><br>solana logs — url <a href="http://127.0.0.1:8899/">http://127.0.0.1:8899</a></p><p><strong>Search for your program</strong><br>grep “Program YOUR_PROGRAM_ID” test-ledger/validator.log</p><p><strong>Find your program messages</strong><br>grep “Program log:” test-ledger/validator.log</p><p><strong>Advanced Testing Scenarios</strong></p><p><strong>Cross-Program Invocations</strong><br>- Test programs calling other programs<br>- Verify correct Program Derived Addresses (PDAs)<br>- Check authority delegation works<br>- Test complex instruction compositions</p><p><strong>Token Program Integration</strong><br>- Test SPL token interactions<br>- Verify mint and burn operations<br>- Check token account ownership<br>- Test transfer restrictions</p><p><strong>Upgrade Testing</strong><br>- Test program upgrade scenarios<br>- Verify data migration works<br>- Check backward compatibility<br>- Test upgrade authority controls</p><p>up next “Part 3 Mastering Anchor (The Framework)”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c125635ad1fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Engineer’s Guide to Solana: Part 1 The Theory]]></title>
            <link>https://medium.com/@yashaswa/engineers-guide-to-solana-part-1-the-theory-71a83d842ea7?source=rss-121ee62fb5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/71a83d842ea7</guid>
            <dc:creator><![CDATA[Yashaswa Varshney]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 05:43:33 GMT</pubDate>
            <atom:updated>2025-08-06T05:43:33.080Z</atom:updated>
            <content:encoded><![CDATA[<p>An epitome of High performance, mass adoption and future friendly crypto: Solanaaaaaa!.</p><p>A global state machine which eliminate the need for each node to waste compute to execute the same instructions repeatedly thus making it environment friendly</p><p>Solana’s ability to accommodate concurrent transaction processing makes it cost effective and safer at the same time. <br>un-Parallel speed with minimal cost of usage</p><h3>Solana developer workflows</h3><ul><li>solana acts as a global computer, open to anyone for storing and executing code for a fee.</li><li>programs are called smart-contracts</li><li>to interact with such programs we rpc apis</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*Ot1pgQfYVOUAnfeuCdQvMA.png" /></figure><p><strong>There are two types of workflows in solana development</strong></p><ul><li>Program Development: Public visible and accessible programs/data, that can be deployed on this global computer.</li><li>Client Development: to connect with programs and data sources. these apps can send transactions (with contains instructions) to be executed to perform a specefic task.</li></ul><p><strong>at the core of solana’s development model, it revolves around three key components.</strong></p><ol><li>Accounts (1.1 Data Accounts, 1.2 Programs Accounts)</li><li>Programs</li><li>Transactions &amp; Instructions (3.1 Invoke Programs, 3.2 Modify accounts)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_pyL8aKeK6hbGRFMBqrrlQ.png" /></figure><h3>1.0 Accounts</h3><p>Every thing on solana is an account, like an SSD which contains all your applications (programs) and data (data which programs interact with)</p><h4>1.1 Data Accounts</h4><ul><li>non executable</li><li>store informations or state of the network (means we can read or write info)</li><li>example user wallet balance is stored in these.</li></ul><h4>1.2 Programs accounts</h4><ul><li>executable accounts</li><li>contains compiled code for a program</li><li>stateless (means they don’t store data instead they r/d data from data accounts)</li></ul><h3>2.0 Programs</h3><ul><li>smart contracts</li><li>deployed to executable accounts contains logic for the DApp</li><li>these are invoked by transactions (which contains instructions)</li><li>can perform actions such as updating the data in data accounts (if they have the authority)</li><li><em>the separation of data and programs allows parallelism!</em></li></ul><blockquote>Executable Account vs Program Account</blockquote><blockquote>“All program accounts are, by definition, executable accounts, but not all executable accounts are “program accounts” in the common sense.”<br><strong>Executable Account:</strong> <br>- fundamental property of an account. <br>- every account on sol has a boolean flag called executable. <br>- when this flag is set to true, means that the account’s data contains compiled program code that can be run by the sol runtime. <br>- If the flag is false, the account is a data account, and its data cannot be executed.<br><strong>Program Account</strong>: <br>- as a developer, you deploy to the Solana blockchain. the “smart contract”. <br>- when you deploy a program, it’s stored in an account, and that account has its executable flag = true. <br>- allows the program to be invoked by transactions.<br>- contains the compiled code<br>- stateless, doesn’t hold the application’s data</blockquote><h3>3.0 Transactions and Instructions</h3><ul><li>a user interacts with a Solana program by sending a transaction.</li><li>transaction is a bundle that contains one or more instructions, list of all the accounts the transaction will interact with, and the user’s signature to authorize the actions.</li><li>instruction says which program to call, which accounts it will read or modify, and any specific data the program needs to execute its logic</li></ul><h3>Accounts</h3><p>we’ll deep dive into accounts the most critical and confusing</p><p>what do we know so far: (account types)</p><p><strong>Executable Accounts -&gt; Program Accounts</strong></p><ul><li>contain compiled BPF bytecode (e.g., smart contract logic).</li><li>executable flag is true.</li></ul><p><strong>Non-Executable Accounts -&gt; Data Accounts</strong></p><ul><li>Hold state or user/application data.</li><li>Used to persist changes across transactions.</li><li>executable flag is false.</li></ul><p>now let’s see what accounts contain.</p><h4>What every solana account has</h4><ul><li><strong>Lomparts: </strong>solana’s native token balance <br>(pay rent)</li><li><strong>data: </strong>A byte array holding account’s state</li><li><strong>owner: </strong>The program ID allowed to modify this account’s data</li><li><strong>Executable: </strong>boolean (if it contains program or not)</li></ul><p><em>“</em><strong><em>an account’s owner is a program not a user</em></strong><em>” </em>this method makes sure only defined actions can be performed on the data, which makes it reliable.<br><strong>example</strong>: <a href="https://medium.com/@marketing.blockchain/a-guide-to-counter-dapp-development-on-solana-blockchain-98895413aea0">in this smart contract</a> a counter program owns a data account, only that program increment and decrement the count by 1. no user can just change the counter to any x number.</p><h3>Rents</h3><ul><li>solana charges rent to store data on chain</li><li><strong>Rent exemped: </strong>means account hold enough lamports so they’re never thrown out</li><li>so either you pay rent continuously or you make the account rent exempt upfront by funding it with enough lamports.</li><li>If an account is not rent exempt and becomes inactive, it may be garbage collected means its lamports are reclaimed and the account is deleted from the chain.</li></ul><p><em>in this section we’ll understand the transactions</em></p><ul><li>A Transaction is a bundle of one or more instructions + recent blockhash (prevents replay) + signatures from all required signers</li><li>when all parts are valid and all req accounts signs, the transactions is valid and processed in chain.</li></ul><h4><strong>Instructions</strong></h4><p>think of them as function/API calls to a program</p><p><strong>instructions contain</strong></p><ul><li>Program ID: the smart contract to execute</li><li>Accounts list: the account needed to read and write.</li><li>params or payload: method name + arguments</li></ul><p>that’s it.</p><p><strong>example: </strong>calling a function to increment a counter will include</p><ul><li>program id: counterProgram</li><li>accounts: [user_account, counter_data_account]</li><li>params: method = “increment” .</li></ul><blockquote>Transactions are Atomic: means if any transaction fails the entire transaction is reverted ** <br>(no partial update, all or nothing, this keeps sol state consistent)</blockquote><h3>“On-chain Program Development”</h3><p>we will get into real development in the part 2 of this Blog, for now let’s understand the theory.</p><h4><strong>Programming language</strong></h4><ul><li>Rust is the goto lang (only!) for sol SmartContract (programs) because Type safe, memory safe, can compile to <strong>BPF bytecode, </strong>Which sol executes</li><li>c, c++ are supported but discouraged by sol community. (if this was not the case sol would have 100x more applications by now but it is what it is!!)</li></ul><h4>SPL Solana Program Library</h4><ul><li>standard toolbox of on chain programs (smart contracts) that dev uses</li><li>solana version of eth’s common contracts i.e. ERC-20, ERC-721 etc.</li><li>these are Audited, Battle tested and most importantly standardised</li></ul><h4><strong>1. SPL token program</strong></h4><ul><li>mint tokens ($USDC, $TRUMP, or NFTs)</li><li>send or recieve tokens</li><li>burn or freeze tokens</li><li>set auth (like who can mint or freeze)</li><li>check balances</li></ul><p><strong>spl tokens balances are not stored inside wallet directly! they are stored in Associated token Accounts (ATA)</strong></p><h4>what is an ATA?</h4><ul><li>a unique token account for a specific (wallet, token mint) pair</li><li>think of like “Richard’s USDC account” if Richard have 5 tokens ($USDC, $BONK, $TRUMP…) they will have 5 different token amounts, each token account is owned by Richard’s wallet but created by same SPL token program.</li><li>ATA are drived using</li></ul><pre>ATA Address = PDA (richard&#39;s wallet address, token mint address, SPL Token Program ID)</pre><p><strong>why do we need ATA’s ?</strong></p><ul><li>Standardised token account structure</li><li>prevent duplicate balances and errors</li><li>Makes wallet integration easier (every wallet knows where to look)</li><li>reduces dev complexities as the token creator don’t have to track token accounts manually</li></ul><h4>SPL Token Mint Authorities</h4><ul><li>we already know that each spl token (<em>also called mint</em>)<em> </em>has authority accounts. has auths like minting or freezing</li><li>these auth rules are baked into token at the time of creation and can be changed or revoked at the time of creation.</li></ul><h4>what is a “Mint”</h4><p>a mint account is an on chain account that defines:</p><ul><li>the token type (eg. USDC, GARI, MYTOKEN)</li><li>decimals (how divisible it is)</li><li>Total supply (if capped)</li><li>Auths (who can mint/freez)</li></ul><p><strong>these are like token factories</strong></p><ul><li>you can crreate it using createMint instruction</li><li>it can mint new tokens into token accounts</li><li>but only the mint auth can do that</li></ul><h4>Types of Authorities</h4><p>there are three types of mint auths for conserning spl tokens.</p><ol><li><strong>mint auth:</strong> who can mint new tokens (increase supply like out shi**y govs), used during ICOs or token distributions</li><li><strong>Freeze Auth: </strong>who can freeze token accounts (block transfers), used by regulated tokens like USDC</li><li><strong>close Auths: </strong>who can close token accounts, rarely used (can be used for cleanups)</li></ol><p>create a new SPL token with a command like</p><pre>spl-token create-token</pre><p>You can pass:</p><ul><li>--mint-authority</li><li>--freeze-authority</li></ul><p>If you don’t, the CLI will use your current wallet as the default.</p><p>Then you can mint tokens using:</p><pre>spl-token mint &lt;TOKEN_MINT_ADDRESS&gt; &lt;AMOUNT&gt; &lt;RECIPIENT_TOKEN_ACCOUNT&gt;</pre><p>But only the mint authority can do this.</p><p><strong>Revoking Authorities (Make Your Token Immutable)</strong></p><p>If you want your token supply to be capped, you can revoke the mint authority like this:</p><pre>spl-token authorize &lt;TOKEN_MINT_ADDRESS&gt; mint --</pre><p>Now, no one can mint new tokens — the supply is locked forever.</p><p><strong>examples:</strong></p><ul><li><strong>Meme Tokens: </strong>mint auth only during initial mint then revoked, freeze auth never used</li><li><strong>USDC: </strong>mint auth retained by circle to mint more, freeze auth is used for compliance</li><li><strong>NFT: </strong>mint auth is used once per NFT, freeze auth is not usually used.</li></ul><h3><strong>PDA Program Derived Address</strong></h3><p>A special type of account only controlled by a program not by any user.</p><p>they are the foundation for</p><ul><li>creating deterministic addresses</li><li>preventing manual signing</li><li>Making your program stateful hence secure **</li></ul><p>features</p><ul><li>ownership by program</li><li>can’t be signed by private key; instead the program signs</li><li>derived from seeds+programID</li></ul><p><strong>general use cases: </strong>Vaults, metadata, token auths, config accounts (automations like for $USDC’s case to ctrl supply and demand and stable the price to $)</p><p>how do you derive a PDA ?</p><p><em>don’t bother about understand the code yet, we will cover them in upcoming parts</em></p><pre>const [pda, bump] = PublicKey.findProgramAddressSync(<br>  [Buffer.from(&quot;seed1&quot;), walletPubkey.toBuffer()], <br>  programId<br>);</pre><ul><li>Seeds: can be any combinations of bytes (generally includes strings, pubkeys, u64s)</li><li>Program ID: your on chain program’s address</li><li>Bump: a number bw 0 to 255 is added to make sure the address is off ed25519 curve</li></ul><p><strong>why off curve ?!</strong></p><p>well solana uses ed25519 curve cryptography, if the derived address is on the curve, someone can generate a private key for it, hence could use that key to modify the content of PDA!</p><p>PDAs are specifically designed to always be off the curve so:</p><ul><li>They can’t be owned by any wallet</li><li>Only the program can sign on their behalf via invoke_signed.</li></ul><p><strong>what do i mean by program signing a PDA ?</strong></p><p>when ur program want to uses the PDA as an authority (to have power to transfer tokens, write data …), it uses this:</p><pre>invoke_signed(<br>  &amp;instruction,<br>  &amp;[...accounts],<br>  &amp;[&amp;[seeds..., &amp;[bump]]],  // PDA seeds and bump<br>)</pre><p>programs shows solana proof that i’m the owner by showing seeds and bump, then if every thing matched using hashmap, sol let the program to sign PDA.</p><p>the best example: how PDAs are used as mint authority in Token programs?</p><p>when you create a new token using SPL token program to create your own stable or meme coin, someone has to have a mint/ freeze authority, which allows to mint/freeze tokens.</p><p>now “should a human controlled wallet hold that power?”</p><p>no! ($LIBRA scandal)</p><p>PDA owned authority makes minting controlled, safe, programmatic more importantly visible to investors.</p><p>Up next:</p><ul><li>Part 2 The Raw Fundamentals, State Management (Native Rust)</li><li>Part 3 Mastering Anchor (The Framework)</li><li>Part 4 Anchor smart contract general patterns ䷡</li></ul><blockquote><em>remember</em> “not your keys, not your coins”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71a83d842ea7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backtesting the viral Nadaraya-Watson Envelop trading indicator in python]]></title>
            <link>https://medium.com/@yashaswa/backtesting-the-viral-nadaraya-watson-envelop-trading-indicator-in-python-b800a70e8167?source=rss-121ee62fb5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/b800a70e8167</guid>
            <category><![CDATA[trading-bot]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[backtesting]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Yashaswa Varshney]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 16:45:07 GMT</pubDate>
            <atom:updated>2023-02-05T17:57:42.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dcYF0_uSW-RUwrZD.png" /></figure><blockquote>Too good to be true is often a warning sign, and this is certainly the case with the Nadaraya-Watson indicator, let me explain…</blockquote><h4>What is Nadaraya-Watson envelope?</h4><p>The Nadaraya-Watson envelope is a type of moving average calculated by taking a weighted average of data points over a period of time. The envelope is created by drawing two lines (one above and one below) parallel to the moving average at a user-defined percentage distance. Top and bottom lines form a “band” around the moving average that can be used to identify potential trend changes and generate trading signals. The Nadaraya-Watson cover is named after its creators, Vasily Nadaraya and his Geoffrey Watson.</p><p>Official: <a href="https://www.tradingview.com/script/Iko0E2kL-Nadaraya-Watson-Envelope-LuxAlgo/">https://www.tradingview.com/script/Iko0E2kL-Nadaraya-Watson-Envelope-LuxAlgo/</a></p><h3><strong>Logic</strong></h3><p>The main computation is done in a ‘for’ loop that iterates over ’n’. At each iteration “i”, a weighted average of the data points is calculated using another inner “for” loop that iterates “j”. The weight “w” is exponentially calculated and depends on the difference between the indices “i” and “j” and the smoothing parameter “h”. The weighted sum of data points is stored in ‘sum’ and the weighted sum of weights is stored in ‘sumw’. The weighted average of the data points for each iteration “i” is computed as the ratio of “sum” and “sumw”. The value “y2[i]” is set to this weighted average at each iteration. The value “y1[i]” is computed as the average of “y2[i]” and “y2[i-1]” for all iterations except the first. This is because the first value of “y1” is undefined. Finally, the arrays ‘y2’ and ‘y1’ are added as new columns to the dataframe ‘df’ contained in the object ‘self’. This function returns arrays “y2” and “y1”.</p><p>The function generates buy and sell signals based on the difference between two elements of the Nadaraya-Watson Envelope (y2). If the difference is greater than a threshold and the previous y2 value is below the previous y1 value, it is a buy signal. If the difference is less than the negative of the threshold and the previous y2 value is above the previous y1 value, it is a sell signal. The index of the buy and sell signals are added to separate lists.</p><h3>Let’s backtest this in python</h3><pre>import numpy as np<br>from sklearn.kernel_ridge import KernelRidge<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import yfinance as yf</pre><pre>class Backtest:<br>    def __init__(self, symbol, tim):<br>        self.tim = tim<br>        self.symbol = symbol<br>        self.df = yf.download(tickers=symbol, period = self.tim)<br>        self.src = self.df[&quot;Close&quot;].values<br>        self.h = 7<br>        y2, y1 = self.nadaraya_watson_envelope()<br>        self.gen_signals(y1,y2)<br><br><br>    def nadaraya_watson_envelope(self):<br>        n = len(self.src)<br>        y2 = np.empty(n)<br>        y1 = np.empty(n)<br>        h= self.h<br>        for i in range(n):<br>            sum = 0<br>            sumw = 0<br>            for j in range(n):<br>                w = np.exp(-(np.power(i-j,2)/(h*h*2)))<br>                sum += self.src[j]*w<br>                sumw += w<br>            y2[i] = sum/sumw<br>            if i &gt; 0:<br>                y1[i] = (y2[i] + y2[i-1]) / 2<br>        self.df[&#39;y2&#39;] = y2<br>        self.df[&#39;y1&#39;] = y1<br>        return y2, y1<br>    <br>    def gen_signals(self,y1,y2):<br>        buy_signals = []<br>        sell_signals = []<br>        thld = 0.01<br><br>        for i in range(1, len(y2)):<br>            d = y2[i] - y2[i-1]<br>            if d &gt; thld and y2[i-1] &lt; y1[i-1]:<br>                buy_signals.append(i)<br>            elif d &lt; -thld and y2[i-1] &gt; y1[i-1]:<br>                sell_signals.append(i)<br>        money = 100<br>        profit = []<br>        for i in range(len(buy_signals)):<br>            buy_index = buy_signals[i]<br>            if i &lt; len(sell_signals):<br>                sell_index = sell_signals[i]<br>                money *= self.src[sell_index] / self.src[buy_index]<br>                profit.append(money - 100)<br>        self.profit  = pd.DataFrame(profit)<br>        rets = &quot;returns &quot;+ self.tim +&quot; = &quot; + str(round(((money/100-1)*100),2)) + &quot;%&quot;<br>        print(rets)<br>        plt.figure(figsize=(20,5))<br>        plt.plot(y2, label=&#39;y2&#39;)<br>        plt.plot(self.src,color=&#39;black&#39;, label=&#39;close&#39;)<br>        for signal in buy_signals:<br>            plt.axvline(x=signal, color=&#39;green&#39;,linewidth=2)<br><br>        for signal in sell_signals:<br>            plt.axvline(x=signal, color=&#39;red&#39;,linewidth=2)<br><br>        plt.text(0.80, 0.25, self.symbol, transform=plt.gca().transAxes, fontsize=34,verticalalignment=&#39;top&#39;)<br>        plt.text(0.80, 0.15, rets, transform=plt.gca().transAxes, fontsize=14,verticalalignment=&#39;top&#39;)<br>        plt.legend()<br>        plt.show()</pre><pre>instance = Backtest(&quot;INFY.NS&quot;, tim=&#39;1y&#39;)</pre><p><em>Test on your desired company: </em><a href="https://finance.yahoo.com/"><em>https://finance.yahoo.com/</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7o28r7B_A9tQ15CMxWi-Q.png" /></figure><p><a href="https://github.com/bbmusa/nadaraya_watson_envelope">https://github.com/bbmusa/nadaraya_watson_envelope</a></p><h3><strong>But wait!!</strong></h3><p>It is considered trash due to its tendency to “repaint,” which is a tactic used by scamsters to sell indicators on platforms like TradingView. In this context, repainting means dynamically changing signals as new data is added, making the indicator appear more successful than it actually is.</p><p>This code does not inherently cause a repaint, but if the self.src data used to compute the Nadaraya-Watson envelopes (y1 and y2) changes dynamically, it will cause a redraw, generated by the gen_signals function. changes the signal received. This can change previous signals and make the indicator appear more successful than it really is. This is the definition of repaint.</p><blockquote>A new free viral indicator from TradingView that looks like a goldmine but is nothing more than a repaint and backtest fooling tool!</blockquote><p>Thanks for reading<br>For error correction or any query or small talks too,<br>Msg me on: <a href="https://www.linkedin.com/in/yashaswa-varshney/">https://www.linkedin.com/in/yashaswa-varshney/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b800a70e8167" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Mean Reversion Trading strategy on Nifty50 stocks]]></title>
            <link>https://medium.com/@yashaswa/testing-mean-reversion-trading-strategy-on-nifty50-stocks-3e2dc2e23483?source=rss-121ee62fb5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e2dc2e23483</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading-system]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[Yashaswa Varshney]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 13:05:10 GMT</pubDate>
            <atom:updated>2023-01-04T13:05:10.313Z</atom:updated>
            <content:encoded><![CDATA[<p>Mean reversion is a trading strategy based on the idea that asset prices tend to revert to their mean or median value over time. This strategy involves identifying assets whose prices deviate significantly from the average and betting that they will eventually return to the average.</p><p>To implement a mean-reverting strategy, traders typically use statistical techniques to identify assets that are trading significantly above or below their historical average. Then, place a trade to make a profit if the asset’s price returns to its average value.</p><p>There are several ways to measure the deviation of an asset from its mean, such as using statistical indicators such as standard deviation and Bollinger Bands. Traders can also use moving averages to identify assets that are trading significantly above or below recent price trends.</p><p>It is important to note that mean reversion is not a guaranteed way to make money and there is no guarantee that an asset’s price will return to its average. Traders should carefully consider risk and employ appropriate risk management techniques when implementing a <strong>return-to-average</strong> strategy.</p><pre>#Import required Libraries<br>import yfinance as yf<br>import pandas as pd<br>import numpy as np<br>import ta<br>import matplotlib.pyplot as plt<br>import time<br>from pandas_datareader import data as pdr</pre><p>Download data from Yahoo Finance</p><pre>df = yf.download(&#39;AXISBANK.NS&#39;,start=&#39;2018-01-01&#39;)</pre><p>Calculating all the Required Statistical para meter using <a href="https://pypi.org/project/ta/"><strong>ta library</strong></a></p><pre>df[&#39;ma_20&#39;] = df.Close.rolling(20).mean()<br>df[&#39;vol&#39;] = df.Close.rolling(20).std()<br>df[&#39;upper_bb&#39;] = df.ma_20 + (2*df.vol)<br>df[&#39;lower_bb&#39;] = df.ma_20 - (2*df.vol)<br>df[&#39;rsi&#39;] = ta.momentum.rsi(df.Close)</pre><p>Defining Buy and Sell conditions</p><pre>conditions = [(df.rsi&lt;30) &amp; (df.Close&lt;df.lower_bb),<br>              (df.rsi&gt;70) &amp; (df.Close &gt; df.upper_bb)]<br>choises = [&#39;Buy&#39;, &#39;Sell&#39;]<br>df[&#39;Signal&#39;] = np.select(conditions,choises)<br>df = df.dropna()</pre><p>Shifting all the signals on the next day because of we got a buy/sell signal we can perform that action the next day only</p><pre>df.Signal = df.Signal.shift()<br>df[&#39;Shifted_Close&#39;] = df.Close.shift()<br>#ignore the warning</pre><p>Defining Trading Logic:</p><pre>position = False<br>buydates, selldates = [],[]<br>buyprices, sellprices = [],[]<br><br>for index,row in df.iterrows():<br>    if not position and row[&#39;Signal&#39;] ==&#39;Buy&#39;:<br>        buydates.append(index)<br>        buyprices.append(row.Open)<br>        position = True<br>    <br>    if position: <br>        if row[&#39;Signal&#39;] == &#39;Sell&#39; or row.Shifted_Close &lt; 0.95 * buyprices[-1]:<br>            #0.95 is stop loss means 5% stop loss*** <br>            selldates.append(index)<br>            sellprices.append(row.Open)<br>            position = False</pre><p>Plotting the resultls</p><pre>plt.figure(figsize=(10,5))<br>plt.plot(df.Close)<br>plt.scatter(df.loc[buydates].index, df.loc[buydates].Close, marker = &#39;^&#39; ,c=&#39;g&#39;)<br>plt.scatter(df.loc[selldates].index, df.loc[selldates].Close, marker = &#39;^&#39; ,c=&#39;r&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*U8if1TCkJGNI12LClrkn9A.png" /></figure><p>Calculating the % of returns</p><pre>(pd.Series([(sell-buy)/ buy for sell,buy in zip(sellprices,buyprices)])+1).prod()-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*D2vylxB0aFIBMcFTQIiBXw.png" /><figcaption>0.3181 = 31.8% return</figcaption></figure><p>Compiling all the steps under one function</p><pre>def Test_MeanReversion(ticker = &#39;&#39;, date_start=&#39;2018-01-01&#39;):<br>    df = yf.download(ticker,date_start)<br>    time.sleep(2)<br>    df[&#39;ma_20&#39;] = df.Close.rolling(20).mean()<br>    df[&#39;vol&#39;] = df.Close.rolling(20).std()<br>    df[&#39;upper_bb&#39;] = df.ma_20 + (2*df.vol)<br>    df[&#39;lower_bb&#39;] = df.ma_20 - (2*df.vol)<br>    df[&#39;rsi&#39;] = ta.momentum.rsi(df.Close)<br>    conditions = [(df.rsi&lt;30) &amp; (df.Close&lt;df.lower_bb),<br>              (df.rsi&gt;70) &amp; (df.Close &gt; df.upper_bb)]<br>    choises = [&#39;Buy&#39;, &#39;Sell&#39;]<br>    df[&#39;Signal&#39;] = np.select(conditions,choises)<br>    df = df.dropna()<br>    <br>    df.Signal = df.Signal.shift()<br>    df[&#39;Shifted_Close&#39;] = df.Close.shift()<br>    position = False<br>    buydates, selldates = [],[]<br>    buyprices, sellprices = [],[]<br><br>    for index,row in df.iterrows():<br>        if not position and row[&#39;Signal&#39;] ==&#39;Buy&#39;:<br>            buydates.append(index)<br>            buyprices.append(row.Open)<br>            position = True<br><br>        if position: <br>            if row[&#39;Signal&#39;] == &#39;Sell&#39; or row.Shifted_Close &lt; 0.90 * buyprices[-1]:<br>                selldates.append(index)<br>                sellprices.append(row.Open)<br>                position = False<br>    #plt.figure(figsize=(10,5))<br>    #plt.plot(df.Close)<br>    #plt.scatter(df.loc[buydates].index, df.loc[buydates].Close, marker = &#39;^&#39; ,c=&#39;g&#39;)<br>    #plt.scatter(df.loc[selldates].index, df.loc[selldates].Close, marker = &#39;^&#39; ,c=&#39;r&#39;)<br>    return (pd.Series([(sell-buy)/ buy for sell,buy in zip(sellprices,buyprices)])+1).prod()-1</pre><h3><strong>Testing the strategy over India’s top 50 Stocks!</strong></h3><p>Initiating return and ticker columns</p><pre>ret = []<br>tick_list = []</pre><p>Getting the Nifty50/Nifty100 tickers from NSE website</p><pre>url = &quot;https://www1.nseindia.com/content/indices/ind_niftysmallcap50list.csv&quot;<br><br>#for nifty100 use this <br>#url = &quot;https://archives.nseindia.com/content/indices/ind_nifty100list.csv&quot;<br><br>ticker_list = pd.read_csv(url)<br>ticker_list[&#39;Symbol&#39;] = ticker_list[&#39;Symbol&#39;] + &#39;.NS&#39;</pre><p>Download the data and test over mean reversion strategy</p><pre>count = 0<br>for tick in ticker_list[&#39;Symbol&#39;]:<br>    try:<br>        ret.append(Test_MeanReversion(tick))<br>        tick_list.append(tick)<br>        count = count+1<br>        print(count)<br>    except Exception as e:<br>            print (e)<br>            print(f&quot;Could not gather data on {tick}&quot;)</pre><p>Converting the data into dataframe</p><pre>rent = pd.DataFrame(ret)<br>tick_list = pd.DataFrame(tick_list)<br>Cum_return = pd.concat([rent,tick_list], axis=1)<br>Cum_return.set_axis([&#39;returns&#39;, &#39;symbol&#39;], axis=&#39;columns&#39;, inplace=True)</pre><p>Box Plotting The data to check if this Strategy is of any good</p><pre>import plotly.express as px<br><br>fig = px.box(Cum_return.returns)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*bq49UMzqNARFqC9zotQR2Q.png" /></figure><p>According to this box plot this is not a good strategy with above used values , But can be fixed by changing the stop loss according to volatility!</p><p>Thanks for reading<br>For error correction or any query or small talks too,<br>Msg me on: <a href="https://www.linkedin.com/in/yashaswa-varshney/">https://www.linkedin.com/in/yashaswa-varshney/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e2dc2e23483" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calculate P/E of Nifty in Python]]></title>
            <link>https://medium.com/@yashaswa/is-nifty-is-still-over-valued-5c0ac8df2bf9?source=rss-121ee62fb5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c0ac8df2bf9</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[nifty]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Yashaswa Varshney]]></dc:creator>
            <pubDate>Mon, 16 May 2022 13:00:42 GMT</pubDate>
            <atom:updated>2022-05-17T12:35:47.949Z</atom:updated>
            <content:encoded><![CDATA[<p>The Nifty has come back to 23 after a all time high peak of 30 in October, According to Money Control, In an extreme worst-case scenario, the Nifty will find support at 20 PE, which would be approx 15,000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScOi6ZAmEbLBzcarPXjjpA.png" /><figcaption>Nifty P/E: June 2021 — May 2022(present date)</figcaption></figure><p>As we can see the down trend isn’t over yet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Qya3YuMAwBRG77-g-msYQ.png" /><figcaption>Nifty P/B: June 2021 — May 2022(present date)</figcaption></figure><p>P/B is also jumping in the same same range for months.</p><p>to check the real time P/E and P/B ratio of Nifty I have made a simple program using NSE data with the help of amazing library <a href="https://github.com/swapniljariwala/nsepy">nsepy</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61e6b8d4d2b10e1ed2b8b40445365778/href">https://medium.com/media/61e6b8d4d2b10e1ed2b8b40445365778/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c0ac8df2bf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>